1use super::{ignore::IgnoreStack, DiagnosticSummary};
2use crate::{copy_recursive, ProjectEntryId, RemoveOptions};
3use ::ignore::gitignore::{Gitignore, GitignoreBuilder};
4use anyhow::{anyhow, Context, Result};
5use client::{proto, Client};
6use clock::ReplicaId;
7use collections::{HashMap, VecDeque};
8use fs::LineEnding;
9use fs::{repository::GitRepository, Fs};
10use futures::{
11 channel::{
12 mpsc::{self, UnboundedSender},
13 oneshot,
14 },
15 Stream, StreamExt,
16};
17use fuzzy::CharBag;
18use git::{DOT_GIT, GITIGNORE};
19use gpui::{
20 executor, AppContext, AsyncAppContext, Entity, ModelContext, ModelHandle, MutableAppContext,
21 Task,
22};
23use language::File as _;
24use language::{
25 proto::{
26 deserialize_fingerprint, deserialize_version, serialize_fingerprint, serialize_line_ending,
27 serialize_version,
28 },
29 Buffer, DiagnosticEntry, PointUtf16, Rope, RopeFingerprint, Unclipped,
30};
31use parking_lot::Mutex;
32use postage::{
33 prelude::{Sink as _, Stream as _},
34 watch,
35};
36use smol::channel::{self, Sender};
37use std::{
38 any::Any,
39 cmp::{self, Ordering},
40 convert::TryFrom,
41 ffi::OsStr,
42 fmt,
43 future::Future,
44 mem,
45 ops::{Deref, DerefMut},
46 path::{Path, PathBuf},
47 sync::{atomic::AtomicUsize, Arc},
48 task::Poll,
49 time::{Duration, SystemTime},
50};
51use sum_tree::{Bias, Edit, SeekTarget, SumTree, TreeMap, TreeSet};
52use util::paths::HOME;
53use util::{ResultExt, TryFutureExt};
54
55#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash, PartialOrd, Ord)]
56pub struct WorktreeId(usize);
57
58#[allow(clippy::large_enum_variant)]
59pub enum Worktree {
60 Local(LocalWorktree),
61 Remote(RemoteWorktree),
62}
63
64pub struct LocalWorktree {
65 snapshot: LocalSnapshot,
66 background_snapshot: Arc<Mutex<LocalSnapshot>>,
67 background_changes: Arc<Mutex<HashMap<Arc<Path>, PathChange>>>,
68 last_scan_state_rx: watch::Receiver<ScanState>,
69 _background_scanner_task: Task<()>,
70 poll_task: Option<Task<()>>,
71 share: Option<ShareState>,
72 diagnostics: HashMap<Arc<Path>, Vec<DiagnosticEntry<Unclipped<PointUtf16>>>>,
73 diagnostic_summaries: TreeMap<PathKey, DiagnosticSummary>,
74 client: Arc<Client>,
75 fs: Arc<dyn Fs>,
76 visible: bool,
77}
78
79pub struct RemoteWorktree {
80 pub snapshot: Snapshot,
81 pub(crate) background_snapshot: Arc<Mutex<Snapshot>>,
82 project_id: u64,
83 client: Arc<Client>,
84 updates_tx: Option<UnboundedSender<proto::UpdateWorktree>>,
85 snapshot_subscriptions: VecDeque<(usize, oneshot::Sender<()>)>,
86 replica_id: ReplicaId,
87 diagnostic_summaries: TreeMap<PathKey, DiagnosticSummary>,
88 visible: bool,
89 disconnected: bool,
90}
91
92#[derive(Clone)]
93pub struct Snapshot {
94 id: WorktreeId,
95 abs_path: Arc<Path>,
96 root_name: String,
97 root_char_bag: CharBag,
98 entries_by_path: SumTree<Entry>,
99 entries_by_id: SumTree<PathEntry>,
100 scan_id: usize,
101 completed_scan_id: usize,
102}
103
104#[derive(Clone)]
105pub struct GitRepositoryEntry {
106 pub(crate) repo: Arc<Mutex<dyn GitRepository>>,
107
108 pub(crate) scan_id: usize,
109 // Path to folder containing the .git file or directory
110 pub(crate) content_path: Arc<Path>,
111 // Path to the actual .git folder.
112 // Note: if .git is a file, this points to the folder indicated by the .git file
113 pub(crate) git_dir_path: Arc<Path>,
114}
115
116impl std::fmt::Debug for GitRepositoryEntry {
117 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
118 f.debug_struct("GitRepositoryEntry")
119 .field("content_path", &self.content_path)
120 .field("git_dir_path", &self.git_dir_path)
121 .field("libgit_repository", &"LibGitRepository")
122 .finish()
123 }
124}
125
126pub struct LocalSnapshot {
127 ignores_by_parent_abs_path: HashMap<Arc<Path>, (Arc<Gitignore>, usize)>,
128 git_repositories: Vec<GitRepositoryEntry>,
129 removed_entry_ids: HashMap<u64, ProjectEntryId>,
130 next_entry_id: Arc<AtomicUsize>,
131 snapshot: Snapshot,
132}
133
134impl Clone for LocalSnapshot {
135 fn clone(&self) -> Self {
136 Self {
137 ignores_by_parent_abs_path: self.ignores_by_parent_abs_path.clone(),
138 git_repositories: self.git_repositories.iter().cloned().collect(),
139 removed_entry_ids: self.removed_entry_ids.clone(),
140 next_entry_id: self.next_entry_id.clone(),
141 snapshot: self.snapshot.clone(),
142 }
143 }
144}
145
146impl Deref for LocalSnapshot {
147 type Target = Snapshot;
148
149 fn deref(&self) -> &Self::Target {
150 &self.snapshot
151 }
152}
153
154impl DerefMut for LocalSnapshot {
155 fn deref_mut(&mut self) -> &mut Self::Target {
156 &mut self.snapshot
157 }
158}
159
160#[derive(Clone, Debug)]
161enum ScanState {
162 Idle,
163 /// The worktree is performing its initial scan of the filesystem.
164 Initializing,
165 /// The worktree is updating in response to filesystem events.
166 Updating,
167 Err(Arc<anyhow::Error>),
168}
169
170struct ShareState {
171 project_id: u64,
172 snapshots_tx: watch::Sender<LocalSnapshot>,
173 resume_updates: watch::Sender<()>,
174 _maintain_remote_snapshot: Task<Option<()>>,
175}
176
177pub enum Event {
178 UpdatedEntries(HashMap<Arc<Path>, PathChange>),
179 UpdatedGitRepositories(Vec<GitRepositoryEntry>),
180}
181
182impl Entity for Worktree {
183 type Event = Event;
184}
185
186impl Worktree {
187 pub async fn local(
188 client: Arc<Client>,
189 path: impl Into<Arc<Path>>,
190 visible: bool,
191 fs: Arc<dyn Fs>,
192 next_entry_id: Arc<AtomicUsize>,
193 cx: &mut AsyncAppContext,
194 ) -> Result<ModelHandle<Self>> {
195 // After determining whether the root entry is a file or a directory, populate the
196 // snapshot's "root name", which will be used for the purpose of fuzzy matching.
197 let abs_path = path.into();
198 let metadata = fs
199 .metadata(&abs_path)
200 .await
201 .context("failed to stat worktree path")?;
202
203 Ok(cx.add_model(move |cx: &mut ModelContext<Worktree>| {
204 let root_name = abs_path
205 .file_name()
206 .map_or(String::new(), |f| f.to_string_lossy().to_string());
207
208 let mut snapshot = LocalSnapshot {
209 ignores_by_parent_abs_path: Default::default(),
210 git_repositories: Default::default(),
211 removed_entry_ids: Default::default(),
212 next_entry_id,
213 snapshot: Snapshot {
214 id: WorktreeId::from_usize(cx.model_id()),
215 abs_path: abs_path.clone(),
216 root_name: root_name.clone(),
217 root_char_bag: root_name.chars().map(|c| c.to_ascii_lowercase()).collect(),
218 entries_by_path: Default::default(),
219 entries_by_id: Default::default(),
220 scan_id: 0,
221 completed_scan_id: 0,
222 },
223 };
224
225 if let Some(metadata) = metadata {
226 snapshot.insert_entry(
227 Entry::new(
228 Arc::from(Path::new("")),
229 &metadata,
230 &snapshot.next_entry_id,
231 snapshot.root_char_bag,
232 ),
233 fs.as_ref(),
234 );
235 }
236
237 let (scan_states_tx, mut scan_states_rx) = mpsc::unbounded();
238 let (mut last_scan_state_tx, last_scan_state_rx) =
239 watch::channel_with(ScanState::Initializing);
240 let background_snapshot = Arc::new(Mutex::new(snapshot.clone()));
241 let background_changes = Arc::new(Mutex::new(HashMap::default()));
242
243 cx.spawn_weak(|this, mut cx| async move {
244 while let Some(scan_state) = scan_states_rx.next().await {
245 if let Some(this) = this.upgrade(&cx) {
246 last_scan_state_tx.blocking_send(scan_state).ok();
247 this.update(&mut cx, |this, cx| {
248 this.as_local_mut().unwrap().poll_snapshot(false, cx)
249 });
250 } else {
251 break;
252 }
253 }
254 })
255 .detach();
256
257 Worktree::Local(LocalWorktree {
258 _background_scanner_task: cx.background().spawn({
259 let fs = fs.clone();
260 let background_snapshot = background_snapshot.clone();
261 let background_changes = background_changes.clone();
262 let background = cx.background().clone();
263 async move {
264 let events = fs.watch(&abs_path, Duration::from_millis(100)).await;
265 let scanner = BackgroundScanner::new(
266 background_snapshot,
267 background_changes,
268 scan_states_tx,
269 fs,
270 background,
271 );
272 scanner.run(events).await;
273 }
274 }),
275 snapshot,
276 background_snapshot,
277 background_changes,
278 last_scan_state_rx,
279 share: None,
280 poll_task: None,
281 diagnostics: Default::default(),
282 diagnostic_summaries: Default::default(),
283 client,
284 fs,
285 visible,
286 })
287 }))
288 }
289
290 pub fn remote(
291 project_remote_id: u64,
292 replica_id: ReplicaId,
293 worktree: proto::WorktreeMetadata,
294 client: Arc<Client>,
295 cx: &mut MutableAppContext,
296 ) -> ModelHandle<Self> {
297 cx.add_model(|cx: &mut ModelContext<Self>| {
298 let snapshot = Snapshot {
299 id: WorktreeId(worktree.id as usize),
300 abs_path: Arc::from(PathBuf::from(worktree.abs_path)),
301 root_name: worktree.root_name.clone(),
302 root_char_bag: worktree
303 .root_name
304 .chars()
305 .map(|c| c.to_ascii_lowercase())
306 .collect(),
307 entries_by_path: Default::default(),
308 entries_by_id: Default::default(),
309 scan_id: 0,
310 completed_scan_id: 0,
311 };
312
313 let (updates_tx, mut updates_rx) = mpsc::unbounded();
314 let background_snapshot = Arc::new(Mutex::new(snapshot.clone()));
315 let (mut snapshot_updated_tx, mut snapshot_updated_rx) = watch::channel();
316
317 cx.background()
318 .spawn({
319 let background_snapshot = background_snapshot.clone();
320 async move {
321 while let Some(update) = updates_rx.next().await {
322 if let Err(error) =
323 background_snapshot.lock().apply_remote_update(update)
324 {
325 log::error!("error applying worktree update: {}", error);
326 }
327 snapshot_updated_tx.send(()).await.ok();
328 }
329 }
330 })
331 .detach();
332
333 cx.spawn_weak(|this, mut cx| async move {
334 while (snapshot_updated_rx.recv().await).is_some() {
335 if let Some(this) = this.upgrade(&cx) {
336 this.update(&mut cx, |this, cx| {
337 let this = this.as_remote_mut().unwrap();
338 this.poll_snapshot(cx);
339 while let Some((scan_id, _)) = this.snapshot_subscriptions.front() {
340 if this.observed_snapshot(*scan_id) {
341 let (_, tx) = this.snapshot_subscriptions.pop_front().unwrap();
342 let _ = tx.send(());
343 } else {
344 break;
345 }
346 }
347 });
348 } else {
349 break;
350 }
351 }
352 })
353 .detach();
354
355 Worktree::Remote(RemoteWorktree {
356 project_id: project_remote_id,
357 replica_id,
358 snapshot: snapshot.clone(),
359 background_snapshot,
360 updates_tx: Some(updates_tx),
361 snapshot_subscriptions: Default::default(),
362 client: client.clone(),
363 diagnostic_summaries: Default::default(),
364 visible: worktree.visible,
365 disconnected: false,
366 })
367 })
368 }
369
370 pub fn as_local(&self) -> Option<&LocalWorktree> {
371 if let Worktree::Local(worktree) = self {
372 Some(worktree)
373 } else {
374 None
375 }
376 }
377
378 pub fn as_remote(&self) -> Option<&RemoteWorktree> {
379 if let Worktree::Remote(worktree) = self {
380 Some(worktree)
381 } else {
382 None
383 }
384 }
385
386 pub fn as_local_mut(&mut self) -> Option<&mut LocalWorktree> {
387 if let Worktree::Local(worktree) = self {
388 Some(worktree)
389 } else {
390 None
391 }
392 }
393
394 pub fn as_remote_mut(&mut self) -> Option<&mut RemoteWorktree> {
395 if let Worktree::Remote(worktree) = self {
396 Some(worktree)
397 } else {
398 None
399 }
400 }
401
402 pub fn is_local(&self) -> bool {
403 matches!(self, Worktree::Local(_))
404 }
405
406 pub fn is_remote(&self) -> bool {
407 !self.is_local()
408 }
409
410 pub fn snapshot(&self) -> Snapshot {
411 match self {
412 Worktree::Local(worktree) => worktree.snapshot().snapshot,
413 Worktree::Remote(worktree) => worktree.snapshot(),
414 }
415 }
416
417 pub fn scan_id(&self) -> usize {
418 match self {
419 Worktree::Local(worktree) => worktree.snapshot.scan_id,
420 Worktree::Remote(worktree) => worktree.snapshot.scan_id,
421 }
422 }
423
424 pub fn completed_scan_id(&self) -> usize {
425 match self {
426 Worktree::Local(worktree) => worktree.snapshot.completed_scan_id,
427 Worktree::Remote(worktree) => worktree.snapshot.completed_scan_id,
428 }
429 }
430
431 pub fn is_visible(&self) -> bool {
432 match self {
433 Worktree::Local(worktree) => worktree.visible,
434 Worktree::Remote(worktree) => worktree.visible,
435 }
436 }
437
438 pub fn replica_id(&self) -> ReplicaId {
439 match self {
440 Worktree::Local(_) => 0,
441 Worktree::Remote(worktree) => worktree.replica_id,
442 }
443 }
444
445 pub fn diagnostic_summaries(
446 &self,
447 ) -> impl Iterator<Item = (Arc<Path>, DiagnosticSummary)> + '_ {
448 match self {
449 Worktree::Local(worktree) => &worktree.diagnostic_summaries,
450 Worktree::Remote(worktree) => &worktree.diagnostic_summaries,
451 }
452 .iter()
453 .map(|(path, summary)| (path.0.clone(), *summary))
454 }
455
456 pub fn abs_path(&self) -> Arc<Path> {
457 match self {
458 Worktree::Local(worktree) => worktree.abs_path.clone(),
459 Worktree::Remote(worktree) => worktree.abs_path.clone(),
460 }
461 }
462}
463
464impl LocalWorktree {
465 pub fn contains_abs_path(&self, path: &Path) -> bool {
466 path.starts_with(&self.abs_path)
467 }
468
469 fn absolutize(&self, path: &Path) -> PathBuf {
470 if path.file_name().is_some() {
471 self.abs_path.join(path)
472 } else {
473 self.abs_path.to_path_buf()
474 }
475 }
476
477 pub(crate) fn load_buffer(
478 &mut self,
479 path: &Path,
480 cx: &mut ModelContext<Worktree>,
481 ) -> Task<Result<ModelHandle<Buffer>>> {
482 let path = Arc::from(path);
483 cx.spawn(move |this, mut cx| async move {
484 let (file, contents, diff_base) = this
485 .update(&mut cx, |t, cx| t.as_local().unwrap().load(&path, cx))
486 .await?;
487 Ok(cx.add_model(|cx| {
488 let mut buffer = Buffer::from_file(0, contents, diff_base, Arc::new(file), cx);
489 buffer.git_diff_recalc(cx);
490 buffer
491 }))
492 })
493 }
494
495 pub fn diagnostics_for_path(
496 &self,
497 path: &Path,
498 ) -> Option<Vec<DiagnosticEntry<Unclipped<PointUtf16>>>> {
499 self.diagnostics.get(path).cloned()
500 }
501
502 pub fn update_diagnostics(
503 &mut self,
504 language_server_id: usize,
505 worktree_path: Arc<Path>,
506 diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
507 _: &mut ModelContext<Worktree>,
508 ) -> Result<bool> {
509 self.diagnostics.remove(&worktree_path);
510 let old_summary = self
511 .diagnostic_summaries
512 .remove(&PathKey(worktree_path.clone()))
513 .unwrap_or_default();
514 let new_summary = DiagnosticSummary::new(language_server_id, &diagnostics);
515 if !new_summary.is_empty() {
516 self.diagnostic_summaries
517 .insert(PathKey(worktree_path.clone()), new_summary);
518 self.diagnostics.insert(worktree_path.clone(), diagnostics);
519 }
520
521 let updated = !old_summary.is_empty() || !new_summary.is_empty();
522 if updated {
523 if let Some(share) = self.share.as_ref() {
524 self.client
525 .send(proto::UpdateDiagnosticSummary {
526 project_id: share.project_id,
527 worktree_id: self.id().to_proto(),
528 summary: Some(proto::DiagnosticSummary {
529 path: worktree_path.to_string_lossy().to_string(),
530 language_server_id: language_server_id as u64,
531 error_count: new_summary.error_count as u32,
532 warning_count: new_summary.warning_count as u32,
533 }),
534 })
535 .log_err();
536 }
537 }
538
539 Ok(updated)
540 }
541
542 fn poll_snapshot(&mut self, force: bool, cx: &mut ModelContext<Worktree>) {
543 self.poll_task.take();
544
545 match self.last_scan_state_rx.borrow().clone() {
546 ScanState::Idle => {
547 let new_snapshot = self.background_snapshot.lock().clone();
548 let changes = mem::take(&mut *self.background_changes.lock());
549 let updated_repos = Self::changed_repos(
550 &self.snapshot.git_repositories,
551 &new_snapshot.git_repositories,
552 );
553 self.snapshot = new_snapshot;
554
555 if let Some(share) = self.share.as_mut() {
556 *share.snapshots_tx.borrow_mut() = self.snapshot.clone();
557 }
558
559 cx.emit(Event::UpdatedEntries(changes));
560
561 if !updated_repos.is_empty() {
562 cx.emit(Event::UpdatedGitRepositories(updated_repos));
563 }
564 }
565
566 ScanState::Initializing => {
567 let is_fake_fs = self.fs.is_fake();
568
569 let new_snapshot = self.background_snapshot.lock().clone();
570 let updated_repos = Self::changed_repos(
571 &self.snapshot.git_repositories,
572 &new_snapshot.git_repositories,
573 );
574 self.snapshot = new_snapshot;
575
576 self.poll_task = Some(cx.spawn_weak(|this, mut cx| async move {
577 if is_fake_fs {
578 #[cfg(any(test, feature = "test-support"))]
579 cx.background().simulate_random_delay().await;
580 } else {
581 smol::Timer::after(Duration::from_millis(100)).await;
582 }
583 if let Some(this) = this.upgrade(&cx) {
584 this.update(&mut cx, |this, cx| {
585 this.as_local_mut().unwrap().poll_snapshot(false, cx)
586 });
587 }
588 }));
589
590 if !updated_repos.is_empty() {
591 cx.emit(Event::UpdatedGitRepositories(updated_repos));
592 }
593 }
594
595 _ => {
596 if force {
597 self.snapshot = self.background_snapshot.lock().clone();
598 }
599 }
600 }
601
602 cx.notify();
603 }
604
605 fn changed_repos(
606 old_repos: &[GitRepositoryEntry],
607 new_repos: &[GitRepositoryEntry],
608 ) -> Vec<GitRepositoryEntry> {
609 fn diff<'a>(
610 a: &'a [GitRepositoryEntry],
611 b: &'a [GitRepositoryEntry],
612 updated: &mut HashMap<&'a Path, GitRepositoryEntry>,
613 ) {
614 for a_repo in a {
615 let matched = b.iter().find(|b_repo| {
616 a_repo.git_dir_path == b_repo.git_dir_path && a_repo.scan_id == b_repo.scan_id
617 });
618
619 if matched.is_none() {
620 updated.insert(a_repo.git_dir_path.as_ref(), a_repo.clone());
621 }
622 }
623 }
624
625 let mut updated = HashMap::<&Path, GitRepositoryEntry>::default();
626
627 diff(old_repos, new_repos, &mut updated);
628 diff(new_repos, old_repos, &mut updated);
629
630 updated.into_values().collect()
631 }
632
633 pub fn scan_complete(&self) -> impl Future<Output = ()> {
634 let mut scan_state_rx = self.last_scan_state_rx.clone();
635 async move {
636 let mut scan_state = Some(scan_state_rx.borrow().clone());
637 while let Some(ScanState::Initializing | ScanState::Updating) = scan_state {
638 scan_state = scan_state_rx.recv().await;
639 }
640 }
641 }
642
643 pub fn snapshot(&self) -> LocalSnapshot {
644 self.snapshot.clone()
645 }
646
647 pub fn metadata_proto(&self) -> proto::WorktreeMetadata {
648 proto::WorktreeMetadata {
649 id: self.id().to_proto(),
650 root_name: self.root_name().to_string(),
651 visible: self.visible,
652 abs_path: self.abs_path().as_os_str().to_string_lossy().into(),
653 }
654 }
655
656 fn load(
657 &self,
658 path: &Path,
659 cx: &mut ModelContext<Worktree>,
660 ) -> Task<Result<(File, String, Option<String>)>> {
661 let handle = cx.handle();
662 let path = Arc::from(path);
663 let abs_path = self.absolutize(&path);
664 let fs = self.fs.clone();
665 let snapshot = self.snapshot();
666
667 cx.spawn(|this, mut cx| async move {
668 let text = fs.load(&abs_path).await?;
669
670 let diff_base = if let Some(repo) = snapshot.repo_for(&path) {
671 if let Ok(repo_relative) = path.strip_prefix(repo.content_path) {
672 let repo_relative = repo_relative.to_owned();
673 cx.background()
674 .spawn(async move { repo.repo.lock().load_index_text(&repo_relative) })
675 .await
676 } else {
677 None
678 }
679 } else {
680 None
681 };
682
683 // Eagerly populate the snapshot with an updated entry for the loaded file
684 let entry = this
685 .update(&mut cx, |this, cx| {
686 this.as_local()
687 .unwrap()
688 .refresh_entry(path, abs_path, None, cx)
689 })
690 .await?;
691
692 Ok((
693 File {
694 entry_id: entry.id,
695 worktree: handle,
696 path: entry.path,
697 mtime: entry.mtime,
698 is_local: true,
699 is_deleted: false,
700 },
701 text,
702 diff_base,
703 ))
704 })
705 }
706
707 pub fn save_buffer(
708 &self,
709 buffer_handle: ModelHandle<Buffer>,
710 path: Arc<Path>,
711 has_changed_file: bool,
712 cx: &mut ModelContext<Worktree>,
713 ) -> Task<Result<(clock::Global, RopeFingerprint, SystemTime)>> {
714 let handle = cx.handle();
715 let buffer = buffer_handle.read(cx);
716
717 let rpc = self.client.clone();
718 let buffer_id = buffer.remote_id();
719 let project_id = self.share.as_ref().map(|share| share.project_id);
720
721 let text = buffer.as_rope().clone();
722 let fingerprint = text.fingerprint();
723 let version = buffer.version();
724 let save = self.write_file(path, text, buffer.line_ending(), cx);
725
726 cx.as_mut().spawn(|mut cx| async move {
727 let entry = save.await?;
728
729 if has_changed_file {
730 let new_file = Arc::new(File {
731 entry_id: entry.id,
732 worktree: handle,
733 path: entry.path,
734 mtime: entry.mtime,
735 is_local: true,
736 is_deleted: false,
737 });
738
739 if let Some(project_id) = project_id {
740 rpc.send(proto::UpdateBufferFile {
741 project_id,
742 buffer_id,
743 file: Some(new_file.to_proto()),
744 })
745 .log_err();
746 }
747
748 buffer_handle.update(&mut cx, |buffer, cx| {
749 if has_changed_file {
750 buffer.file_updated(new_file, cx).detach();
751 }
752 });
753 }
754
755 if let Some(project_id) = project_id {
756 rpc.send(proto::BufferSaved {
757 project_id,
758 buffer_id,
759 version: serialize_version(&version),
760 mtime: Some(entry.mtime.into()),
761 fingerprint: serialize_fingerprint(fingerprint),
762 })?;
763 }
764
765 buffer_handle.update(&mut cx, |buffer, cx| {
766 buffer.did_save(version.clone(), fingerprint, entry.mtime, cx);
767 });
768
769 Ok((version, fingerprint, entry.mtime))
770 })
771 }
772
773 pub fn create_entry(
774 &self,
775 path: impl Into<Arc<Path>>,
776 is_dir: bool,
777 cx: &mut ModelContext<Worktree>,
778 ) -> Task<Result<Entry>> {
779 self.write_entry_internal(
780 path,
781 if is_dir {
782 None
783 } else {
784 Some(Default::default())
785 },
786 cx,
787 )
788 }
789
790 pub fn write_file(
791 &self,
792 path: impl Into<Arc<Path>>,
793 text: Rope,
794 line_ending: LineEnding,
795 cx: &mut ModelContext<Worktree>,
796 ) -> Task<Result<Entry>> {
797 self.write_entry_internal(path, Some((text, line_ending)), cx)
798 }
799
800 pub fn delete_entry(
801 &self,
802 entry_id: ProjectEntryId,
803 cx: &mut ModelContext<Worktree>,
804 ) -> Option<Task<Result<()>>> {
805 let entry = self.entry_for_id(entry_id)?.clone();
806 let abs_path = self.absolutize(&entry.path);
807 let delete = cx.background().spawn({
808 let fs = self.fs.clone();
809 let abs_path = abs_path;
810 async move {
811 if entry.is_file() {
812 fs.remove_file(&abs_path, Default::default()).await
813 } else {
814 fs.remove_dir(
815 &abs_path,
816 RemoveOptions {
817 recursive: true,
818 ignore_if_not_exists: false,
819 },
820 )
821 .await
822 }
823 }
824 });
825
826 Some(cx.spawn(|this, mut cx| async move {
827 delete.await?;
828 this.update(&mut cx, |this, cx| {
829 let this = this.as_local_mut().unwrap();
830 {
831 let mut snapshot = this.background_snapshot.lock();
832 snapshot.delete_entry(entry_id);
833 }
834 this.poll_snapshot(true, cx);
835 });
836 Ok(())
837 }))
838 }
839
840 pub fn rename_entry(
841 &self,
842 entry_id: ProjectEntryId,
843 new_path: impl Into<Arc<Path>>,
844 cx: &mut ModelContext<Worktree>,
845 ) -> Option<Task<Result<Entry>>> {
846 let old_path = self.entry_for_id(entry_id)?.path.clone();
847 let new_path = new_path.into();
848 let abs_old_path = self.absolutize(&old_path);
849 let abs_new_path = self.absolutize(new_path.as_ref());
850 let rename = cx.background().spawn({
851 let fs = self.fs.clone();
852 let abs_new_path = abs_new_path.clone();
853 async move {
854 fs.rename(&abs_old_path, &abs_new_path, Default::default())
855 .await
856 }
857 });
858
859 Some(cx.spawn(|this, mut cx| async move {
860 rename.await?;
861 let entry = this
862 .update(&mut cx, |this, cx| {
863 this.as_local_mut().unwrap().refresh_entry(
864 new_path.clone(),
865 abs_new_path,
866 Some(old_path),
867 cx,
868 )
869 })
870 .await?;
871 Ok(entry)
872 }))
873 }
874
875 pub fn copy_entry(
876 &self,
877 entry_id: ProjectEntryId,
878 new_path: impl Into<Arc<Path>>,
879 cx: &mut ModelContext<Worktree>,
880 ) -> Option<Task<Result<Entry>>> {
881 let old_path = self.entry_for_id(entry_id)?.path.clone();
882 let new_path = new_path.into();
883 let abs_old_path = self.absolutize(&old_path);
884 let abs_new_path = self.absolutize(&new_path);
885 let copy = cx.background().spawn({
886 let fs = self.fs.clone();
887 let abs_new_path = abs_new_path.clone();
888 async move {
889 copy_recursive(
890 fs.as_ref(),
891 &abs_old_path,
892 &abs_new_path,
893 Default::default(),
894 )
895 .await
896 }
897 });
898
899 Some(cx.spawn(|this, mut cx| async move {
900 copy.await?;
901 let entry = this
902 .update(&mut cx, |this, cx| {
903 this.as_local_mut().unwrap().refresh_entry(
904 new_path.clone(),
905 abs_new_path,
906 None,
907 cx,
908 )
909 })
910 .await?;
911 Ok(entry)
912 }))
913 }
914
915 fn write_entry_internal(
916 &self,
917 path: impl Into<Arc<Path>>,
918 text_if_file: Option<(Rope, LineEnding)>,
919 cx: &mut ModelContext<Worktree>,
920 ) -> Task<Result<Entry>> {
921 let path = path.into();
922 let abs_path = self.absolutize(&path);
923 let write = cx.background().spawn({
924 let fs = self.fs.clone();
925 let abs_path = abs_path.clone();
926 async move {
927 if let Some((text, line_ending)) = text_if_file {
928 fs.save(&abs_path, &text, line_ending).await
929 } else {
930 fs.create_dir(&abs_path).await
931 }
932 }
933 });
934
935 cx.spawn(|this, mut cx| async move {
936 write.await?;
937 let entry = this
938 .update(&mut cx, |this, cx| {
939 this.as_local_mut()
940 .unwrap()
941 .refresh_entry(path, abs_path, None, cx)
942 })
943 .await?;
944 Ok(entry)
945 })
946 }
947
948 fn refresh_entry(
949 &self,
950 path: Arc<Path>,
951 abs_path: PathBuf,
952 old_path: Option<Arc<Path>>,
953 cx: &mut ModelContext<Worktree>,
954 ) -> Task<Result<Entry>> {
955 let fs = self.fs.clone();
956 let root_char_bag;
957 let next_entry_id;
958 {
959 let snapshot = self.background_snapshot.lock();
960 root_char_bag = snapshot.root_char_bag;
961 next_entry_id = snapshot.next_entry_id.clone();
962 }
963 cx.spawn_weak(|this, mut cx| async move {
964 let metadata = fs
965 .metadata(&abs_path)
966 .await?
967 .ok_or_else(|| anyhow!("could not read saved file metadata"))?;
968 let this = this
969 .upgrade(&cx)
970 .ok_or_else(|| anyhow!("worktree was dropped"))?;
971 this.update(&mut cx, |this, cx| {
972 let this = this.as_local_mut().unwrap();
973 let inserted_entry;
974 {
975 let mut snapshot = this.background_snapshot.lock();
976 let mut changes = this.background_changes.lock();
977 let mut entry = Entry::new(path, &metadata, &next_entry_id, root_char_bag);
978 entry.is_ignored = snapshot
979 .ignore_stack_for_abs_path(&abs_path, entry.is_dir())
980 .is_abs_path_ignored(&abs_path, entry.is_dir());
981 if let Some(old_path) = old_path {
982 snapshot.remove_path(&old_path);
983 changes.insert(old_path.clone(), PathChange::Removed);
984 }
985 snapshot.scan_started();
986 let exists = snapshot.entry_for_path(&entry.path).is_some();
987 inserted_entry = snapshot.insert_entry(entry, fs.as_ref());
988 changes.insert(
989 inserted_entry.path.clone(),
990 if exists {
991 PathChange::Updated
992 } else {
993 PathChange::Added
994 },
995 );
996 snapshot.scan_completed();
997 }
998 this.poll_snapshot(true, cx);
999 Ok(inserted_entry)
1000 })
1001 })
1002 }
1003
1004 pub fn share(&mut self, project_id: u64, cx: &mut ModelContext<Worktree>) -> Task<Result<()>> {
1005 let (share_tx, share_rx) = oneshot::channel();
1006
1007 if let Some(share) = self.share.as_mut() {
1008 let _ = share_tx.send(());
1009 *share.resume_updates.borrow_mut() = ();
1010 } else {
1011 let (snapshots_tx, mut snapshots_rx) = watch::channel_with(self.snapshot());
1012 let (resume_updates_tx, mut resume_updates_rx) = watch::channel();
1013 let worktree_id = cx.model_id() as u64;
1014
1015 for (path, summary) in self.diagnostic_summaries.iter() {
1016 if let Err(e) = self.client.send(proto::UpdateDiagnosticSummary {
1017 project_id,
1018 worktree_id,
1019 summary: Some(summary.to_proto(&path.0)),
1020 }) {
1021 return Task::ready(Err(e));
1022 }
1023 }
1024
1025 let _maintain_remote_snapshot = cx.background().spawn({
1026 let client = self.client.clone();
1027 async move {
1028 let mut share_tx = Some(share_tx);
1029 let mut prev_snapshot = LocalSnapshot {
1030 ignores_by_parent_abs_path: Default::default(),
1031 git_repositories: Default::default(),
1032 removed_entry_ids: Default::default(),
1033 next_entry_id: Default::default(),
1034 snapshot: Snapshot {
1035 id: WorktreeId(worktree_id as usize),
1036 abs_path: Path::new("").into(),
1037 root_name: Default::default(),
1038 root_char_bag: Default::default(),
1039 entries_by_path: Default::default(),
1040 entries_by_id: Default::default(),
1041 scan_id: 0,
1042 completed_scan_id: 0,
1043 },
1044 };
1045 while let Some(snapshot) = snapshots_rx.recv().await {
1046 #[cfg(any(test, feature = "test-support"))]
1047 const MAX_CHUNK_SIZE: usize = 2;
1048 #[cfg(not(any(test, feature = "test-support")))]
1049 const MAX_CHUNK_SIZE: usize = 256;
1050
1051 let update =
1052 snapshot.build_update(&prev_snapshot, project_id, worktree_id, true);
1053 for update in proto::split_worktree_update(update, MAX_CHUNK_SIZE) {
1054 let _ = resume_updates_rx.try_recv();
1055 while let Err(error) = client.request(update.clone()).await {
1056 log::error!("failed to send worktree update: {}", error);
1057 log::info!("waiting to resume updates");
1058 if resume_updates_rx.next().await.is_none() {
1059 return Ok(());
1060 }
1061 }
1062 }
1063
1064 if let Some(share_tx) = share_tx.take() {
1065 let _ = share_tx.send(());
1066 }
1067
1068 prev_snapshot = snapshot;
1069 }
1070
1071 Ok::<_, anyhow::Error>(())
1072 }
1073 .log_err()
1074 });
1075
1076 self.share = Some(ShareState {
1077 project_id,
1078 snapshots_tx,
1079 resume_updates: resume_updates_tx,
1080 _maintain_remote_snapshot,
1081 });
1082 }
1083
1084 cx.foreground()
1085 .spawn(async move { share_rx.await.map_err(|_| anyhow!("share ended")) })
1086 }
1087
1088 pub fn unshare(&mut self) {
1089 self.share.take();
1090 }
1091
1092 pub fn is_shared(&self) -> bool {
1093 self.share.is_some()
1094 }
1095}
1096
1097impl RemoteWorktree {
1098 fn snapshot(&self) -> Snapshot {
1099 self.snapshot.clone()
1100 }
1101
1102 fn poll_snapshot(&mut self, cx: &mut ModelContext<Worktree>) {
1103 self.snapshot = self.background_snapshot.lock().clone();
1104 cx.emit(Event::UpdatedEntries(Default::default()));
1105 cx.notify();
1106 }
1107
1108 pub fn disconnected_from_host(&mut self) {
1109 self.updates_tx.take();
1110 self.snapshot_subscriptions.clear();
1111 self.disconnected = true;
1112 }
1113
1114 pub fn save_buffer(
1115 &self,
1116 buffer_handle: ModelHandle<Buffer>,
1117 cx: &mut ModelContext<Worktree>,
1118 ) -> Task<Result<(clock::Global, RopeFingerprint, SystemTime)>> {
1119 let buffer = buffer_handle.read(cx);
1120 let buffer_id = buffer.remote_id();
1121 let version = buffer.version();
1122 let rpc = self.client.clone();
1123 let project_id = self.project_id;
1124 cx.as_mut().spawn(|mut cx| async move {
1125 let response = rpc
1126 .request(proto::SaveBuffer {
1127 project_id,
1128 buffer_id,
1129 version: serialize_version(&version),
1130 })
1131 .await?;
1132 let version = deserialize_version(response.version);
1133 let fingerprint = deserialize_fingerprint(&response.fingerprint)?;
1134 let mtime = response
1135 .mtime
1136 .ok_or_else(|| anyhow!("missing mtime"))?
1137 .into();
1138
1139 buffer_handle.update(&mut cx, |buffer, cx| {
1140 buffer.did_save(version.clone(), fingerprint, mtime, cx);
1141 });
1142
1143 Ok((version, fingerprint, mtime))
1144 })
1145 }
1146
1147 pub fn update_from_remote(&mut self, update: proto::UpdateWorktree) {
1148 if let Some(updates_tx) = &self.updates_tx {
1149 updates_tx
1150 .unbounded_send(update)
1151 .expect("consumer runs to completion");
1152 }
1153 }
1154
1155 fn observed_snapshot(&self, scan_id: usize) -> bool {
1156 self.completed_scan_id >= scan_id
1157 }
1158
1159 fn wait_for_snapshot(&mut self, scan_id: usize) -> impl Future<Output = Result<()>> {
1160 let (tx, rx) = oneshot::channel();
1161 if self.observed_snapshot(scan_id) {
1162 let _ = tx.send(());
1163 } else if self.disconnected {
1164 drop(tx);
1165 } else {
1166 match self
1167 .snapshot_subscriptions
1168 .binary_search_by_key(&scan_id, |probe| probe.0)
1169 {
1170 Ok(ix) | Err(ix) => self.snapshot_subscriptions.insert(ix, (scan_id, tx)),
1171 }
1172 }
1173
1174 async move {
1175 rx.await?;
1176 Ok(())
1177 }
1178 }
1179
1180 pub fn update_diagnostic_summary(
1181 &mut self,
1182 path: Arc<Path>,
1183 summary: &proto::DiagnosticSummary,
1184 ) {
1185 let summary = DiagnosticSummary {
1186 language_server_id: summary.language_server_id as usize,
1187 error_count: summary.error_count as usize,
1188 warning_count: summary.warning_count as usize,
1189 };
1190 if summary.is_empty() {
1191 self.diagnostic_summaries.remove(&PathKey(path));
1192 } else {
1193 self.diagnostic_summaries.insert(PathKey(path), summary);
1194 }
1195 }
1196
1197 pub fn insert_entry(
1198 &mut self,
1199 entry: proto::Entry,
1200 scan_id: usize,
1201 cx: &mut ModelContext<Worktree>,
1202 ) -> Task<Result<Entry>> {
1203 let wait_for_snapshot = self.wait_for_snapshot(scan_id);
1204 cx.spawn(|this, mut cx| async move {
1205 wait_for_snapshot.await?;
1206 this.update(&mut cx, |worktree, _| {
1207 let worktree = worktree.as_remote_mut().unwrap();
1208 let mut snapshot = worktree.background_snapshot.lock();
1209 let entry = snapshot.insert_entry(entry);
1210 worktree.snapshot = snapshot.clone();
1211 entry
1212 })
1213 })
1214 }
1215
1216 pub(crate) fn delete_entry(
1217 &mut self,
1218 id: ProjectEntryId,
1219 scan_id: usize,
1220 cx: &mut ModelContext<Worktree>,
1221 ) -> Task<Result<()>> {
1222 let wait_for_snapshot = self.wait_for_snapshot(scan_id);
1223 cx.spawn(|this, mut cx| async move {
1224 wait_for_snapshot.await?;
1225 this.update(&mut cx, |worktree, _| {
1226 let worktree = worktree.as_remote_mut().unwrap();
1227 let mut snapshot = worktree.background_snapshot.lock();
1228 snapshot.delete_entry(id);
1229 worktree.snapshot = snapshot.clone();
1230 });
1231 Ok(())
1232 })
1233 }
1234}
1235
1236impl Snapshot {
1237 pub fn id(&self) -> WorktreeId {
1238 self.id
1239 }
1240
1241 pub fn abs_path(&self) -> &Arc<Path> {
1242 &self.abs_path
1243 }
1244
1245 pub fn contains_entry(&self, entry_id: ProjectEntryId) -> bool {
1246 self.entries_by_id.get(&entry_id, &()).is_some()
1247 }
1248
1249 pub(crate) fn insert_entry(&mut self, entry: proto::Entry) -> Result<Entry> {
1250 let entry = Entry::try_from((&self.root_char_bag, entry))?;
1251 let old_entry = self.entries_by_id.insert_or_replace(
1252 PathEntry {
1253 id: entry.id,
1254 path: entry.path.clone(),
1255 is_ignored: entry.is_ignored,
1256 scan_id: 0,
1257 },
1258 &(),
1259 );
1260 if let Some(old_entry) = old_entry {
1261 self.entries_by_path.remove(&PathKey(old_entry.path), &());
1262 }
1263 self.entries_by_path.insert_or_replace(entry.clone(), &());
1264 Ok(entry)
1265 }
1266
1267 fn delete_entry(&mut self, entry_id: ProjectEntryId) -> bool {
1268 if let Some(removed_entry) = self.entries_by_id.remove(&entry_id, &()) {
1269 self.entries_by_path = {
1270 let mut cursor = self.entries_by_path.cursor();
1271 let mut new_entries_by_path =
1272 cursor.slice(&TraversalTarget::Path(&removed_entry.path), Bias::Left, &());
1273 while let Some(entry) = cursor.item() {
1274 if entry.path.starts_with(&removed_entry.path) {
1275 self.entries_by_id.remove(&entry.id, &());
1276 cursor.next(&());
1277 } else {
1278 break;
1279 }
1280 }
1281 new_entries_by_path.push_tree(cursor.suffix(&()), &());
1282 new_entries_by_path
1283 };
1284
1285 true
1286 } else {
1287 false
1288 }
1289 }
1290
1291 pub(crate) fn apply_remote_update(&mut self, update: proto::UpdateWorktree) -> Result<()> {
1292 let mut entries_by_path_edits = Vec::new();
1293 let mut entries_by_id_edits = Vec::new();
1294 for entry_id in update.removed_entries {
1295 let entry = self
1296 .entry_for_id(ProjectEntryId::from_proto(entry_id))
1297 .ok_or_else(|| anyhow!("unknown entry {}", entry_id))?;
1298 entries_by_path_edits.push(Edit::Remove(PathKey(entry.path.clone())));
1299 entries_by_id_edits.push(Edit::Remove(entry.id));
1300 }
1301
1302 for entry in update.updated_entries {
1303 let entry = Entry::try_from((&self.root_char_bag, entry))?;
1304 if let Some(PathEntry { path, .. }) = self.entries_by_id.get(&entry.id, &()) {
1305 entries_by_path_edits.push(Edit::Remove(PathKey(path.clone())));
1306 }
1307 entries_by_id_edits.push(Edit::Insert(PathEntry {
1308 id: entry.id,
1309 path: entry.path.clone(),
1310 is_ignored: entry.is_ignored,
1311 scan_id: 0,
1312 }));
1313 entries_by_path_edits.push(Edit::Insert(entry));
1314 }
1315
1316 self.entries_by_path.edit(entries_by_path_edits, &());
1317 self.entries_by_id.edit(entries_by_id_edits, &());
1318 self.scan_id = update.scan_id as usize;
1319 if update.is_last_update {
1320 self.completed_scan_id = update.scan_id as usize;
1321 }
1322
1323 Ok(())
1324 }
1325
1326 pub fn file_count(&self) -> usize {
1327 self.entries_by_path.summary().file_count
1328 }
1329
1330 pub fn visible_file_count(&self) -> usize {
1331 self.entries_by_path.summary().visible_file_count
1332 }
1333
1334 fn traverse_from_offset(
1335 &self,
1336 include_dirs: bool,
1337 include_ignored: bool,
1338 start_offset: usize,
1339 ) -> Traversal {
1340 let mut cursor = self.entries_by_path.cursor();
1341 cursor.seek(
1342 &TraversalTarget::Count {
1343 count: start_offset,
1344 include_dirs,
1345 include_ignored,
1346 },
1347 Bias::Right,
1348 &(),
1349 );
1350 Traversal {
1351 cursor,
1352 include_dirs,
1353 include_ignored,
1354 }
1355 }
1356
1357 fn traverse_from_path(
1358 &self,
1359 include_dirs: bool,
1360 include_ignored: bool,
1361 path: &Path,
1362 ) -> Traversal {
1363 let mut cursor = self.entries_by_path.cursor();
1364 cursor.seek(&TraversalTarget::Path(path), Bias::Left, &());
1365 Traversal {
1366 cursor,
1367 include_dirs,
1368 include_ignored,
1369 }
1370 }
1371
1372 pub fn files(&self, include_ignored: bool, start: usize) -> Traversal {
1373 self.traverse_from_offset(false, include_ignored, start)
1374 }
1375
1376 pub fn entries(&self, include_ignored: bool) -> Traversal {
1377 self.traverse_from_offset(true, include_ignored, 0)
1378 }
1379
1380 pub fn paths(&self) -> impl Iterator<Item = &Arc<Path>> {
1381 let empty_path = Path::new("");
1382 self.entries_by_path
1383 .cursor::<()>()
1384 .filter(move |entry| entry.path.as_ref() != empty_path)
1385 .map(|entry| &entry.path)
1386 }
1387
1388 fn child_entries<'a>(&'a self, parent_path: &'a Path) -> ChildEntriesIter<'a> {
1389 let mut cursor = self.entries_by_path.cursor();
1390 cursor.seek(&TraversalTarget::Path(parent_path), Bias::Right, &());
1391 let traversal = Traversal {
1392 cursor,
1393 include_dirs: true,
1394 include_ignored: true,
1395 };
1396 ChildEntriesIter {
1397 traversal,
1398 parent_path,
1399 }
1400 }
1401
1402 pub fn root_entry(&self) -> Option<&Entry> {
1403 self.entry_for_path("")
1404 }
1405
1406 pub fn root_name(&self) -> &str {
1407 &self.root_name
1408 }
1409
1410 pub fn scan_started(&mut self) {
1411 self.scan_id += 1;
1412 }
1413
1414 pub fn scan_completed(&mut self) {
1415 self.completed_scan_id = self.scan_id;
1416 }
1417
1418 pub fn scan_id(&self) -> usize {
1419 self.scan_id
1420 }
1421
1422 pub fn entry_for_path(&self, path: impl AsRef<Path>) -> Option<&Entry> {
1423 let path = path.as_ref();
1424 self.traverse_from_path(true, true, path)
1425 .entry()
1426 .and_then(|entry| {
1427 if entry.path.as_ref() == path {
1428 Some(entry)
1429 } else {
1430 None
1431 }
1432 })
1433 }
1434
1435 pub fn entry_for_id(&self, id: ProjectEntryId) -> Option<&Entry> {
1436 let entry = self.entries_by_id.get(&id, &())?;
1437 self.entry_for_path(&entry.path)
1438 }
1439
1440 pub fn inode_for_path(&self, path: impl AsRef<Path>) -> Option<u64> {
1441 self.entry_for_path(path.as_ref()).map(|e| e.inode)
1442 }
1443}
1444
1445impl LocalSnapshot {
1446 // Gives the most specific git repository for a given path
1447 pub(crate) fn repo_for(&self, path: &Path) -> Option<GitRepositoryEntry> {
1448 self.git_repositories
1449 .iter()
1450 .rev() //git_repository is ordered lexicographically
1451 .find(|repo| repo.manages(path))
1452 .cloned()
1453 }
1454
1455 pub(crate) fn in_dot_git(&mut self, path: &Path) -> Option<&mut GitRepositoryEntry> {
1456 // Git repositories cannot be nested, so we don't need to reverse the order
1457 self.git_repositories
1458 .iter_mut()
1459 .find(|repo| repo.in_dot_git(path))
1460 }
1461
1462 #[cfg(test)]
1463 pub(crate) fn build_initial_update(&self, project_id: u64) -> proto::UpdateWorktree {
1464 let root_name = self.root_name.clone();
1465 proto::UpdateWorktree {
1466 project_id,
1467 worktree_id: self.id().to_proto(),
1468 abs_path: self.abs_path().to_string_lossy().into(),
1469 root_name,
1470 updated_entries: self.entries_by_path.iter().map(Into::into).collect(),
1471 removed_entries: Default::default(),
1472 scan_id: self.scan_id as u64,
1473 is_last_update: true,
1474 }
1475 }
1476
1477 pub(crate) fn build_update(
1478 &self,
1479 other: &Self,
1480 project_id: u64,
1481 worktree_id: u64,
1482 include_ignored: bool,
1483 ) -> proto::UpdateWorktree {
1484 let mut updated_entries = Vec::new();
1485 let mut removed_entries = Vec::new();
1486 let mut self_entries = self
1487 .entries_by_id
1488 .cursor::<()>()
1489 .filter(|e| include_ignored || !e.is_ignored)
1490 .peekable();
1491 let mut other_entries = other
1492 .entries_by_id
1493 .cursor::<()>()
1494 .filter(|e| include_ignored || !e.is_ignored)
1495 .peekable();
1496 loop {
1497 match (self_entries.peek(), other_entries.peek()) {
1498 (Some(self_entry), Some(other_entry)) => {
1499 match Ord::cmp(&self_entry.id, &other_entry.id) {
1500 Ordering::Less => {
1501 let entry = self.entry_for_id(self_entry.id).unwrap().into();
1502 updated_entries.push(entry);
1503 self_entries.next();
1504 }
1505 Ordering::Equal => {
1506 if self_entry.scan_id != other_entry.scan_id {
1507 let entry = self.entry_for_id(self_entry.id).unwrap().into();
1508 updated_entries.push(entry);
1509 }
1510
1511 self_entries.next();
1512 other_entries.next();
1513 }
1514 Ordering::Greater => {
1515 removed_entries.push(other_entry.id.to_proto());
1516 other_entries.next();
1517 }
1518 }
1519 }
1520 (Some(self_entry), None) => {
1521 let entry = self.entry_for_id(self_entry.id).unwrap().into();
1522 updated_entries.push(entry);
1523 self_entries.next();
1524 }
1525 (None, Some(other_entry)) => {
1526 removed_entries.push(other_entry.id.to_proto());
1527 other_entries.next();
1528 }
1529 (None, None) => break,
1530 }
1531 }
1532
1533 proto::UpdateWorktree {
1534 project_id,
1535 worktree_id,
1536 abs_path: self.abs_path().to_string_lossy().into(),
1537 root_name: self.root_name().to_string(),
1538 updated_entries,
1539 removed_entries,
1540 scan_id: self.scan_id as u64,
1541 is_last_update: self.completed_scan_id == self.scan_id,
1542 }
1543 }
1544
1545 fn insert_entry(&mut self, mut entry: Entry, fs: &dyn Fs) -> Entry {
1546 if entry.is_file() && entry.path.file_name() == Some(&GITIGNORE) {
1547 let abs_path = self.abs_path.join(&entry.path);
1548 match smol::block_on(build_gitignore(&abs_path, fs)) {
1549 Ok(ignore) => {
1550 self.ignores_by_parent_abs_path.insert(
1551 abs_path.parent().unwrap().into(),
1552 (Arc::new(ignore), self.scan_id),
1553 );
1554 }
1555 Err(error) => {
1556 log::error!(
1557 "error loading .gitignore file {:?} - {:?}",
1558 &entry.path,
1559 error
1560 );
1561 }
1562 }
1563 }
1564
1565 self.reuse_entry_id(&mut entry);
1566
1567 if entry.kind == EntryKind::PendingDir {
1568 if let Some(existing_entry) =
1569 self.entries_by_path.get(&PathKey(entry.path.clone()), &())
1570 {
1571 entry.kind = existing_entry.kind;
1572 }
1573 }
1574
1575 let scan_id = self.scan_id;
1576 self.entries_by_path.insert_or_replace(entry.clone(), &());
1577 self.entries_by_id.insert_or_replace(
1578 PathEntry {
1579 id: entry.id,
1580 path: entry.path.clone(),
1581 is_ignored: entry.is_ignored,
1582 scan_id,
1583 },
1584 &(),
1585 );
1586
1587 entry
1588 }
1589
1590 fn populate_dir(
1591 &mut self,
1592 parent_path: Arc<Path>,
1593 entries: impl IntoIterator<Item = Entry>,
1594 ignore: Option<Arc<Gitignore>>,
1595 fs: &dyn Fs,
1596 ) {
1597 let mut parent_entry = if let Some(parent_entry) =
1598 self.entries_by_path.get(&PathKey(parent_path.clone()), &())
1599 {
1600 parent_entry.clone()
1601 } else {
1602 log::warn!(
1603 "populating a directory {:?} that has been removed",
1604 parent_path
1605 );
1606 return;
1607 };
1608
1609 if let Some(ignore) = ignore {
1610 self.ignores_by_parent_abs_path.insert(
1611 self.abs_path.join(&parent_path).into(),
1612 (ignore, self.scan_id),
1613 );
1614 }
1615 if matches!(parent_entry.kind, EntryKind::PendingDir) {
1616 parent_entry.kind = EntryKind::Dir;
1617 } else {
1618 unreachable!();
1619 }
1620
1621 if parent_path.file_name() == Some(&DOT_GIT) {
1622 let abs_path = self.abs_path.join(&parent_path);
1623 let content_path: Arc<Path> = parent_path.parent().unwrap().into();
1624 if let Err(ix) = self
1625 .git_repositories
1626 .binary_search_by_key(&&content_path, |repo| &repo.content_path)
1627 {
1628 if let Some(repo) = fs.open_repo(abs_path.as_path()) {
1629 self.git_repositories.insert(
1630 ix,
1631 GitRepositoryEntry {
1632 repo,
1633 scan_id: 0,
1634 content_path,
1635 git_dir_path: parent_path,
1636 },
1637 );
1638 }
1639 }
1640 }
1641
1642 let mut entries_by_path_edits = vec![Edit::Insert(parent_entry)];
1643 let mut entries_by_id_edits = Vec::new();
1644
1645 for mut entry in entries {
1646 self.reuse_entry_id(&mut entry);
1647 entries_by_id_edits.push(Edit::Insert(PathEntry {
1648 id: entry.id,
1649 path: entry.path.clone(),
1650 is_ignored: entry.is_ignored,
1651 scan_id: self.scan_id,
1652 }));
1653 entries_by_path_edits.push(Edit::Insert(entry));
1654 }
1655
1656 self.entries_by_path.edit(entries_by_path_edits, &());
1657 self.entries_by_id.edit(entries_by_id_edits, &());
1658 }
1659
1660 fn reuse_entry_id(&mut self, entry: &mut Entry) {
1661 if let Some(removed_entry_id) = self.removed_entry_ids.remove(&entry.inode) {
1662 entry.id = removed_entry_id;
1663 } else if let Some(existing_entry) = self.entry_for_path(&entry.path) {
1664 entry.id = existing_entry.id;
1665 }
1666 }
1667
1668 fn remove_path(&mut self, path: &Path) {
1669 let mut new_entries;
1670 let removed_entries;
1671 {
1672 let mut cursor = self.entries_by_path.cursor::<TraversalProgress>();
1673 new_entries = cursor.slice(&TraversalTarget::Path(path), Bias::Left, &());
1674 removed_entries = cursor.slice(&TraversalTarget::PathSuccessor(path), Bias::Left, &());
1675 new_entries.push_tree(cursor.suffix(&()), &());
1676 }
1677 self.entries_by_path = new_entries;
1678
1679 let mut entries_by_id_edits = Vec::new();
1680 for entry in removed_entries.cursor::<()>() {
1681 let removed_entry_id = self
1682 .removed_entry_ids
1683 .entry(entry.inode)
1684 .or_insert(entry.id);
1685 *removed_entry_id = cmp::max(*removed_entry_id, entry.id);
1686 entries_by_id_edits.push(Edit::Remove(entry.id));
1687 }
1688 self.entries_by_id.edit(entries_by_id_edits, &());
1689
1690 if path.file_name() == Some(&GITIGNORE) {
1691 let abs_parent_path = self.abs_path.join(path.parent().unwrap());
1692 if let Some((_, scan_id)) = self
1693 .ignores_by_parent_abs_path
1694 .get_mut(abs_parent_path.as_path())
1695 {
1696 *scan_id = self.snapshot.scan_id;
1697 }
1698 } else if path.file_name() == Some(&DOT_GIT) {
1699 let parent_path = path.parent().unwrap();
1700 if let Ok(ix) = self
1701 .git_repositories
1702 .binary_search_by_key(&parent_path, |repo| repo.git_dir_path.as_ref())
1703 {
1704 self.git_repositories[ix].scan_id = self.snapshot.scan_id;
1705 }
1706 }
1707 }
1708
1709 fn ancestor_inodes_for_path(&self, path: &Path) -> TreeSet<u64> {
1710 let mut inodes = TreeSet::default();
1711 for ancestor in path.ancestors().skip(1) {
1712 if let Some(entry) = self.entry_for_path(ancestor) {
1713 inodes.insert(entry.inode);
1714 }
1715 }
1716 inodes
1717 }
1718
1719 fn ignore_stack_for_abs_path(&self, abs_path: &Path, is_dir: bool) -> Arc<IgnoreStack> {
1720 let mut new_ignores = Vec::new();
1721 for ancestor in abs_path.ancestors().skip(1) {
1722 if let Some((ignore, _)) = self.ignores_by_parent_abs_path.get(ancestor) {
1723 new_ignores.push((ancestor, Some(ignore.clone())));
1724 } else {
1725 new_ignores.push((ancestor, None));
1726 }
1727 }
1728
1729 let mut ignore_stack = IgnoreStack::none();
1730 for (parent_abs_path, ignore) in new_ignores.into_iter().rev() {
1731 if ignore_stack.is_abs_path_ignored(parent_abs_path, true) {
1732 ignore_stack = IgnoreStack::all();
1733 break;
1734 } else if let Some(ignore) = ignore {
1735 ignore_stack = ignore_stack.append(parent_abs_path.into(), ignore);
1736 }
1737 }
1738
1739 if ignore_stack.is_abs_path_ignored(abs_path, is_dir) {
1740 ignore_stack = IgnoreStack::all();
1741 }
1742
1743 ignore_stack
1744 }
1745
1746 pub fn git_repo_entries(&self) -> &[GitRepositoryEntry] {
1747 &self.git_repositories
1748 }
1749}
1750
1751impl GitRepositoryEntry {
1752 // Note that these paths should be relative to the worktree root.
1753 pub(crate) fn manages(&self, path: &Path) -> bool {
1754 path.starts_with(self.content_path.as_ref())
1755 }
1756
1757 // Note that theis path should be relative to the worktree root.
1758 pub(crate) fn in_dot_git(&self, path: &Path) -> bool {
1759 path.starts_with(self.git_dir_path.as_ref())
1760 }
1761}
1762
1763async fn build_gitignore(abs_path: &Path, fs: &dyn Fs) -> Result<Gitignore> {
1764 let contents = fs.load(abs_path).await?;
1765 let parent = abs_path.parent().unwrap_or_else(|| Path::new("/"));
1766 let mut builder = GitignoreBuilder::new(parent);
1767 for line in contents.lines() {
1768 builder.add_line(Some(abs_path.into()), line)?;
1769 }
1770 Ok(builder.build()?)
1771}
1772
1773impl WorktreeId {
1774 pub fn from_usize(handle_id: usize) -> Self {
1775 Self(handle_id)
1776 }
1777
1778 pub(crate) fn from_proto(id: u64) -> Self {
1779 Self(id as usize)
1780 }
1781
1782 pub fn to_proto(&self) -> u64 {
1783 self.0 as u64
1784 }
1785
1786 pub fn to_usize(&self) -> usize {
1787 self.0
1788 }
1789}
1790
1791impl fmt::Display for WorktreeId {
1792 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1793 self.0.fmt(f)
1794 }
1795}
1796
1797impl Deref for Worktree {
1798 type Target = Snapshot;
1799
1800 fn deref(&self) -> &Self::Target {
1801 match self {
1802 Worktree::Local(worktree) => &worktree.snapshot,
1803 Worktree::Remote(worktree) => &worktree.snapshot,
1804 }
1805 }
1806}
1807
1808impl Deref for LocalWorktree {
1809 type Target = LocalSnapshot;
1810
1811 fn deref(&self) -> &Self::Target {
1812 &self.snapshot
1813 }
1814}
1815
1816impl Deref for RemoteWorktree {
1817 type Target = Snapshot;
1818
1819 fn deref(&self) -> &Self::Target {
1820 &self.snapshot
1821 }
1822}
1823
1824impl fmt::Debug for LocalWorktree {
1825 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1826 self.snapshot.fmt(f)
1827 }
1828}
1829
1830impl fmt::Debug for Snapshot {
1831 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1832 struct EntriesById<'a>(&'a SumTree<PathEntry>);
1833 struct EntriesByPath<'a>(&'a SumTree<Entry>);
1834
1835 impl<'a> fmt::Debug for EntriesByPath<'a> {
1836 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1837 f.debug_map()
1838 .entries(self.0.iter().map(|entry| (&entry.path, entry.id)))
1839 .finish()
1840 }
1841 }
1842
1843 impl<'a> fmt::Debug for EntriesById<'a> {
1844 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1845 f.debug_list().entries(self.0.iter()).finish()
1846 }
1847 }
1848
1849 f.debug_struct("Snapshot")
1850 .field("id", &self.id)
1851 .field("root_name", &self.root_name)
1852 .field("entries_by_path", &EntriesByPath(&self.entries_by_path))
1853 .field("entries_by_id", &EntriesById(&self.entries_by_id))
1854 .finish()
1855 }
1856}
1857
1858#[derive(Clone, PartialEq)]
1859pub struct File {
1860 pub worktree: ModelHandle<Worktree>,
1861 pub path: Arc<Path>,
1862 pub mtime: SystemTime,
1863 pub(crate) entry_id: ProjectEntryId,
1864 pub(crate) is_local: bool,
1865 pub(crate) is_deleted: bool,
1866}
1867
1868impl language::File for File {
1869 fn as_local(&self) -> Option<&dyn language::LocalFile> {
1870 if self.is_local {
1871 Some(self)
1872 } else {
1873 None
1874 }
1875 }
1876
1877 fn mtime(&self) -> SystemTime {
1878 self.mtime
1879 }
1880
1881 fn path(&self) -> &Arc<Path> {
1882 &self.path
1883 }
1884
1885 fn full_path(&self, cx: &AppContext) -> PathBuf {
1886 let mut full_path = PathBuf::new();
1887 let worktree = self.worktree.read(cx);
1888
1889 if worktree.is_visible() {
1890 full_path.push(worktree.root_name());
1891 } else {
1892 let path = worktree.abs_path();
1893
1894 if worktree.is_local() && path.starts_with(HOME.as_path()) {
1895 full_path.push("~");
1896 full_path.push(path.strip_prefix(HOME.as_path()).unwrap());
1897 } else {
1898 full_path.push(path)
1899 }
1900 }
1901
1902 if self.path.components().next().is_some() {
1903 full_path.push(&self.path);
1904 }
1905
1906 full_path
1907 }
1908
1909 /// Returns the last component of this handle's absolute path. If this handle refers to the root
1910 /// of its worktree, then this method will return the name of the worktree itself.
1911 fn file_name<'a>(&'a self, cx: &'a AppContext) -> &'a OsStr {
1912 self.path
1913 .file_name()
1914 .unwrap_or_else(|| OsStr::new(&self.worktree.read(cx).root_name))
1915 }
1916
1917 fn is_deleted(&self) -> bool {
1918 self.is_deleted
1919 }
1920
1921 fn as_any(&self) -> &dyn Any {
1922 self
1923 }
1924
1925 fn to_proto(&self) -> rpc::proto::File {
1926 rpc::proto::File {
1927 worktree_id: self.worktree.id() as u64,
1928 entry_id: self.entry_id.to_proto(),
1929 path: self.path.to_string_lossy().into(),
1930 mtime: Some(self.mtime.into()),
1931 is_deleted: self.is_deleted,
1932 }
1933 }
1934}
1935
1936impl language::LocalFile for File {
1937 fn abs_path(&self, cx: &AppContext) -> PathBuf {
1938 self.worktree
1939 .read(cx)
1940 .as_local()
1941 .unwrap()
1942 .abs_path
1943 .join(&self.path)
1944 }
1945
1946 fn load(&self, cx: &AppContext) -> Task<Result<String>> {
1947 let worktree = self.worktree.read(cx).as_local().unwrap();
1948 let abs_path = worktree.absolutize(&self.path);
1949 let fs = worktree.fs.clone();
1950 cx.background()
1951 .spawn(async move { fs.load(&abs_path).await })
1952 }
1953
1954 fn buffer_reloaded(
1955 &self,
1956 buffer_id: u64,
1957 version: &clock::Global,
1958 fingerprint: RopeFingerprint,
1959 line_ending: LineEnding,
1960 mtime: SystemTime,
1961 cx: &mut MutableAppContext,
1962 ) {
1963 let worktree = self.worktree.read(cx).as_local().unwrap();
1964 if let Some(project_id) = worktree.share.as_ref().map(|share| share.project_id) {
1965 worktree
1966 .client
1967 .send(proto::BufferReloaded {
1968 project_id,
1969 buffer_id,
1970 version: serialize_version(version),
1971 mtime: Some(mtime.into()),
1972 fingerprint: serialize_fingerprint(fingerprint),
1973 line_ending: serialize_line_ending(line_ending) as i32,
1974 })
1975 .log_err();
1976 }
1977 }
1978}
1979
1980impl File {
1981 pub fn from_proto(
1982 proto: rpc::proto::File,
1983 worktree: ModelHandle<Worktree>,
1984 cx: &AppContext,
1985 ) -> Result<Self> {
1986 let worktree_id = worktree
1987 .read(cx)
1988 .as_remote()
1989 .ok_or_else(|| anyhow!("not remote"))?
1990 .id();
1991
1992 if worktree_id.to_proto() != proto.worktree_id {
1993 return Err(anyhow!("worktree id does not match file"));
1994 }
1995
1996 Ok(Self {
1997 worktree,
1998 path: Path::new(&proto.path).into(),
1999 mtime: proto.mtime.ok_or_else(|| anyhow!("no timestamp"))?.into(),
2000 entry_id: ProjectEntryId::from_proto(proto.entry_id),
2001 is_local: false,
2002 is_deleted: proto.is_deleted,
2003 })
2004 }
2005
2006 pub fn from_dyn(file: Option<&Arc<dyn language::File>>) -> Option<&Self> {
2007 file.and_then(|f| f.as_any().downcast_ref())
2008 }
2009
2010 pub fn worktree_id(&self, cx: &AppContext) -> WorktreeId {
2011 self.worktree.read(cx).id()
2012 }
2013
2014 pub fn project_entry_id(&self, _: &AppContext) -> Option<ProjectEntryId> {
2015 if self.is_deleted {
2016 None
2017 } else {
2018 Some(self.entry_id)
2019 }
2020 }
2021}
2022
2023#[derive(Clone, Debug, PartialEq, Eq)]
2024pub struct Entry {
2025 pub id: ProjectEntryId,
2026 pub kind: EntryKind,
2027 pub path: Arc<Path>,
2028 pub inode: u64,
2029 pub mtime: SystemTime,
2030 pub is_symlink: bool,
2031 pub is_ignored: bool,
2032}
2033
2034#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2035pub enum EntryKind {
2036 PendingDir,
2037 Dir,
2038 File(CharBag),
2039}
2040
2041#[derive(Clone, Copy, Debug)]
2042pub enum PathChange {
2043 Added,
2044 Removed,
2045 Updated,
2046 AddedOrUpdated,
2047}
2048
2049impl Entry {
2050 fn new(
2051 path: Arc<Path>,
2052 metadata: &fs::Metadata,
2053 next_entry_id: &AtomicUsize,
2054 root_char_bag: CharBag,
2055 ) -> Self {
2056 Self {
2057 id: ProjectEntryId::new(next_entry_id),
2058 kind: if metadata.is_dir {
2059 EntryKind::PendingDir
2060 } else {
2061 EntryKind::File(char_bag_for_path(root_char_bag, &path))
2062 },
2063 path,
2064 inode: metadata.inode,
2065 mtime: metadata.mtime,
2066 is_symlink: metadata.is_symlink,
2067 is_ignored: false,
2068 }
2069 }
2070
2071 pub fn is_dir(&self) -> bool {
2072 matches!(self.kind, EntryKind::Dir | EntryKind::PendingDir)
2073 }
2074
2075 pub fn is_file(&self) -> bool {
2076 matches!(self.kind, EntryKind::File(_))
2077 }
2078}
2079
2080impl sum_tree::Item for Entry {
2081 type Summary = EntrySummary;
2082
2083 fn summary(&self) -> Self::Summary {
2084 let visible_count = if self.is_ignored { 0 } else { 1 };
2085 let file_count;
2086 let visible_file_count;
2087 if self.is_file() {
2088 file_count = 1;
2089 visible_file_count = visible_count;
2090 } else {
2091 file_count = 0;
2092 visible_file_count = 0;
2093 }
2094
2095 EntrySummary {
2096 max_path: self.path.clone(),
2097 count: 1,
2098 visible_count,
2099 file_count,
2100 visible_file_count,
2101 }
2102 }
2103}
2104
2105impl sum_tree::KeyedItem for Entry {
2106 type Key = PathKey;
2107
2108 fn key(&self) -> Self::Key {
2109 PathKey(self.path.clone())
2110 }
2111}
2112
2113#[derive(Clone, Debug)]
2114pub struct EntrySummary {
2115 max_path: Arc<Path>,
2116 count: usize,
2117 visible_count: usize,
2118 file_count: usize,
2119 visible_file_count: usize,
2120}
2121
2122impl Default for EntrySummary {
2123 fn default() -> Self {
2124 Self {
2125 max_path: Arc::from(Path::new("")),
2126 count: 0,
2127 visible_count: 0,
2128 file_count: 0,
2129 visible_file_count: 0,
2130 }
2131 }
2132}
2133
2134impl sum_tree::Summary for EntrySummary {
2135 type Context = ();
2136
2137 fn add_summary(&mut self, rhs: &Self, _: &()) {
2138 self.max_path = rhs.max_path.clone();
2139 self.count += rhs.count;
2140 self.visible_count += rhs.visible_count;
2141 self.file_count += rhs.file_count;
2142 self.visible_file_count += rhs.visible_file_count;
2143 }
2144}
2145
2146#[derive(Clone, Debug)]
2147struct PathEntry {
2148 id: ProjectEntryId,
2149 path: Arc<Path>,
2150 is_ignored: bool,
2151 scan_id: usize,
2152}
2153
2154impl sum_tree::Item for PathEntry {
2155 type Summary = PathEntrySummary;
2156
2157 fn summary(&self) -> Self::Summary {
2158 PathEntrySummary { max_id: self.id }
2159 }
2160}
2161
2162impl sum_tree::KeyedItem for PathEntry {
2163 type Key = ProjectEntryId;
2164
2165 fn key(&self) -> Self::Key {
2166 self.id
2167 }
2168}
2169
2170#[derive(Clone, Debug, Default)]
2171struct PathEntrySummary {
2172 max_id: ProjectEntryId,
2173}
2174
2175impl sum_tree::Summary for PathEntrySummary {
2176 type Context = ();
2177
2178 fn add_summary(&mut self, summary: &Self, _: &Self::Context) {
2179 self.max_id = summary.max_id;
2180 }
2181}
2182
2183impl<'a> sum_tree::Dimension<'a, PathEntrySummary> for ProjectEntryId {
2184 fn add_summary(&mut self, summary: &'a PathEntrySummary, _: &()) {
2185 *self = summary.max_id;
2186 }
2187}
2188
2189#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
2190pub struct PathKey(Arc<Path>);
2191
2192impl Default for PathKey {
2193 fn default() -> Self {
2194 Self(Path::new("").into())
2195 }
2196}
2197
2198impl<'a> sum_tree::Dimension<'a, EntrySummary> for PathKey {
2199 fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
2200 self.0 = summary.max_path.clone();
2201 }
2202}
2203
2204struct BackgroundScanner {
2205 fs: Arc<dyn Fs>,
2206 snapshot: Arc<Mutex<LocalSnapshot>>,
2207 changes: Arc<Mutex<HashMap<Arc<Path>, PathChange>>>,
2208 notify: UnboundedSender<ScanState>,
2209 executor: Arc<executor::Background>,
2210}
2211
2212impl BackgroundScanner {
2213 fn new(
2214 snapshot: Arc<Mutex<LocalSnapshot>>,
2215 changes: Arc<Mutex<HashMap<Arc<Path>, PathChange>>>,
2216 notify: UnboundedSender<ScanState>,
2217 fs: Arc<dyn Fs>,
2218 executor: Arc<executor::Background>,
2219 ) -> Self {
2220 Self {
2221 fs,
2222 snapshot,
2223 changes,
2224 notify,
2225 executor,
2226 }
2227 }
2228
2229 fn abs_path(&self) -> Arc<Path> {
2230 self.snapshot.lock().abs_path.clone()
2231 }
2232
2233 async fn run(mut self, events_rx: impl Stream<Item = Vec<fsevent::Event>>) {
2234 if self.notify.unbounded_send(ScanState::Initializing).is_err() {
2235 return;
2236 }
2237
2238 if let Err(err) = self.scan_dirs().await {
2239 if self
2240 .notify
2241 .unbounded_send(ScanState::Err(Arc::new(err)))
2242 .is_err()
2243 {
2244 return;
2245 }
2246 }
2247
2248 if self.notify.unbounded_send(ScanState::Idle).is_err() {
2249 return;
2250 }
2251
2252 futures::pin_mut!(events_rx);
2253
2254 // Process any events that occurred while performing the initial scan. These
2255 // events can't be reported as precisely, because there is no snapshot of the
2256 // worktree before they occurred.
2257 if let Some(mut events) = events_rx.next().await {
2258 while let Poll::Ready(Some(additional_events)) = futures::poll!(events_rx.next()) {
2259 events.extend(additional_events);
2260 }
2261 if self.notify.unbounded_send(ScanState::Updating).is_err() {
2262 return;
2263 }
2264 if !self.process_events(events, true).await {
2265 return;
2266 }
2267 if self.notify.unbounded_send(ScanState::Idle).is_err() {
2268 return;
2269 }
2270 }
2271
2272 // Continue processing events until the worktree is dropped.
2273 while let Some(mut events) = events_rx.next().await {
2274 while let Poll::Ready(Some(additional_events)) = futures::poll!(events_rx.next()) {
2275 events.extend(additional_events);
2276 }
2277 if self.notify.unbounded_send(ScanState::Updating).is_err() {
2278 return;
2279 }
2280 if !self.process_events(events, false).await {
2281 return;
2282 }
2283 if self.notify.unbounded_send(ScanState::Idle).is_err() {
2284 return;
2285 }
2286 }
2287 }
2288
2289 async fn scan_dirs(&mut self) -> Result<()> {
2290 let root_char_bag;
2291 let root_abs_path;
2292 let root_inode;
2293 let is_dir;
2294 let next_entry_id;
2295 {
2296 let mut snapshot = self.snapshot.lock();
2297 snapshot.scan_started();
2298 root_char_bag = snapshot.root_char_bag;
2299 root_abs_path = snapshot.abs_path.clone();
2300 root_inode = snapshot.root_entry().map(|e| e.inode);
2301 is_dir = snapshot.root_entry().map_or(false, |e| e.is_dir());
2302 next_entry_id = snapshot.next_entry_id.clone();
2303 };
2304
2305 // Populate ignores above the root.
2306 for ancestor in root_abs_path.ancestors().skip(1) {
2307 if let Ok(ignore) = build_gitignore(&ancestor.join(&*GITIGNORE), self.fs.as_ref()).await
2308 {
2309 self.snapshot
2310 .lock()
2311 .ignores_by_parent_abs_path
2312 .insert(ancestor.into(), (ignore.into(), 0));
2313 }
2314 }
2315
2316 let ignore_stack = {
2317 let mut snapshot = self.snapshot.lock();
2318 let ignore_stack = snapshot.ignore_stack_for_abs_path(&root_abs_path, true);
2319 if ignore_stack.is_all() {
2320 if let Some(mut root_entry) = snapshot.root_entry().cloned() {
2321 root_entry.is_ignored = true;
2322 snapshot.insert_entry(root_entry, self.fs.as_ref());
2323 }
2324 }
2325 ignore_stack
2326 };
2327
2328 if is_dir {
2329 let path: Arc<Path> = Arc::from(Path::new(""));
2330 let mut ancestor_inodes = TreeSet::default();
2331 if let Some(root_inode) = root_inode {
2332 ancestor_inodes.insert(root_inode);
2333 }
2334
2335 let (tx, rx) = channel::unbounded();
2336 self.executor
2337 .block(tx.send(ScanJob {
2338 abs_path: root_abs_path.to_path_buf(),
2339 path,
2340 ignore_stack,
2341 ancestor_inodes,
2342 scan_queue: tx.clone(),
2343 }))
2344 .unwrap();
2345 drop(tx);
2346
2347 self.executor
2348 .scoped(|scope| {
2349 for _ in 0..self.executor.num_cpus() {
2350 scope.spawn(async {
2351 while let Ok(job) = rx.recv().await {
2352 if let Err(err) = self
2353 .scan_dir(root_char_bag, next_entry_id.clone(), &job)
2354 .await
2355 {
2356 log::error!("error scanning {:?}: {}", job.abs_path, err);
2357 }
2358 }
2359 });
2360 }
2361 })
2362 .await;
2363
2364 self.snapshot.lock().scan_completed();
2365 }
2366
2367 Ok(())
2368 }
2369
2370 async fn scan_dir(
2371 &self,
2372 root_char_bag: CharBag,
2373 next_entry_id: Arc<AtomicUsize>,
2374 job: &ScanJob,
2375 ) -> Result<()> {
2376 let mut new_entries: Vec<Entry> = Vec::new();
2377 let mut new_jobs: Vec<Option<ScanJob>> = Vec::new();
2378 let mut ignore_stack = job.ignore_stack.clone();
2379 let mut new_ignore = None;
2380
2381 let mut child_paths = self.fs.read_dir(&job.abs_path).await?;
2382 while let Some(child_abs_path) = child_paths.next().await {
2383 let child_abs_path = match child_abs_path {
2384 Ok(child_abs_path) => child_abs_path,
2385 Err(error) => {
2386 log::error!("error processing entry {:?}", error);
2387 continue;
2388 }
2389 };
2390
2391 let child_name = child_abs_path.file_name().unwrap();
2392 let child_path: Arc<Path> = job.path.join(child_name).into();
2393 let child_metadata = match self.fs.metadata(&child_abs_path).await {
2394 Ok(Some(metadata)) => metadata,
2395 Ok(None) => continue,
2396 Err(err) => {
2397 log::error!("error processing {:?}: {:?}", child_abs_path, err);
2398 continue;
2399 }
2400 };
2401
2402 // If we find a .gitignore, add it to the stack of ignores used to determine which paths are ignored
2403 if child_name == *GITIGNORE {
2404 match build_gitignore(&child_abs_path, self.fs.as_ref()).await {
2405 Ok(ignore) => {
2406 let ignore = Arc::new(ignore);
2407 ignore_stack =
2408 ignore_stack.append(job.abs_path.as_path().into(), ignore.clone());
2409 new_ignore = Some(ignore);
2410 }
2411 Err(error) => {
2412 log::error!(
2413 "error loading .gitignore file {:?} - {:?}",
2414 child_name,
2415 error
2416 );
2417 }
2418 }
2419
2420 // Update ignore status of any child entries we've already processed to reflect the
2421 // ignore file in the current directory. Because `.gitignore` starts with a `.`,
2422 // there should rarely be too numerous. Update the ignore stack associated with any
2423 // new jobs as well.
2424 let mut new_jobs = new_jobs.iter_mut();
2425 for entry in &mut new_entries {
2426 let entry_abs_path = self.abs_path().join(&entry.path);
2427 entry.is_ignored =
2428 ignore_stack.is_abs_path_ignored(&entry_abs_path, entry.is_dir());
2429
2430 if entry.is_dir() {
2431 if let Some(job) = new_jobs.next().expect("Missing scan job for entry") {
2432 job.ignore_stack = if entry.is_ignored {
2433 IgnoreStack::all()
2434 } else {
2435 ignore_stack.clone()
2436 };
2437 }
2438 }
2439 }
2440 }
2441
2442 let mut child_entry = Entry::new(
2443 child_path.clone(),
2444 &child_metadata,
2445 &next_entry_id,
2446 root_char_bag,
2447 );
2448
2449 if child_entry.is_dir() {
2450 let is_ignored = ignore_stack.is_abs_path_ignored(&child_abs_path, true);
2451 child_entry.is_ignored = is_ignored;
2452
2453 // Avoid recursing until crash in the case of a recursive symlink
2454 if !job.ancestor_inodes.contains(&child_entry.inode) {
2455 let mut ancestor_inodes = job.ancestor_inodes.clone();
2456 ancestor_inodes.insert(child_entry.inode);
2457
2458 new_jobs.push(Some(ScanJob {
2459 abs_path: child_abs_path,
2460 path: child_path,
2461 ignore_stack: if is_ignored {
2462 IgnoreStack::all()
2463 } else {
2464 ignore_stack.clone()
2465 },
2466 ancestor_inodes,
2467 scan_queue: job.scan_queue.clone(),
2468 }));
2469 } else {
2470 new_jobs.push(None);
2471 }
2472 } else {
2473 child_entry.is_ignored = ignore_stack.is_abs_path_ignored(&child_abs_path, false);
2474 }
2475
2476 new_entries.push(child_entry);
2477 }
2478
2479 self.snapshot.lock().populate_dir(
2480 job.path.clone(),
2481 new_entries,
2482 new_ignore,
2483 self.fs.as_ref(),
2484 );
2485
2486 for new_job in new_jobs {
2487 if let Some(new_job) = new_job {
2488 job.scan_queue.send(new_job).await.unwrap();
2489 }
2490 }
2491
2492 Ok(())
2493 }
2494
2495 async fn process_events(
2496 &mut self,
2497 mut events: Vec<fsevent::Event>,
2498 received_before_initialized: bool,
2499 ) -> bool {
2500 events.sort_unstable_by(|a, b| a.path.cmp(&b.path));
2501 events.dedup_by(|a, b| a.path.starts_with(&b.path));
2502
2503 let root_char_bag;
2504 let root_abs_path;
2505 let next_entry_id;
2506 let prev_snapshot;
2507 {
2508 let mut snapshot = self.snapshot.lock();
2509 prev_snapshot = snapshot.snapshot.clone();
2510 root_char_bag = snapshot.root_char_bag;
2511 root_abs_path = snapshot.abs_path.clone();
2512 next_entry_id = snapshot.next_entry_id.clone();
2513 snapshot.scan_started();
2514 }
2515
2516 let root_canonical_path = if let Ok(path) = self.fs.canonicalize(&root_abs_path).await {
2517 path
2518 } else {
2519 return false;
2520 };
2521 let metadata = futures::future::join_all(
2522 events
2523 .iter()
2524 .map(|event| self.fs.metadata(&event.path))
2525 .collect::<Vec<_>>(),
2526 )
2527 .await;
2528
2529 // Hold the snapshot lock while clearing and re-inserting the root entries
2530 // for each event. This way, the snapshot is not observable to the foreground
2531 // thread while this operation is in-progress.
2532 let mut event_paths = Vec::with_capacity(events.len());
2533 let (scan_queue_tx, scan_queue_rx) = channel::unbounded();
2534 {
2535 let mut snapshot = self.snapshot.lock();
2536 for event in &events {
2537 if let Ok(path) = event.path.strip_prefix(&root_canonical_path) {
2538 snapshot.remove_path(path);
2539 }
2540 }
2541
2542 for (event, metadata) in events.into_iter().zip(metadata.into_iter()) {
2543 let path: Arc<Path> = match event.path.strip_prefix(&root_canonical_path) {
2544 Ok(path) => Arc::from(path.to_path_buf()),
2545 Err(_) => {
2546 log::error!(
2547 "unexpected event {:?} for root path {:?}",
2548 event.path,
2549 root_canonical_path
2550 );
2551 continue;
2552 }
2553 };
2554 event_paths.push(path.clone());
2555 let abs_path = root_abs_path.join(&path);
2556
2557 match metadata {
2558 Ok(Some(metadata)) => {
2559 let ignore_stack =
2560 snapshot.ignore_stack_for_abs_path(&abs_path, metadata.is_dir);
2561 let mut fs_entry = Entry::new(
2562 path.clone(),
2563 &metadata,
2564 snapshot.next_entry_id.as_ref(),
2565 snapshot.root_char_bag,
2566 );
2567 fs_entry.is_ignored = ignore_stack.is_all();
2568 snapshot.insert_entry(fs_entry, self.fs.as_ref());
2569
2570 let scan_id = snapshot.scan_id;
2571 if let Some(repo) = snapshot.in_dot_git(&path) {
2572 repo.repo.lock().reload_index();
2573 repo.scan_id = scan_id;
2574 }
2575
2576 let mut ancestor_inodes = snapshot.ancestor_inodes_for_path(&path);
2577 if metadata.is_dir && !ancestor_inodes.contains(&metadata.inode) {
2578 ancestor_inodes.insert(metadata.inode);
2579 self.executor
2580 .block(scan_queue_tx.send(ScanJob {
2581 abs_path,
2582 path,
2583 ignore_stack,
2584 ancestor_inodes,
2585 scan_queue: scan_queue_tx.clone(),
2586 }))
2587 .unwrap();
2588 }
2589 }
2590 Ok(None) => {}
2591 Err(err) => {
2592 // TODO - create a special 'error' entry in the entries tree to mark this
2593 log::error!("error reading file on event {:?}", err);
2594 }
2595 }
2596 }
2597 drop(scan_queue_tx);
2598 }
2599
2600 // Scan any directories that were created as part of this event batch.
2601 self.executor
2602 .scoped(|scope| {
2603 for _ in 0..self.executor.num_cpus() {
2604 scope.spawn(async {
2605 while let Ok(job) = scan_queue_rx.recv().await {
2606 if let Err(err) = self
2607 .scan_dir(root_char_bag, next_entry_id.clone(), &job)
2608 .await
2609 {
2610 log::error!("error scanning {:?}: {}", job.abs_path, err);
2611 }
2612 }
2613 });
2614 }
2615 })
2616 .await;
2617
2618 // Attempt to detect renames only over a single batch of file-system events.
2619 self.snapshot.lock().removed_entry_ids.clear();
2620
2621 self.update_ignore_statuses().await;
2622 self.update_git_repositories();
2623 self.build_change_set(prev_snapshot, event_paths, received_before_initialized);
2624 self.snapshot.lock().scan_completed();
2625 true
2626 }
2627
2628 async fn update_ignore_statuses(&self) {
2629 let mut snapshot = self.snapshot.lock().clone();
2630 let mut ignores_to_update = Vec::new();
2631 let mut ignores_to_delete = Vec::new();
2632 for (parent_abs_path, (_, scan_id)) in &snapshot.ignores_by_parent_abs_path {
2633 if let Ok(parent_path) = parent_abs_path.strip_prefix(&snapshot.abs_path) {
2634 if *scan_id == snapshot.scan_id && snapshot.entry_for_path(parent_path).is_some() {
2635 ignores_to_update.push(parent_abs_path.clone());
2636 }
2637
2638 let ignore_path = parent_path.join(&*GITIGNORE);
2639 if snapshot.entry_for_path(ignore_path).is_none() {
2640 ignores_to_delete.push(parent_abs_path.clone());
2641 }
2642 }
2643 }
2644
2645 for parent_abs_path in ignores_to_delete {
2646 snapshot.ignores_by_parent_abs_path.remove(&parent_abs_path);
2647 self.snapshot
2648 .lock()
2649 .ignores_by_parent_abs_path
2650 .remove(&parent_abs_path);
2651 }
2652
2653 let (ignore_queue_tx, ignore_queue_rx) = channel::unbounded();
2654 ignores_to_update.sort_unstable();
2655 let mut ignores_to_update = ignores_to_update.into_iter().peekable();
2656 while let Some(parent_abs_path) = ignores_to_update.next() {
2657 while ignores_to_update
2658 .peek()
2659 .map_or(false, |p| p.starts_with(&parent_abs_path))
2660 {
2661 ignores_to_update.next().unwrap();
2662 }
2663
2664 let ignore_stack = snapshot.ignore_stack_for_abs_path(&parent_abs_path, true);
2665 ignore_queue_tx
2666 .send(UpdateIgnoreStatusJob {
2667 abs_path: parent_abs_path,
2668 ignore_stack,
2669 ignore_queue: ignore_queue_tx.clone(),
2670 })
2671 .await
2672 .unwrap();
2673 }
2674 drop(ignore_queue_tx);
2675
2676 self.executor
2677 .scoped(|scope| {
2678 for _ in 0..self.executor.num_cpus() {
2679 scope.spawn(async {
2680 while let Ok(job) = ignore_queue_rx.recv().await {
2681 self.update_ignore_status(job, &snapshot).await;
2682 }
2683 });
2684 }
2685 })
2686 .await;
2687 }
2688
2689 fn update_git_repositories(&self) {
2690 let mut snapshot = self.snapshot.lock();
2691 let mut git_repositories = mem::take(&mut snapshot.git_repositories);
2692 git_repositories.retain(|repo| snapshot.entry_for_path(&repo.git_dir_path).is_some());
2693 snapshot.git_repositories = git_repositories;
2694 }
2695
2696 async fn update_ignore_status(&self, job: UpdateIgnoreStatusJob, snapshot: &LocalSnapshot) {
2697 let mut ignore_stack = job.ignore_stack;
2698 if let Some((ignore, _)) = snapshot.ignores_by_parent_abs_path.get(&job.abs_path) {
2699 ignore_stack = ignore_stack.append(job.abs_path.clone(), ignore.clone());
2700 }
2701
2702 let mut entries_by_id_edits = Vec::new();
2703 let mut entries_by_path_edits = Vec::new();
2704 let path = job.abs_path.strip_prefix(&snapshot.abs_path).unwrap();
2705 for mut entry in snapshot.child_entries(path).cloned() {
2706 let was_ignored = entry.is_ignored;
2707 let abs_path = self.abs_path().join(&entry.path);
2708 entry.is_ignored = ignore_stack.is_abs_path_ignored(&abs_path, entry.is_dir());
2709 if entry.is_dir() {
2710 let child_ignore_stack = if entry.is_ignored {
2711 IgnoreStack::all()
2712 } else {
2713 ignore_stack.clone()
2714 };
2715 job.ignore_queue
2716 .send(UpdateIgnoreStatusJob {
2717 abs_path: abs_path.into(),
2718 ignore_stack: child_ignore_stack,
2719 ignore_queue: job.ignore_queue.clone(),
2720 })
2721 .await
2722 .unwrap();
2723 }
2724
2725 if entry.is_ignored != was_ignored {
2726 let mut path_entry = snapshot.entries_by_id.get(&entry.id, &()).unwrap().clone();
2727 path_entry.scan_id = snapshot.scan_id;
2728 path_entry.is_ignored = entry.is_ignored;
2729 entries_by_id_edits.push(Edit::Insert(path_entry));
2730 entries_by_path_edits.push(Edit::Insert(entry));
2731 }
2732 }
2733
2734 let mut snapshot = self.snapshot.lock();
2735 snapshot.entries_by_path.edit(entries_by_path_edits, &());
2736 snapshot.entries_by_id.edit(entries_by_id_edits, &());
2737 }
2738
2739 fn build_change_set(
2740 &self,
2741 old_snapshot: Snapshot,
2742 event_paths: Vec<Arc<Path>>,
2743 received_before_initialized: bool,
2744 ) {
2745 let new_snapshot = self.snapshot.lock();
2746 let mut old_paths = old_snapshot.entries_by_path.cursor::<PathKey>();
2747 let mut new_paths = new_snapshot.entries_by_path.cursor::<PathKey>();
2748
2749 let mut change_set = self.changes.lock();
2750 for path in event_paths {
2751 let path = PathKey(path);
2752 old_paths.seek(&path, Bias::Left, &());
2753 new_paths.seek(&path, Bias::Left, &());
2754
2755 loop {
2756 match (old_paths.item(), new_paths.item()) {
2757 (Some(old_entry), Some(new_entry)) => {
2758 if old_entry.path > path.0
2759 && new_entry.path > path.0
2760 && !old_entry.path.starts_with(&path.0)
2761 && !new_entry.path.starts_with(&path.0)
2762 {
2763 break;
2764 }
2765
2766 match Ord::cmp(&old_entry.path, &new_entry.path) {
2767 Ordering::Less => {
2768 change_set.insert(old_entry.path.clone(), PathChange::Removed);
2769 old_paths.next(&());
2770 }
2771 Ordering::Equal => {
2772 if received_before_initialized {
2773 // If the worktree was not fully initialized when this event was generated,
2774 // we can't know whether this entry was added during the scan or whether
2775 // it was merely updated.
2776 change_set
2777 .insert(old_entry.path.clone(), PathChange::AddedOrUpdated);
2778 } else if old_entry.mtime != new_entry.mtime {
2779 change_set.insert(old_entry.path.clone(), PathChange::Updated);
2780 }
2781 old_paths.next(&());
2782 new_paths.next(&());
2783 }
2784 Ordering::Greater => {
2785 change_set.insert(new_entry.path.clone(), PathChange::Added);
2786 new_paths.next(&());
2787 }
2788 }
2789 }
2790 (Some(old_entry), None) => {
2791 change_set.insert(old_entry.path.clone(), PathChange::Removed);
2792 old_paths.next(&());
2793 }
2794 (None, Some(new_entry)) => {
2795 change_set.insert(new_entry.path.clone(), PathChange::Added);
2796 new_paths.next(&());
2797 }
2798 (None, None) => break,
2799 }
2800 }
2801 }
2802 }
2803}
2804
2805fn char_bag_for_path(root_char_bag: CharBag, path: &Path) -> CharBag {
2806 let mut result = root_char_bag;
2807 result.extend(
2808 path.to_string_lossy()
2809 .chars()
2810 .map(|c| c.to_ascii_lowercase()),
2811 );
2812 result
2813}
2814
2815struct ScanJob {
2816 abs_path: PathBuf,
2817 path: Arc<Path>,
2818 ignore_stack: Arc<IgnoreStack>,
2819 scan_queue: Sender<ScanJob>,
2820 ancestor_inodes: TreeSet<u64>,
2821}
2822
2823struct UpdateIgnoreStatusJob {
2824 abs_path: Arc<Path>,
2825 ignore_stack: Arc<IgnoreStack>,
2826 ignore_queue: Sender<UpdateIgnoreStatusJob>,
2827}
2828
2829pub trait WorktreeHandle {
2830 #[cfg(any(test, feature = "test-support"))]
2831 fn flush_fs_events<'a>(
2832 &self,
2833 cx: &'a gpui::TestAppContext,
2834 ) -> futures::future::LocalBoxFuture<'a, ()>;
2835}
2836
2837impl WorktreeHandle for ModelHandle<Worktree> {
2838 // When the worktree's FS event stream sometimes delivers "redundant" events for FS changes that
2839 // occurred before the worktree was constructed. These events can cause the worktree to perfrom
2840 // extra directory scans, and emit extra scan-state notifications.
2841 //
2842 // This function mutates the worktree's directory and waits for those mutations to be picked up,
2843 // to ensure that all redundant FS events have already been processed.
2844 #[cfg(any(test, feature = "test-support"))]
2845 fn flush_fs_events<'a>(
2846 &self,
2847 cx: &'a gpui::TestAppContext,
2848 ) -> futures::future::LocalBoxFuture<'a, ()> {
2849 use smol::future::FutureExt;
2850
2851 let filename = "fs-event-sentinel";
2852 let tree = self.clone();
2853 let (fs, root_path) = self.read_with(cx, |tree, _| {
2854 let tree = tree.as_local().unwrap();
2855 (tree.fs.clone(), tree.abs_path().clone())
2856 });
2857
2858 async move {
2859 fs.create_file(&root_path.join(filename), Default::default())
2860 .await
2861 .unwrap();
2862 tree.condition(cx, |tree, _| tree.entry_for_path(filename).is_some())
2863 .await;
2864
2865 fs.remove_file(&root_path.join(filename), Default::default())
2866 .await
2867 .unwrap();
2868 tree.condition(cx, |tree, _| tree.entry_for_path(filename).is_none())
2869 .await;
2870
2871 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2872 .await;
2873 }
2874 .boxed_local()
2875 }
2876}
2877
2878#[derive(Clone, Debug)]
2879struct TraversalProgress<'a> {
2880 max_path: &'a Path,
2881 count: usize,
2882 visible_count: usize,
2883 file_count: usize,
2884 visible_file_count: usize,
2885}
2886
2887impl<'a> TraversalProgress<'a> {
2888 fn count(&self, include_dirs: bool, include_ignored: bool) -> usize {
2889 match (include_ignored, include_dirs) {
2890 (true, true) => self.count,
2891 (true, false) => self.file_count,
2892 (false, true) => self.visible_count,
2893 (false, false) => self.visible_file_count,
2894 }
2895 }
2896}
2897
2898impl<'a> sum_tree::Dimension<'a, EntrySummary> for TraversalProgress<'a> {
2899 fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
2900 self.max_path = summary.max_path.as_ref();
2901 self.count += summary.count;
2902 self.visible_count += summary.visible_count;
2903 self.file_count += summary.file_count;
2904 self.visible_file_count += summary.visible_file_count;
2905 }
2906}
2907
2908impl<'a> Default for TraversalProgress<'a> {
2909 fn default() -> Self {
2910 Self {
2911 max_path: Path::new(""),
2912 count: 0,
2913 visible_count: 0,
2914 file_count: 0,
2915 visible_file_count: 0,
2916 }
2917 }
2918}
2919
2920pub struct Traversal<'a> {
2921 cursor: sum_tree::Cursor<'a, Entry, TraversalProgress<'a>>,
2922 include_ignored: bool,
2923 include_dirs: bool,
2924}
2925
2926impl<'a> Traversal<'a> {
2927 pub fn advance(&mut self) -> bool {
2928 self.advance_to_offset(self.offset() + 1)
2929 }
2930
2931 pub fn advance_to_offset(&mut self, offset: usize) -> bool {
2932 self.cursor.seek_forward(
2933 &TraversalTarget::Count {
2934 count: offset,
2935 include_dirs: self.include_dirs,
2936 include_ignored: self.include_ignored,
2937 },
2938 Bias::Right,
2939 &(),
2940 )
2941 }
2942
2943 pub fn advance_to_sibling(&mut self) -> bool {
2944 while let Some(entry) = self.cursor.item() {
2945 self.cursor.seek_forward(
2946 &TraversalTarget::PathSuccessor(&entry.path),
2947 Bias::Left,
2948 &(),
2949 );
2950 if let Some(entry) = self.cursor.item() {
2951 if (self.include_dirs || !entry.is_dir())
2952 && (self.include_ignored || !entry.is_ignored)
2953 {
2954 return true;
2955 }
2956 }
2957 }
2958 false
2959 }
2960
2961 pub fn entry(&self) -> Option<&'a Entry> {
2962 self.cursor.item()
2963 }
2964
2965 pub fn offset(&self) -> usize {
2966 self.cursor
2967 .start()
2968 .count(self.include_dirs, self.include_ignored)
2969 }
2970}
2971
2972impl<'a> Iterator for Traversal<'a> {
2973 type Item = &'a Entry;
2974
2975 fn next(&mut self) -> Option<Self::Item> {
2976 if let Some(item) = self.entry() {
2977 self.advance();
2978 Some(item)
2979 } else {
2980 None
2981 }
2982 }
2983}
2984
2985#[derive(Debug)]
2986enum TraversalTarget<'a> {
2987 Path(&'a Path),
2988 PathSuccessor(&'a Path),
2989 Count {
2990 count: usize,
2991 include_ignored: bool,
2992 include_dirs: bool,
2993 },
2994}
2995
2996impl<'a, 'b> SeekTarget<'a, EntrySummary, TraversalProgress<'a>> for TraversalTarget<'b> {
2997 fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: &()) -> Ordering {
2998 match self {
2999 TraversalTarget::Path(path) => path.cmp(&cursor_location.max_path),
3000 TraversalTarget::PathSuccessor(path) => {
3001 if !cursor_location.max_path.starts_with(path) {
3002 Ordering::Equal
3003 } else {
3004 Ordering::Greater
3005 }
3006 }
3007 TraversalTarget::Count {
3008 count,
3009 include_dirs,
3010 include_ignored,
3011 } => Ord::cmp(
3012 count,
3013 &cursor_location.count(*include_dirs, *include_ignored),
3014 ),
3015 }
3016 }
3017}
3018
3019struct ChildEntriesIter<'a> {
3020 parent_path: &'a Path,
3021 traversal: Traversal<'a>,
3022}
3023
3024impl<'a> Iterator for ChildEntriesIter<'a> {
3025 type Item = &'a Entry;
3026
3027 fn next(&mut self) -> Option<Self::Item> {
3028 if let Some(item) = self.traversal.entry() {
3029 if item.path.starts_with(&self.parent_path) {
3030 self.traversal.advance_to_sibling();
3031 return Some(item);
3032 }
3033 }
3034 None
3035 }
3036}
3037
3038impl<'a> From<&'a Entry> for proto::Entry {
3039 fn from(entry: &'a Entry) -> Self {
3040 Self {
3041 id: entry.id.to_proto(),
3042 is_dir: entry.is_dir(),
3043 path: entry.path.to_string_lossy().into(),
3044 inode: entry.inode,
3045 mtime: Some(entry.mtime.into()),
3046 is_symlink: entry.is_symlink,
3047 is_ignored: entry.is_ignored,
3048 }
3049 }
3050}
3051
3052impl<'a> TryFrom<(&'a CharBag, proto::Entry)> for Entry {
3053 type Error = anyhow::Error;
3054
3055 fn try_from((root_char_bag, entry): (&'a CharBag, proto::Entry)) -> Result<Self> {
3056 if let Some(mtime) = entry.mtime {
3057 let kind = if entry.is_dir {
3058 EntryKind::Dir
3059 } else {
3060 let mut char_bag = *root_char_bag;
3061 char_bag.extend(entry.path.chars().map(|c| c.to_ascii_lowercase()));
3062 EntryKind::File(char_bag)
3063 };
3064 let path: Arc<Path> = PathBuf::from(entry.path).into();
3065 Ok(Entry {
3066 id: ProjectEntryId::from_proto(entry.id),
3067 kind,
3068 path,
3069 inode: entry.inode,
3070 mtime: mtime.into(),
3071 is_symlink: entry.is_symlink,
3072 is_ignored: entry.is_ignored,
3073 })
3074 } else {
3075 Err(anyhow!(
3076 "missing mtime in remote worktree entry {:?}",
3077 entry.path
3078 ))
3079 }
3080 }
3081}
3082
3083#[cfg(test)]
3084mod tests {
3085 use super::*;
3086 use client::test::FakeHttpClient;
3087 use fs::repository::FakeGitRepository;
3088 use fs::{FakeFs, RealFs};
3089 use gpui::{executor::Deterministic, TestAppContext};
3090 use rand::prelude::*;
3091 use serde_json::json;
3092 use std::{env, fmt::Write};
3093 use util::test::temp_tree;
3094
3095 #[gpui::test]
3096 async fn test_traversal(cx: &mut TestAppContext) {
3097 let fs = FakeFs::new(cx.background());
3098 fs.insert_tree(
3099 "/root",
3100 json!({
3101 ".gitignore": "a/b\n",
3102 "a": {
3103 "b": "",
3104 "c": "",
3105 }
3106 }),
3107 )
3108 .await;
3109
3110 let http_client = FakeHttpClient::with_404_response();
3111 let client = cx.read(|cx| Client::new(http_client, cx));
3112
3113 let tree = Worktree::local(
3114 client,
3115 Arc::from(Path::new("/root")),
3116 true,
3117 fs,
3118 Default::default(),
3119 &mut cx.to_async(),
3120 )
3121 .await
3122 .unwrap();
3123 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3124 .await;
3125
3126 tree.read_with(cx, |tree, _| {
3127 assert_eq!(
3128 tree.entries(false)
3129 .map(|entry| entry.path.as_ref())
3130 .collect::<Vec<_>>(),
3131 vec![
3132 Path::new(""),
3133 Path::new(".gitignore"),
3134 Path::new("a"),
3135 Path::new("a/c"),
3136 ]
3137 );
3138 assert_eq!(
3139 tree.entries(true)
3140 .map(|entry| entry.path.as_ref())
3141 .collect::<Vec<_>>(),
3142 vec![
3143 Path::new(""),
3144 Path::new(".gitignore"),
3145 Path::new("a"),
3146 Path::new("a/b"),
3147 Path::new("a/c"),
3148 ]
3149 );
3150 })
3151 }
3152
3153 #[gpui::test(iterations = 10)]
3154 async fn test_circular_symlinks(executor: Arc<Deterministic>, cx: &mut TestAppContext) {
3155 let fs = FakeFs::new(cx.background());
3156 fs.insert_tree(
3157 "/root",
3158 json!({
3159 "lib": {
3160 "a": {
3161 "a.txt": ""
3162 },
3163 "b": {
3164 "b.txt": ""
3165 }
3166 }
3167 }),
3168 )
3169 .await;
3170 fs.insert_symlink("/root/lib/a/lib", "..".into()).await;
3171 fs.insert_symlink("/root/lib/b/lib", "..".into()).await;
3172
3173 let client = cx.read(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
3174 let tree = Worktree::local(
3175 client,
3176 Arc::from(Path::new("/root")),
3177 true,
3178 fs.clone(),
3179 Default::default(),
3180 &mut cx.to_async(),
3181 )
3182 .await
3183 .unwrap();
3184
3185 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3186 .await;
3187
3188 tree.read_with(cx, |tree, _| {
3189 assert_eq!(
3190 tree.entries(false)
3191 .map(|entry| entry.path.as_ref())
3192 .collect::<Vec<_>>(),
3193 vec![
3194 Path::new(""),
3195 Path::new("lib"),
3196 Path::new("lib/a"),
3197 Path::new("lib/a/a.txt"),
3198 Path::new("lib/a/lib"),
3199 Path::new("lib/b"),
3200 Path::new("lib/b/b.txt"),
3201 Path::new("lib/b/lib"),
3202 ]
3203 );
3204 });
3205
3206 fs.rename(
3207 Path::new("/root/lib/a/lib"),
3208 Path::new("/root/lib/a/lib-2"),
3209 Default::default(),
3210 )
3211 .await
3212 .unwrap();
3213 executor.run_until_parked();
3214 tree.read_with(cx, |tree, _| {
3215 assert_eq!(
3216 tree.entries(false)
3217 .map(|entry| entry.path.as_ref())
3218 .collect::<Vec<_>>(),
3219 vec![
3220 Path::new(""),
3221 Path::new("lib"),
3222 Path::new("lib/a"),
3223 Path::new("lib/a/a.txt"),
3224 Path::new("lib/a/lib-2"),
3225 Path::new("lib/b"),
3226 Path::new("lib/b/b.txt"),
3227 Path::new("lib/b/lib"),
3228 ]
3229 );
3230 });
3231 }
3232
3233 #[gpui::test]
3234 async fn test_rescan_with_gitignore(cx: &mut TestAppContext) {
3235 let parent_dir = temp_tree(json!({
3236 ".gitignore": "ancestor-ignored-file1\nancestor-ignored-file2\n",
3237 "tree": {
3238 ".git": {},
3239 ".gitignore": "ignored-dir\n",
3240 "tracked-dir": {
3241 "tracked-file1": "",
3242 "ancestor-ignored-file1": "",
3243 },
3244 "ignored-dir": {
3245 "ignored-file1": ""
3246 }
3247 }
3248 }));
3249 let dir = parent_dir.path().join("tree");
3250
3251 let client = cx.read(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
3252
3253 let tree = Worktree::local(
3254 client,
3255 dir.as_path(),
3256 true,
3257 Arc::new(RealFs),
3258 Default::default(),
3259 &mut cx.to_async(),
3260 )
3261 .await
3262 .unwrap();
3263 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3264 .await;
3265 tree.flush_fs_events(cx).await;
3266 cx.read(|cx| {
3267 let tree = tree.read(cx);
3268 assert!(
3269 !tree
3270 .entry_for_path("tracked-dir/tracked-file1")
3271 .unwrap()
3272 .is_ignored
3273 );
3274 assert!(
3275 tree.entry_for_path("tracked-dir/ancestor-ignored-file1")
3276 .unwrap()
3277 .is_ignored
3278 );
3279 assert!(
3280 tree.entry_for_path("ignored-dir/ignored-file1")
3281 .unwrap()
3282 .is_ignored
3283 );
3284 });
3285
3286 std::fs::write(dir.join("tracked-dir/tracked-file2"), "").unwrap();
3287 std::fs::write(dir.join("tracked-dir/ancestor-ignored-file2"), "").unwrap();
3288 std::fs::write(dir.join("ignored-dir/ignored-file2"), "").unwrap();
3289 tree.flush_fs_events(cx).await;
3290 cx.read(|cx| {
3291 let tree = tree.read(cx);
3292 assert!(
3293 !tree
3294 .entry_for_path("tracked-dir/tracked-file2")
3295 .unwrap()
3296 .is_ignored
3297 );
3298 assert!(
3299 tree.entry_for_path("tracked-dir/ancestor-ignored-file2")
3300 .unwrap()
3301 .is_ignored
3302 );
3303 assert!(
3304 tree.entry_for_path("ignored-dir/ignored-file2")
3305 .unwrap()
3306 .is_ignored
3307 );
3308 assert!(tree.entry_for_path(".git").unwrap().is_ignored);
3309 });
3310 }
3311
3312 #[gpui::test]
3313 async fn test_git_repository_for_path(cx: &mut TestAppContext) {
3314 let root = temp_tree(json!({
3315 "dir1": {
3316 ".git": {},
3317 "deps": {
3318 "dep1": {
3319 ".git": {},
3320 "src": {
3321 "a.txt": ""
3322 }
3323 }
3324 },
3325 "src": {
3326 "b.txt": ""
3327 }
3328 },
3329 "c.txt": "",
3330 }));
3331
3332 let http_client = FakeHttpClient::with_404_response();
3333 let client = cx.read(|cx| Client::new(http_client, cx));
3334 let tree = Worktree::local(
3335 client,
3336 root.path(),
3337 true,
3338 Arc::new(RealFs),
3339 Default::default(),
3340 &mut cx.to_async(),
3341 )
3342 .await
3343 .unwrap();
3344
3345 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3346 .await;
3347 tree.flush_fs_events(cx).await;
3348
3349 tree.read_with(cx, |tree, _cx| {
3350 let tree = tree.as_local().unwrap();
3351
3352 assert!(tree.repo_for("c.txt".as_ref()).is_none());
3353
3354 let repo = tree.repo_for("dir1/src/b.txt".as_ref()).unwrap();
3355 assert_eq!(repo.content_path.as_ref(), Path::new("dir1"));
3356 assert_eq!(repo.git_dir_path.as_ref(), Path::new("dir1/.git"));
3357
3358 let repo = tree.repo_for("dir1/deps/dep1/src/a.txt".as_ref()).unwrap();
3359 assert_eq!(repo.content_path.as_ref(), Path::new("dir1/deps/dep1"));
3360 assert_eq!(repo.git_dir_path.as_ref(), Path::new("dir1/deps/dep1/.git"),);
3361 });
3362
3363 let original_scan_id = tree.read_with(cx, |tree, _cx| {
3364 let tree = tree.as_local().unwrap();
3365 tree.repo_for("dir1/src/b.txt".as_ref()).unwrap().scan_id
3366 });
3367
3368 std::fs::write(root.path().join("dir1/.git/random_new_file"), "hello").unwrap();
3369 tree.flush_fs_events(cx).await;
3370
3371 tree.read_with(cx, |tree, _cx| {
3372 let tree = tree.as_local().unwrap();
3373 let new_scan_id = tree.repo_for("dir1/src/b.txt".as_ref()).unwrap().scan_id;
3374 assert_ne!(
3375 original_scan_id, new_scan_id,
3376 "original {original_scan_id}, new {new_scan_id}"
3377 );
3378 });
3379
3380 std::fs::remove_dir_all(root.path().join("dir1/.git")).unwrap();
3381 tree.flush_fs_events(cx).await;
3382
3383 tree.read_with(cx, |tree, _cx| {
3384 let tree = tree.as_local().unwrap();
3385
3386 assert!(tree.repo_for("dir1/src/b.txt".as_ref()).is_none());
3387 });
3388 }
3389
3390 #[test]
3391 fn test_changed_repos() {
3392 fn fake_entry(git_dir_path: impl AsRef<Path>, scan_id: usize) -> GitRepositoryEntry {
3393 GitRepositoryEntry {
3394 repo: Arc::new(Mutex::new(FakeGitRepository::default())),
3395 scan_id,
3396 content_path: git_dir_path.as_ref().parent().unwrap().into(),
3397 git_dir_path: git_dir_path.as_ref().into(),
3398 }
3399 }
3400
3401 let prev_repos: Vec<GitRepositoryEntry> = vec![
3402 fake_entry("/.git", 0),
3403 fake_entry("/a/.git", 0),
3404 fake_entry("/a/b/.git", 0),
3405 ];
3406
3407 let new_repos: Vec<GitRepositoryEntry> = vec![
3408 fake_entry("/a/.git", 1),
3409 fake_entry("/a/b/.git", 0),
3410 fake_entry("/a/c/.git", 0),
3411 ];
3412
3413 let res = LocalWorktree::changed_repos(&prev_repos, &new_repos);
3414
3415 // Deletion retained
3416 assert!(res
3417 .iter()
3418 .find(|repo| repo.git_dir_path.as_ref() == Path::new("/.git") && repo.scan_id == 0)
3419 .is_some());
3420
3421 // Update retained
3422 assert!(res
3423 .iter()
3424 .find(|repo| repo.git_dir_path.as_ref() == Path::new("/a/.git") && repo.scan_id == 1)
3425 .is_some());
3426
3427 // Addition retained
3428 assert!(res
3429 .iter()
3430 .find(|repo| repo.git_dir_path.as_ref() == Path::new("/a/c/.git") && repo.scan_id == 0)
3431 .is_some());
3432
3433 // Nochange, not retained
3434 assert!(res
3435 .iter()
3436 .find(|repo| repo.git_dir_path.as_ref() == Path::new("/a/b/.git") && repo.scan_id == 0)
3437 .is_none());
3438 }
3439
3440 #[gpui::test]
3441 async fn test_write_file(cx: &mut TestAppContext) {
3442 let dir = temp_tree(json!({
3443 ".git": {},
3444 ".gitignore": "ignored-dir\n",
3445 "tracked-dir": {},
3446 "ignored-dir": {}
3447 }));
3448
3449 let client = cx.read(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
3450
3451 let tree = Worktree::local(
3452 client,
3453 dir.path(),
3454 true,
3455 Arc::new(RealFs),
3456 Default::default(),
3457 &mut cx.to_async(),
3458 )
3459 .await
3460 .unwrap();
3461 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3462 .await;
3463 tree.flush_fs_events(cx).await;
3464
3465 tree.update(cx, |tree, cx| {
3466 tree.as_local().unwrap().write_file(
3467 Path::new("tracked-dir/file.txt"),
3468 "hello".into(),
3469 Default::default(),
3470 cx,
3471 )
3472 })
3473 .await
3474 .unwrap();
3475 tree.update(cx, |tree, cx| {
3476 tree.as_local().unwrap().write_file(
3477 Path::new("ignored-dir/file.txt"),
3478 "world".into(),
3479 Default::default(),
3480 cx,
3481 )
3482 })
3483 .await
3484 .unwrap();
3485
3486 tree.read_with(cx, |tree, _| {
3487 let tracked = tree.entry_for_path("tracked-dir/file.txt").unwrap();
3488 let ignored = tree.entry_for_path("ignored-dir/file.txt").unwrap();
3489 assert!(!tracked.is_ignored);
3490 assert!(ignored.is_ignored);
3491 });
3492 }
3493
3494 #[gpui::test(iterations = 30)]
3495 async fn test_create_directory(cx: &mut TestAppContext) {
3496 let client = cx.read(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
3497
3498 let fs = FakeFs::new(cx.background());
3499 fs.insert_tree(
3500 "/a",
3501 json!({
3502 "b": {},
3503 "c": {},
3504 "d": {},
3505 }),
3506 )
3507 .await;
3508
3509 let tree = Worktree::local(
3510 client,
3511 "/a".as_ref(),
3512 true,
3513 fs,
3514 Default::default(),
3515 &mut cx.to_async(),
3516 )
3517 .await
3518 .unwrap();
3519
3520 let entry = tree
3521 .update(cx, |tree, cx| {
3522 tree.as_local_mut()
3523 .unwrap()
3524 .create_entry("a/e".as_ref(), true, cx)
3525 })
3526 .await
3527 .unwrap();
3528 assert!(entry.is_dir());
3529
3530 cx.foreground().run_until_parked();
3531 tree.read_with(cx, |tree, _| {
3532 assert_eq!(tree.entry_for_path("a/e").unwrap().kind, EntryKind::Dir);
3533 });
3534 }
3535
3536 #[gpui::test(iterations = 100)]
3537 async fn test_random_worktree_changes(cx: &mut TestAppContext, mut rng: StdRng) {
3538 let operations = env::var("OPERATIONS")
3539 .map(|o| o.parse().unwrap())
3540 .unwrap_or(40);
3541 let initial_entries = env::var("INITIAL_ENTRIES")
3542 .map(|o| o.parse().unwrap())
3543 .unwrap_or(20);
3544
3545 let root_dir = Path::new("/test");
3546 let fs = FakeFs::new(cx.background()) as Arc<dyn Fs>;
3547 fs.as_fake().insert_tree(root_dir, json!({})).await;
3548 for _ in 0..initial_entries {
3549 randomly_mutate_tree(&fs, root_dir, 1.0, &mut rng).await;
3550 }
3551 log::info!("generated initial tree");
3552
3553 let next_entry_id = Arc::new(AtomicUsize::default());
3554 let client = cx.read(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
3555 let worktree = Worktree::local(
3556 client.clone(),
3557 root_dir,
3558 true,
3559 fs.clone(),
3560 next_entry_id.clone(),
3561 &mut cx.to_async(),
3562 )
3563 .await
3564 .unwrap();
3565
3566 worktree
3567 .update(cx, |tree, _| tree.as_local_mut().unwrap().scan_complete())
3568 .await;
3569
3570 let mut snapshots = Vec::new();
3571 let mut mutations_len = operations;
3572 while mutations_len > 1 {
3573 randomly_mutate_tree(&fs, root_dir, 1.0, &mut rng).await;
3574 let buffered_event_count = fs.as_fake().buffered_event_count().await;
3575 if buffered_event_count > 0 && rng.gen_bool(0.3) {
3576 let len = rng.gen_range(0..=buffered_event_count);
3577 log::info!("flushing {} events", len);
3578 fs.as_fake().flush_events(len).await;
3579 } else {
3580 randomly_mutate_tree(&fs, root_dir, 0.6, &mut rng).await;
3581 mutations_len -= 1;
3582 }
3583
3584 cx.foreground().run_until_parked();
3585 if rng.gen_bool(0.2) {
3586 log::info!("storing snapshot {}", snapshots.len());
3587 let snapshot =
3588 worktree.read_with(cx, |tree, _| tree.as_local().unwrap().snapshot());
3589 snapshots.push(snapshot);
3590 }
3591 }
3592
3593 log::info!("quiescing");
3594 fs.as_fake().flush_events(usize::MAX).await;
3595 cx.foreground().run_until_parked();
3596 let snapshot = worktree.read_with(cx, |tree, _| tree.as_local().unwrap().snapshot());
3597 snapshot.check_invariants();
3598
3599 {
3600 let new_worktree = Worktree::local(
3601 client.clone(),
3602 root_dir,
3603 true,
3604 fs.clone(),
3605 next_entry_id,
3606 &mut cx.to_async(),
3607 )
3608 .await
3609 .unwrap();
3610 new_worktree
3611 .update(cx, |tree, _| tree.as_local_mut().unwrap().scan_complete())
3612 .await;
3613 let new_snapshot =
3614 new_worktree.read_with(cx, |tree, _| tree.as_local().unwrap().snapshot());
3615 assert_eq!(snapshot.to_vec(true), new_snapshot.to_vec(true));
3616 }
3617
3618 for (i, mut prev_snapshot) in snapshots.into_iter().enumerate() {
3619 let include_ignored = rng.gen::<bool>();
3620 if !include_ignored {
3621 let mut entries_by_path_edits = Vec::new();
3622 let mut entries_by_id_edits = Vec::new();
3623 for entry in prev_snapshot
3624 .entries_by_id
3625 .cursor::<()>()
3626 .filter(|e| e.is_ignored)
3627 {
3628 entries_by_path_edits.push(Edit::Remove(PathKey(entry.path.clone())));
3629 entries_by_id_edits.push(Edit::Remove(entry.id));
3630 }
3631
3632 prev_snapshot
3633 .entries_by_path
3634 .edit(entries_by_path_edits, &());
3635 prev_snapshot.entries_by_id.edit(entries_by_id_edits, &());
3636 }
3637
3638 let update = snapshot.build_update(&prev_snapshot, 0, 0, include_ignored);
3639 prev_snapshot.apply_remote_update(update.clone()).unwrap();
3640 assert_eq!(
3641 prev_snapshot.to_vec(include_ignored),
3642 snapshot.to_vec(include_ignored),
3643 "wrong update for snapshot {i}. update: {:?}",
3644 update
3645 );
3646 }
3647 }
3648
3649 async fn randomly_mutate_tree(
3650 fs: &Arc<dyn Fs>,
3651 root_path: &Path,
3652 insertion_probability: f64,
3653 rng: &mut impl Rng,
3654 ) {
3655 let mut files = Vec::new();
3656 let mut dirs = Vec::new();
3657 for path in fs.as_fake().paths().await {
3658 if path.starts_with(root_path) {
3659 if fs.is_file(&path).await {
3660 files.push(path);
3661 } else {
3662 dirs.push(path);
3663 }
3664 }
3665 }
3666
3667 if (files.is_empty() && dirs.len() == 1) || rng.gen_bool(insertion_probability) {
3668 let path = dirs.choose(rng).unwrap();
3669 let new_path = path.join(gen_name(rng));
3670
3671 if rng.gen() {
3672 log::info!(
3673 "creating dir {:?}",
3674 new_path.strip_prefix(root_path).unwrap()
3675 );
3676 fs.create_dir(&new_path).await.unwrap();
3677 } else {
3678 log::info!(
3679 "creating file {:?}",
3680 new_path.strip_prefix(root_path).unwrap()
3681 );
3682 fs.create_file(&new_path, Default::default()).await.unwrap();
3683 }
3684 } else if rng.gen_bool(0.05) {
3685 let ignore_dir_path = dirs.choose(rng).unwrap();
3686 let ignore_path = ignore_dir_path.join(&*GITIGNORE);
3687
3688 let subdirs = dirs
3689 .iter()
3690 .filter(|d| d.starts_with(&ignore_dir_path))
3691 .cloned()
3692 .collect::<Vec<_>>();
3693 let subfiles = files
3694 .iter()
3695 .filter(|d| d.starts_with(&ignore_dir_path))
3696 .cloned()
3697 .collect::<Vec<_>>();
3698 let files_to_ignore = {
3699 let len = rng.gen_range(0..=subfiles.len());
3700 subfiles.choose_multiple(rng, len)
3701 };
3702 let dirs_to_ignore = {
3703 let len = rng.gen_range(0..subdirs.len());
3704 subdirs.choose_multiple(rng, len)
3705 };
3706
3707 let mut ignore_contents = String::new();
3708 for path_to_ignore in files_to_ignore.chain(dirs_to_ignore) {
3709 writeln!(
3710 ignore_contents,
3711 "{}",
3712 path_to_ignore
3713 .strip_prefix(&ignore_dir_path)
3714 .unwrap()
3715 .to_str()
3716 .unwrap()
3717 )
3718 .unwrap();
3719 }
3720 log::info!(
3721 "creating gitignore {:?} with contents:\n{}",
3722 ignore_path.strip_prefix(&root_path).unwrap(),
3723 ignore_contents
3724 );
3725 fs.save(
3726 &ignore_path,
3727 &ignore_contents.as_str().into(),
3728 Default::default(),
3729 )
3730 .await
3731 .unwrap();
3732 } else {
3733 let old_path = {
3734 let file_path = files.choose(rng);
3735 let dir_path = dirs[1..].choose(rng);
3736 file_path.into_iter().chain(dir_path).choose(rng).unwrap()
3737 };
3738
3739 let is_rename = rng.gen();
3740 if is_rename {
3741 let new_path_parent = dirs
3742 .iter()
3743 .filter(|d| !d.starts_with(old_path))
3744 .choose(rng)
3745 .unwrap();
3746
3747 let overwrite_existing_dir =
3748 !old_path.starts_with(&new_path_parent) && rng.gen_bool(0.3);
3749 let new_path = if overwrite_existing_dir {
3750 fs.remove_dir(
3751 &new_path_parent,
3752 RemoveOptions {
3753 recursive: true,
3754 ignore_if_not_exists: true,
3755 },
3756 )
3757 .await
3758 .unwrap();
3759 new_path_parent.to_path_buf()
3760 } else {
3761 new_path_parent.join(gen_name(rng))
3762 };
3763
3764 log::info!(
3765 "renaming {:?} to {}{:?}",
3766 old_path.strip_prefix(&root_path).unwrap(),
3767 if overwrite_existing_dir {
3768 "overwrite "
3769 } else {
3770 ""
3771 },
3772 new_path.strip_prefix(&root_path).unwrap()
3773 );
3774 fs.rename(
3775 &old_path,
3776 &new_path,
3777 fs::RenameOptions {
3778 overwrite: true,
3779 ignore_if_exists: true,
3780 },
3781 )
3782 .await
3783 .unwrap();
3784 } else if fs.is_file(&old_path).await {
3785 log::info!(
3786 "deleting file {:?}",
3787 old_path.strip_prefix(&root_path).unwrap()
3788 );
3789 fs.remove_file(old_path, Default::default()).await.unwrap();
3790 } else {
3791 log::info!(
3792 "deleting dir {:?}",
3793 old_path.strip_prefix(&root_path).unwrap()
3794 );
3795 fs.remove_dir(
3796 &old_path,
3797 RemoveOptions {
3798 recursive: true,
3799 ignore_if_not_exists: true,
3800 },
3801 )
3802 .await
3803 .unwrap();
3804 }
3805 }
3806 }
3807
3808 fn gen_name(rng: &mut impl Rng) -> String {
3809 (0..6)
3810 .map(|_| rng.sample(rand::distributions::Alphanumeric))
3811 .map(char::from)
3812 .collect()
3813 }
3814
3815 impl LocalSnapshot {
3816 fn check_invariants(&self) {
3817 let mut files = self.files(true, 0);
3818 let mut visible_files = self.files(false, 0);
3819 for entry in self.entries_by_path.cursor::<()>() {
3820 if entry.is_file() {
3821 assert_eq!(files.next().unwrap().inode, entry.inode);
3822 if !entry.is_ignored {
3823 assert_eq!(visible_files.next().unwrap().inode, entry.inode);
3824 }
3825 }
3826 }
3827 assert!(files.next().is_none());
3828 assert!(visible_files.next().is_none());
3829
3830 let mut bfs_paths = Vec::new();
3831 let mut stack = vec![Path::new("")];
3832 while let Some(path) = stack.pop() {
3833 bfs_paths.push(path);
3834 let ix = stack.len();
3835 for child_entry in self.child_entries(path) {
3836 stack.insert(ix, &child_entry.path);
3837 }
3838 }
3839
3840 let dfs_paths_via_iter = self
3841 .entries_by_path
3842 .cursor::<()>()
3843 .map(|e| e.path.as_ref())
3844 .collect::<Vec<_>>();
3845 assert_eq!(bfs_paths, dfs_paths_via_iter);
3846
3847 let dfs_paths_via_traversal = self
3848 .entries(true)
3849 .map(|e| e.path.as_ref())
3850 .collect::<Vec<_>>();
3851 assert_eq!(dfs_paths_via_traversal, dfs_paths_via_iter);
3852
3853 for ignore_parent_abs_path in self.ignores_by_parent_abs_path.keys() {
3854 let ignore_parent_path =
3855 ignore_parent_abs_path.strip_prefix(&self.abs_path).unwrap();
3856 assert!(self.entry_for_path(&ignore_parent_path).is_some());
3857 assert!(self
3858 .entry_for_path(ignore_parent_path.join(&*GITIGNORE))
3859 .is_some());
3860 }
3861 }
3862
3863 fn to_vec(&self, include_ignored: bool) -> Vec<(&Path, u64, bool)> {
3864 let mut paths = Vec::new();
3865 for entry in self.entries_by_path.cursor::<()>() {
3866 if include_ignored || !entry.is_ignored {
3867 paths.push((entry.path.as_ref(), entry.inode, entry.is_ignored));
3868 }
3869 }
3870 paths.sort_by(|a, b| a.0.cmp(b.0));
3871 paths
3872 }
3873 }
3874}