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