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