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::{repository::GitRepository, Fs};
9use fs::{HomeDir, LineEnding};
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 let worktree = self.worktree.read(cx);
1843 if worktree.is_visible() {
1844 full_path.push(worktree.root_name());
1845 } else {
1846 let home_dir = cx.global::<HomeDir>();
1847 let local_path = worktree.as_local().map(|local| local.abs_path.clone());
1848 if let Some(path) = local_path {
1849 if let Ok(path) = path.strip_prefix(home_dir.0.as_path()) {
1850 full_path.push("~");
1851 full_path.push(path);
1852 } else {
1853 full_path.push(path)
1854 }
1855 } else {
1856 full_path.push(Path::new("/host-filesystem/"))
1857 }
1858 }
1859 if self.path.components().next().is_some() {
1860 full_path.push(&self.path);
1861 }
1862 full_path
1863 }
1864
1865 /// Returns the last component of this handle's absolute path. If this handle refers to the root
1866 /// of its worktree, then this method will return the name of the worktree itself.
1867 fn file_name<'a>(&'a self, cx: &'a AppContext) -> &'a OsStr {
1868 self.path
1869 .file_name()
1870 .unwrap_or_else(|| OsStr::new(&self.worktree.read(cx).root_name))
1871 }
1872
1873 fn is_deleted(&self) -> bool {
1874 self.is_deleted
1875 }
1876
1877 fn save(
1878 &self,
1879 buffer_id: u64,
1880 text: Rope,
1881 version: clock::Global,
1882 line_ending: LineEnding,
1883 cx: &mut MutableAppContext,
1884 ) -> Task<Result<(clock::Global, String, SystemTime)>> {
1885 self.worktree.update(cx, |worktree, cx| match worktree {
1886 Worktree::Local(worktree) => {
1887 let rpc = worktree.client.clone();
1888 let project_id = worktree.share.as_ref().map(|share| share.project_id);
1889 let fingerprint = text.fingerprint();
1890 let save = worktree.write_file(self.path.clone(), text, line_ending, cx);
1891 cx.background().spawn(async move {
1892 let entry = save.await?;
1893 if let Some(project_id) = project_id {
1894 rpc.send(proto::BufferSaved {
1895 project_id,
1896 buffer_id,
1897 version: serialize_version(&version),
1898 mtime: Some(entry.mtime.into()),
1899 fingerprint: fingerprint.clone(),
1900 })?;
1901 }
1902 Ok((version, fingerprint, entry.mtime))
1903 })
1904 }
1905 Worktree::Remote(worktree) => {
1906 let rpc = worktree.client.clone();
1907 let project_id = worktree.project_id;
1908 cx.foreground().spawn(async move {
1909 let response = rpc
1910 .request(proto::SaveBuffer {
1911 project_id,
1912 buffer_id,
1913 version: serialize_version(&version),
1914 })
1915 .await?;
1916 let version = deserialize_version(response.version);
1917 let mtime = response
1918 .mtime
1919 .ok_or_else(|| anyhow!("missing mtime"))?
1920 .into();
1921 Ok((version, response.fingerprint, mtime))
1922 })
1923 }
1924 })
1925 }
1926
1927 fn as_any(&self) -> &dyn Any {
1928 self
1929 }
1930
1931 fn to_proto(&self) -> rpc::proto::File {
1932 rpc::proto::File {
1933 worktree_id: self.worktree.id() as u64,
1934 entry_id: self.entry_id.to_proto(),
1935 path: self.path.to_string_lossy().into(),
1936 mtime: Some(self.mtime.into()),
1937 is_deleted: self.is_deleted,
1938 }
1939 }
1940}
1941
1942impl language::LocalFile for File {
1943 fn abs_path(&self, cx: &AppContext) -> PathBuf {
1944 self.worktree
1945 .read(cx)
1946 .as_local()
1947 .unwrap()
1948 .abs_path
1949 .join(&self.path)
1950 }
1951
1952 fn load(&self, cx: &AppContext) -> Task<Result<String>> {
1953 let worktree = self.worktree.read(cx).as_local().unwrap();
1954 let abs_path = worktree.absolutize(&self.path);
1955 let fs = worktree.fs.clone();
1956 cx.background()
1957 .spawn(async move { fs.load(&abs_path).await })
1958 }
1959
1960 fn buffer_reloaded(
1961 &self,
1962 buffer_id: u64,
1963 version: &clock::Global,
1964 fingerprint: String,
1965 line_ending: LineEnding,
1966 mtime: SystemTime,
1967 cx: &mut MutableAppContext,
1968 ) {
1969 let worktree = self.worktree.read(cx).as_local().unwrap();
1970 if let Some(project_id) = worktree.share.as_ref().map(|share| share.project_id) {
1971 worktree
1972 .client
1973 .send(proto::BufferReloaded {
1974 project_id,
1975 buffer_id,
1976 version: serialize_version(version),
1977 mtime: Some(mtime.into()),
1978 fingerprint,
1979 line_ending: serialize_line_ending(line_ending) as i32,
1980 })
1981 .log_err();
1982 }
1983 }
1984}
1985
1986impl File {
1987 pub fn from_proto(
1988 proto: rpc::proto::File,
1989 worktree: ModelHandle<Worktree>,
1990 cx: &AppContext,
1991 ) -> Result<Self> {
1992 let worktree_id = worktree
1993 .read(cx)
1994 .as_remote()
1995 .ok_or_else(|| anyhow!("not remote"))?
1996 .id();
1997
1998 if worktree_id.to_proto() != proto.worktree_id {
1999 return Err(anyhow!("worktree id does not match file"));
2000 }
2001
2002 Ok(Self {
2003 worktree,
2004 path: Path::new(&proto.path).into(),
2005 mtime: proto.mtime.ok_or_else(|| anyhow!("no timestamp"))?.into(),
2006 entry_id: ProjectEntryId::from_proto(proto.entry_id),
2007 is_local: false,
2008 is_deleted: proto.is_deleted,
2009 })
2010 }
2011
2012 pub fn from_dyn(file: Option<&dyn language::File>) -> Option<&Self> {
2013 file.and_then(|f| f.as_any().downcast_ref())
2014 }
2015
2016 pub fn worktree_id(&self, cx: &AppContext) -> WorktreeId {
2017 self.worktree.read(cx).id()
2018 }
2019
2020 pub fn project_entry_id(&self, _: &AppContext) -> Option<ProjectEntryId> {
2021 if self.is_deleted {
2022 None
2023 } else {
2024 Some(self.entry_id)
2025 }
2026 }
2027}
2028
2029#[derive(Clone, Debug, PartialEq, Eq)]
2030pub struct Entry {
2031 pub id: ProjectEntryId,
2032 pub kind: EntryKind,
2033 pub path: Arc<Path>,
2034 pub inode: u64,
2035 pub mtime: SystemTime,
2036 pub is_symlink: bool,
2037 pub is_ignored: bool,
2038}
2039
2040#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2041pub enum EntryKind {
2042 PendingDir,
2043 Dir,
2044 File(CharBag),
2045}
2046
2047impl Entry {
2048 fn new(
2049 path: Arc<Path>,
2050 metadata: &fs::Metadata,
2051 next_entry_id: &AtomicUsize,
2052 root_char_bag: CharBag,
2053 ) -> Self {
2054 Self {
2055 id: ProjectEntryId::new(next_entry_id),
2056 kind: if metadata.is_dir {
2057 EntryKind::PendingDir
2058 } else {
2059 EntryKind::File(char_bag_for_path(root_char_bag, &path))
2060 },
2061 path,
2062 inode: metadata.inode,
2063 mtime: metadata.mtime,
2064 is_symlink: metadata.is_symlink,
2065 is_ignored: false,
2066 }
2067 }
2068
2069 pub fn is_dir(&self) -> bool {
2070 matches!(self.kind, EntryKind::Dir | EntryKind::PendingDir)
2071 }
2072
2073 pub fn is_file(&self) -> bool {
2074 matches!(self.kind, EntryKind::File(_))
2075 }
2076}
2077
2078impl sum_tree::Item for Entry {
2079 type Summary = EntrySummary;
2080
2081 fn summary(&self) -> Self::Summary {
2082 let visible_count = if self.is_ignored { 0 } else { 1 };
2083 let file_count;
2084 let visible_file_count;
2085 if self.is_file() {
2086 file_count = 1;
2087 visible_file_count = visible_count;
2088 } else {
2089 file_count = 0;
2090 visible_file_count = 0;
2091 }
2092
2093 EntrySummary {
2094 max_path: self.path.clone(),
2095 count: 1,
2096 visible_count,
2097 file_count,
2098 visible_file_count,
2099 }
2100 }
2101}
2102
2103impl sum_tree::KeyedItem for Entry {
2104 type Key = PathKey;
2105
2106 fn key(&self) -> Self::Key {
2107 PathKey(self.path.clone())
2108 }
2109}
2110
2111#[derive(Clone, Debug)]
2112pub struct EntrySummary {
2113 max_path: Arc<Path>,
2114 count: usize,
2115 visible_count: usize,
2116 file_count: usize,
2117 visible_file_count: usize,
2118}
2119
2120impl Default for EntrySummary {
2121 fn default() -> Self {
2122 Self {
2123 max_path: Arc::from(Path::new("")),
2124 count: 0,
2125 visible_count: 0,
2126 file_count: 0,
2127 visible_file_count: 0,
2128 }
2129 }
2130}
2131
2132impl sum_tree::Summary for EntrySummary {
2133 type Context = ();
2134
2135 fn add_summary(&mut self, rhs: &Self, _: &()) {
2136 self.max_path = rhs.max_path.clone();
2137 self.count += rhs.count;
2138 self.visible_count += rhs.visible_count;
2139 self.file_count += rhs.file_count;
2140 self.visible_file_count += rhs.visible_file_count;
2141 }
2142}
2143
2144#[derive(Clone, Debug)]
2145struct PathEntry {
2146 id: ProjectEntryId,
2147 path: Arc<Path>,
2148 is_ignored: bool,
2149 scan_id: usize,
2150}
2151
2152impl sum_tree::Item for PathEntry {
2153 type Summary = PathEntrySummary;
2154
2155 fn summary(&self) -> Self::Summary {
2156 PathEntrySummary { max_id: self.id }
2157 }
2158}
2159
2160impl sum_tree::KeyedItem for PathEntry {
2161 type Key = ProjectEntryId;
2162
2163 fn key(&self) -> Self::Key {
2164 self.id
2165 }
2166}
2167
2168#[derive(Clone, Debug, Default)]
2169struct PathEntrySummary {
2170 max_id: ProjectEntryId,
2171}
2172
2173impl sum_tree::Summary for PathEntrySummary {
2174 type Context = ();
2175
2176 fn add_summary(&mut self, summary: &Self, _: &Self::Context) {
2177 self.max_id = summary.max_id;
2178 }
2179}
2180
2181impl<'a> sum_tree::Dimension<'a, PathEntrySummary> for ProjectEntryId {
2182 fn add_summary(&mut self, summary: &'a PathEntrySummary, _: &()) {
2183 *self = summary.max_id;
2184 }
2185}
2186
2187#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
2188pub struct PathKey(Arc<Path>);
2189
2190impl Default for PathKey {
2191 fn default() -> Self {
2192 Self(Path::new("").into())
2193 }
2194}
2195
2196impl<'a> sum_tree::Dimension<'a, EntrySummary> for PathKey {
2197 fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
2198 self.0 = summary.max_path.clone();
2199 }
2200}
2201
2202struct BackgroundScanner {
2203 fs: Arc<dyn Fs>,
2204 snapshot: Arc<Mutex<LocalSnapshot>>,
2205 notify: UnboundedSender<ScanState>,
2206 executor: Arc<executor::Background>,
2207}
2208
2209impl BackgroundScanner {
2210 fn new(
2211 snapshot: Arc<Mutex<LocalSnapshot>>,
2212 notify: UnboundedSender<ScanState>,
2213 fs: Arc<dyn Fs>,
2214 executor: Arc<executor::Background>,
2215 ) -> Self {
2216 Self {
2217 fs,
2218 snapshot,
2219 notify,
2220 executor,
2221 }
2222 }
2223
2224 fn abs_path(&self) -> Arc<Path> {
2225 self.snapshot.lock().abs_path.clone()
2226 }
2227
2228 fn snapshot(&self) -> LocalSnapshot {
2229 self.snapshot.lock().clone()
2230 }
2231
2232 async fn run(mut self, events_rx: impl Stream<Item = Vec<fsevent::Event>>) {
2233 if self.notify.unbounded_send(ScanState::Initializing).is_err() {
2234 return;
2235 }
2236
2237 if let Err(err) = self.scan_dirs().await {
2238 if self
2239 .notify
2240 .unbounded_send(ScanState::Err(Arc::new(err)))
2241 .is_err()
2242 {
2243 return;
2244 }
2245 }
2246
2247 if self.notify.unbounded_send(ScanState::Idle).is_err() {
2248 return;
2249 }
2250
2251 futures::pin_mut!(events_rx);
2252
2253 while let Some(mut events) = events_rx.next().await {
2254 while let Poll::Ready(Some(additional_events)) = futures::poll!(events_rx.next()) {
2255 events.extend(additional_events);
2256 }
2257
2258 if self.notify.unbounded_send(ScanState::Updating).is_err() {
2259 break;
2260 }
2261
2262 if !self.process_events(events).await {
2263 break;
2264 }
2265
2266 if self.notify.unbounded_send(ScanState::Idle).is_err() {
2267 break;
2268 }
2269 }
2270 }
2271
2272 async fn scan_dirs(&mut self) -> Result<()> {
2273 let root_char_bag;
2274 let root_abs_path;
2275 let root_inode;
2276 let is_dir;
2277 let next_entry_id;
2278 {
2279 let snapshot = self.snapshot.lock();
2280 root_char_bag = snapshot.root_char_bag;
2281 root_abs_path = snapshot.abs_path.clone();
2282 root_inode = snapshot.root_entry().map(|e| e.inode);
2283 is_dir = snapshot.root_entry().map_or(false, |e| e.is_dir());
2284 next_entry_id = snapshot.next_entry_id.clone();
2285 };
2286
2287 // Populate ignores above the root.
2288 for ancestor in root_abs_path.ancestors().skip(1) {
2289 if let Ok(ignore) = build_gitignore(&ancestor.join(&*GITIGNORE), self.fs.as_ref()).await
2290 {
2291 self.snapshot
2292 .lock()
2293 .ignores_by_parent_abs_path
2294 .insert(ancestor.into(), (ignore.into(), 0));
2295 }
2296 }
2297
2298 let ignore_stack = {
2299 let mut snapshot = self.snapshot.lock();
2300 let ignore_stack = snapshot.ignore_stack_for_abs_path(&root_abs_path, true);
2301 if ignore_stack.is_all() {
2302 if let Some(mut root_entry) = snapshot.root_entry().cloned() {
2303 root_entry.is_ignored = true;
2304 snapshot.insert_entry(root_entry, self.fs.as_ref());
2305 }
2306 }
2307 ignore_stack
2308 };
2309
2310 if is_dir {
2311 let path: Arc<Path> = Arc::from(Path::new(""));
2312 let mut ancestor_inodes = TreeSet::default();
2313 if let Some(root_inode) = root_inode {
2314 ancestor_inodes.insert(root_inode);
2315 }
2316
2317 let (tx, rx) = channel::unbounded();
2318 self.executor
2319 .block(tx.send(ScanJob {
2320 abs_path: root_abs_path.to_path_buf(),
2321 path,
2322 ignore_stack,
2323 ancestor_inodes,
2324 scan_queue: tx.clone(),
2325 }))
2326 .unwrap();
2327 drop(tx);
2328
2329 self.executor
2330 .scoped(|scope| {
2331 for _ in 0..self.executor.num_cpus() {
2332 scope.spawn(async {
2333 while let Ok(job) = rx.recv().await {
2334 if let Err(err) = self
2335 .scan_dir(root_char_bag, next_entry_id.clone(), &job)
2336 .await
2337 {
2338 log::error!("error scanning {:?}: {}", job.abs_path, err);
2339 }
2340 }
2341 });
2342 }
2343 })
2344 .await;
2345 }
2346
2347 Ok(())
2348 }
2349
2350 async fn scan_dir(
2351 &self,
2352 root_char_bag: CharBag,
2353 next_entry_id: Arc<AtomicUsize>,
2354 job: &ScanJob,
2355 ) -> Result<()> {
2356 let mut new_entries: Vec<Entry> = Vec::new();
2357 let mut new_jobs: Vec<ScanJob> = Vec::new();
2358 let mut ignore_stack = job.ignore_stack.clone();
2359 let mut new_ignore = None;
2360
2361 let mut child_paths = self.fs.read_dir(&job.abs_path).await?;
2362 while let Some(child_abs_path) = child_paths.next().await {
2363 let child_abs_path = match child_abs_path {
2364 Ok(child_abs_path) => child_abs_path,
2365 Err(error) => {
2366 log::error!("error processing entry {:?}", error);
2367 continue;
2368 }
2369 };
2370 let child_name = child_abs_path.file_name().unwrap();
2371 let child_path: Arc<Path> = job.path.join(child_name).into();
2372 let child_metadata = match self.fs.metadata(&child_abs_path).await {
2373 Ok(Some(metadata)) => metadata,
2374 Ok(None) => continue,
2375 Err(err) => {
2376 log::error!("error processing {:?}: {:?}", child_abs_path, err);
2377 continue;
2378 }
2379 };
2380
2381 // If we find a .gitignore, add it to the stack of ignores used to determine which paths are ignored
2382 if child_name == *GITIGNORE {
2383 match build_gitignore(&child_abs_path, self.fs.as_ref()).await {
2384 Ok(ignore) => {
2385 let ignore = Arc::new(ignore);
2386 ignore_stack =
2387 ignore_stack.append(job.abs_path.as_path().into(), ignore.clone());
2388 new_ignore = Some(ignore);
2389 }
2390 Err(error) => {
2391 log::error!(
2392 "error loading .gitignore file {:?} - {:?}",
2393 child_name,
2394 error
2395 );
2396 }
2397 }
2398
2399 // Update ignore status of any child entries we've already processed to reflect the
2400 // ignore file in the current directory. Because `.gitignore` starts with a `.`,
2401 // there should rarely be too numerous. Update the ignore stack associated with any
2402 // new jobs as well.
2403 let mut new_jobs = new_jobs.iter_mut();
2404 for entry in &mut new_entries {
2405 let entry_abs_path = self.abs_path().join(&entry.path);
2406 entry.is_ignored =
2407 ignore_stack.is_abs_path_ignored(&entry_abs_path, entry.is_dir());
2408 if entry.is_dir() {
2409 new_jobs.next().unwrap().ignore_stack = if entry.is_ignored {
2410 IgnoreStack::all()
2411 } else {
2412 ignore_stack.clone()
2413 };
2414 }
2415 }
2416 }
2417
2418 let mut child_entry = Entry::new(
2419 child_path.clone(),
2420 &child_metadata,
2421 &next_entry_id,
2422 root_char_bag,
2423 );
2424
2425 if child_entry.is_dir() {
2426 let is_ignored = ignore_stack.is_abs_path_ignored(&child_abs_path, true);
2427 child_entry.is_ignored = is_ignored;
2428
2429 if !job.ancestor_inodes.contains(&child_entry.inode) {
2430 let mut ancestor_inodes = job.ancestor_inodes.clone();
2431 ancestor_inodes.insert(child_entry.inode);
2432 new_jobs.push(ScanJob {
2433 abs_path: child_abs_path,
2434 path: child_path,
2435 ignore_stack: if is_ignored {
2436 IgnoreStack::all()
2437 } else {
2438 ignore_stack.clone()
2439 },
2440 ancestor_inodes,
2441 scan_queue: job.scan_queue.clone(),
2442 });
2443 }
2444 } else {
2445 child_entry.is_ignored = ignore_stack.is_abs_path_ignored(&child_abs_path, false);
2446 }
2447
2448 new_entries.push(child_entry);
2449 }
2450
2451 self.snapshot.lock().populate_dir(
2452 job.path.clone(),
2453 new_entries,
2454 new_ignore,
2455 self.fs.as_ref(),
2456 );
2457 for new_job in new_jobs {
2458 job.scan_queue.send(new_job).await.unwrap();
2459 }
2460
2461 Ok(())
2462 }
2463
2464 async fn process_events(&mut self, mut events: Vec<fsevent::Event>) -> bool {
2465 events.sort_unstable_by(|a, b| a.path.cmp(&b.path));
2466 events.dedup_by(|a, b| a.path.starts_with(&b.path));
2467
2468 let root_char_bag;
2469 let root_abs_path;
2470 let next_entry_id;
2471 {
2472 let snapshot = self.snapshot.lock();
2473 root_char_bag = snapshot.root_char_bag;
2474 root_abs_path = snapshot.abs_path.clone();
2475 next_entry_id = snapshot.next_entry_id.clone();
2476 }
2477
2478 let root_canonical_path = if let Ok(path) = self.fs.canonicalize(&root_abs_path).await {
2479 path
2480 } else {
2481 return false;
2482 };
2483 let metadata = futures::future::join_all(
2484 events
2485 .iter()
2486 .map(|event| self.fs.metadata(&event.path))
2487 .collect::<Vec<_>>(),
2488 )
2489 .await;
2490
2491 // Hold the snapshot lock while clearing and re-inserting the root entries
2492 // for each event. This way, the snapshot is not observable to the foreground
2493 // thread while this operation is in-progress.
2494 let (scan_queue_tx, scan_queue_rx) = channel::unbounded();
2495 {
2496 let mut snapshot = self.snapshot.lock();
2497 snapshot.scan_id += 1;
2498 for event in &events {
2499 if let Ok(path) = event.path.strip_prefix(&root_canonical_path) {
2500 snapshot.remove_path(path);
2501 }
2502 }
2503
2504 for (event, metadata) in events.into_iter().zip(metadata.into_iter()) {
2505 let path: Arc<Path> = match event.path.strip_prefix(&root_canonical_path) {
2506 Ok(path) => Arc::from(path.to_path_buf()),
2507 Err(_) => {
2508 log::error!(
2509 "unexpected event {:?} for root path {:?}",
2510 event.path,
2511 root_canonical_path
2512 );
2513 continue;
2514 }
2515 };
2516 let abs_path = root_abs_path.join(&path);
2517
2518 match metadata {
2519 Ok(Some(metadata)) => {
2520 let ignore_stack =
2521 snapshot.ignore_stack_for_abs_path(&abs_path, metadata.is_dir);
2522 let mut fs_entry = Entry::new(
2523 path.clone(),
2524 &metadata,
2525 snapshot.next_entry_id.as_ref(),
2526 snapshot.root_char_bag,
2527 );
2528 fs_entry.is_ignored = ignore_stack.is_all();
2529 snapshot.insert_entry(fs_entry, self.fs.as_ref());
2530
2531 let scan_id = snapshot.scan_id;
2532 if let Some(repo) = snapshot.in_dot_git(&path) {
2533 repo.repo.lock().reload_index();
2534 repo.scan_id = scan_id;
2535 }
2536
2537 let mut ancestor_inodes = snapshot.ancestor_inodes_for_path(&path);
2538 if metadata.is_dir && !ancestor_inodes.contains(&metadata.inode) {
2539 ancestor_inodes.insert(metadata.inode);
2540 self.executor
2541 .block(scan_queue_tx.send(ScanJob {
2542 abs_path,
2543 path,
2544 ignore_stack,
2545 ancestor_inodes,
2546 scan_queue: scan_queue_tx.clone(),
2547 }))
2548 .unwrap();
2549 }
2550 }
2551 Ok(None) => {}
2552 Err(err) => {
2553 // TODO - create a special 'error' entry in the entries tree to mark this
2554 log::error!("error reading file on event {:?}", err);
2555 }
2556 }
2557 }
2558 drop(scan_queue_tx);
2559 }
2560
2561 // Scan any directories that were created as part of this event batch.
2562 self.executor
2563 .scoped(|scope| {
2564 for _ in 0..self.executor.num_cpus() {
2565 scope.spawn(async {
2566 while let Ok(job) = scan_queue_rx.recv().await {
2567 if let Err(err) = self
2568 .scan_dir(root_char_bag, next_entry_id.clone(), &job)
2569 .await
2570 {
2571 log::error!("error scanning {:?}: {}", job.abs_path, err);
2572 }
2573 }
2574 });
2575 }
2576 })
2577 .await;
2578
2579 // Attempt to detect renames only over a single batch of file-system events.
2580 self.snapshot.lock().removed_entry_ids.clear();
2581
2582 self.update_ignore_statuses().await;
2583 self.update_git_repositories();
2584 true
2585 }
2586
2587 async fn update_ignore_statuses(&self) {
2588 let mut snapshot = self.snapshot();
2589
2590 let mut ignores_to_update = Vec::new();
2591 let mut ignores_to_delete = Vec::new();
2592 for (parent_abs_path, (_, scan_id)) in &snapshot.ignores_by_parent_abs_path {
2593 if let Ok(parent_path) = parent_abs_path.strip_prefix(&snapshot.abs_path) {
2594 if *scan_id == snapshot.scan_id && snapshot.entry_for_path(parent_path).is_some() {
2595 ignores_to_update.push(parent_abs_path.clone());
2596 }
2597
2598 let ignore_path = parent_path.join(&*GITIGNORE);
2599 if snapshot.entry_for_path(ignore_path).is_none() {
2600 ignores_to_delete.push(parent_abs_path.clone());
2601 }
2602 }
2603 }
2604
2605 for parent_abs_path in ignores_to_delete {
2606 snapshot.ignores_by_parent_abs_path.remove(&parent_abs_path);
2607 self.snapshot
2608 .lock()
2609 .ignores_by_parent_abs_path
2610 .remove(&parent_abs_path);
2611 }
2612
2613 let (ignore_queue_tx, ignore_queue_rx) = channel::unbounded();
2614 ignores_to_update.sort_unstable();
2615 let mut ignores_to_update = ignores_to_update.into_iter().peekable();
2616 while let Some(parent_abs_path) = ignores_to_update.next() {
2617 while ignores_to_update
2618 .peek()
2619 .map_or(false, |p| p.starts_with(&parent_abs_path))
2620 {
2621 ignores_to_update.next().unwrap();
2622 }
2623
2624 let ignore_stack = snapshot.ignore_stack_for_abs_path(&parent_abs_path, true);
2625 ignore_queue_tx
2626 .send(UpdateIgnoreStatusJob {
2627 abs_path: parent_abs_path,
2628 ignore_stack,
2629 ignore_queue: ignore_queue_tx.clone(),
2630 })
2631 .await
2632 .unwrap();
2633 }
2634 drop(ignore_queue_tx);
2635
2636 self.executor
2637 .scoped(|scope| {
2638 for _ in 0..self.executor.num_cpus() {
2639 scope.spawn(async {
2640 while let Ok(job) = ignore_queue_rx.recv().await {
2641 self.update_ignore_status(job, &snapshot).await;
2642 }
2643 });
2644 }
2645 })
2646 .await;
2647 }
2648
2649 fn update_git_repositories(&self) {
2650 let mut snapshot = self.snapshot.lock();
2651 let mut git_repositories = mem::take(&mut snapshot.git_repositories);
2652 git_repositories.retain(|repo| snapshot.entry_for_path(&repo.git_dir_path).is_some());
2653 snapshot.git_repositories = git_repositories;
2654 }
2655
2656 async fn update_ignore_status(&self, job: UpdateIgnoreStatusJob, snapshot: &LocalSnapshot) {
2657 let mut ignore_stack = job.ignore_stack;
2658 if let Some((ignore, _)) = snapshot.ignores_by_parent_abs_path.get(&job.abs_path) {
2659 ignore_stack = ignore_stack.append(job.abs_path.clone(), ignore.clone());
2660 }
2661
2662 let mut entries_by_id_edits = Vec::new();
2663 let mut entries_by_path_edits = Vec::new();
2664 let path = job.abs_path.strip_prefix(&snapshot.abs_path).unwrap();
2665 for mut entry in snapshot.child_entries(path).cloned() {
2666 let was_ignored = entry.is_ignored;
2667 let abs_path = self.abs_path().join(&entry.path);
2668 entry.is_ignored = ignore_stack.is_abs_path_ignored(&abs_path, entry.is_dir());
2669 if entry.is_dir() {
2670 let child_ignore_stack = if entry.is_ignored {
2671 IgnoreStack::all()
2672 } else {
2673 ignore_stack.clone()
2674 };
2675 job.ignore_queue
2676 .send(UpdateIgnoreStatusJob {
2677 abs_path: abs_path.into(),
2678 ignore_stack: child_ignore_stack,
2679 ignore_queue: job.ignore_queue.clone(),
2680 })
2681 .await
2682 .unwrap();
2683 }
2684
2685 if entry.is_ignored != was_ignored {
2686 let mut path_entry = snapshot.entries_by_id.get(&entry.id, &()).unwrap().clone();
2687 path_entry.scan_id = snapshot.scan_id;
2688 path_entry.is_ignored = entry.is_ignored;
2689 entries_by_id_edits.push(Edit::Insert(path_entry));
2690 entries_by_path_edits.push(Edit::Insert(entry));
2691 }
2692 }
2693
2694 let mut snapshot = self.snapshot.lock();
2695 snapshot.entries_by_path.edit(entries_by_path_edits, &());
2696 snapshot.entries_by_id.edit(entries_by_id_edits, &());
2697 }
2698}
2699
2700fn char_bag_for_path(root_char_bag: CharBag, path: &Path) -> CharBag {
2701 let mut result = root_char_bag;
2702 result.extend(
2703 path.to_string_lossy()
2704 .chars()
2705 .map(|c| c.to_ascii_lowercase()),
2706 );
2707 result
2708}
2709
2710struct ScanJob {
2711 abs_path: PathBuf,
2712 path: Arc<Path>,
2713 ignore_stack: Arc<IgnoreStack>,
2714 scan_queue: Sender<ScanJob>,
2715 ancestor_inodes: TreeSet<u64>,
2716}
2717
2718struct UpdateIgnoreStatusJob {
2719 abs_path: Arc<Path>,
2720 ignore_stack: Arc<IgnoreStack>,
2721 ignore_queue: Sender<UpdateIgnoreStatusJob>,
2722}
2723
2724pub trait WorktreeHandle {
2725 #[cfg(any(test, feature = "test-support"))]
2726 fn flush_fs_events<'a>(
2727 &self,
2728 cx: &'a gpui::TestAppContext,
2729 ) -> futures::future::LocalBoxFuture<'a, ()>;
2730}
2731
2732impl WorktreeHandle for ModelHandle<Worktree> {
2733 // When the worktree's FS event stream sometimes delivers "redundant" events for FS changes that
2734 // occurred before the worktree was constructed. These events can cause the worktree to perfrom
2735 // extra directory scans, and emit extra scan-state notifications.
2736 //
2737 // This function mutates the worktree's directory and waits for those mutations to be picked up,
2738 // to ensure that all redundant FS events have already been processed.
2739 #[cfg(any(test, feature = "test-support"))]
2740 fn flush_fs_events<'a>(
2741 &self,
2742 cx: &'a gpui::TestAppContext,
2743 ) -> futures::future::LocalBoxFuture<'a, ()> {
2744 use smol::future::FutureExt;
2745
2746 let filename = "fs-event-sentinel";
2747 let tree = self.clone();
2748 let (fs, root_path) = self.read_with(cx, |tree, _| {
2749 let tree = tree.as_local().unwrap();
2750 (tree.fs.clone(), tree.abs_path().clone())
2751 });
2752
2753 async move {
2754 fs.create_file(&root_path.join(filename), Default::default())
2755 .await
2756 .unwrap();
2757 tree.condition(cx, |tree, _| tree.entry_for_path(filename).is_some())
2758 .await;
2759
2760 fs.remove_file(&root_path.join(filename), Default::default())
2761 .await
2762 .unwrap();
2763 tree.condition(cx, |tree, _| tree.entry_for_path(filename).is_none())
2764 .await;
2765
2766 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2767 .await;
2768 }
2769 .boxed_local()
2770 }
2771}
2772
2773#[derive(Clone, Debug)]
2774struct TraversalProgress<'a> {
2775 max_path: &'a Path,
2776 count: usize,
2777 visible_count: usize,
2778 file_count: usize,
2779 visible_file_count: usize,
2780}
2781
2782impl<'a> TraversalProgress<'a> {
2783 fn count(&self, include_dirs: bool, include_ignored: bool) -> usize {
2784 match (include_ignored, include_dirs) {
2785 (true, true) => self.count,
2786 (true, false) => self.file_count,
2787 (false, true) => self.visible_count,
2788 (false, false) => self.visible_file_count,
2789 }
2790 }
2791}
2792
2793impl<'a> sum_tree::Dimension<'a, EntrySummary> for TraversalProgress<'a> {
2794 fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
2795 self.max_path = summary.max_path.as_ref();
2796 self.count += summary.count;
2797 self.visible_count += summary.visible_count;
2798 self.file_count += summary.file_count;
2799 self.visible_file_count += summary.visible_file_count;
2800 }
2801}
2802
2803impl<'a> Default for TraversalProgress<'a> {
2804 fn default() -> Self {
2805 Self {
2806 max_path: Path::new(""),
2807 count: 0,
2808 visible_count: 0,
2809 file_count: 0,
2810 visible_file_count: 0,
2811 }
2812 }
2813}
2814
2815pub struct Traversal<'a> {
2816 cursor: sum_tree::Cursor<'a, Entry, TraversalProgress<'a>>,
2817 include_ignored: bool,
2818 include_dirs: bool,
2819}
2820
2821impl<'a> Traversal<'a> {
2822 pub fn advance(&mut self) -> bool {
2823 self.advance_to_offset(self.offset() + 1)
2824 }
2825
2826 pub fn advance_to_offset(&mut self, offset: usize) -> bool {
2827 self.cursor.seek_forward(
2828 &TraversalTarget::Count {
2829 count: offset,
2830 include_dirs: self.include_dirs,
2831 include_ignored: self.include_ignored,
2832 },
2833 Bias::Right,
2834 &(),
2835 )
2836 }
2837
2838 pub fn advance_to_sibling(&mut self) -> bool {
2839 while let Some(entry) = self.cursor.item() {
2840 self.cursor.seek_forward(
2841 &TraversalTarget::PathSuccessor(&entry.path),
2842 Bias::Left,
2843 &(),
2844 );
2845 if let Some(entry) = self.cursor.item() {
2846 if (self.include_dirs || !entry.is_dir())
2847 && (self.include_ignored || !entry.is_ignored)
2848 {
2849 return true;
2850 }
2851 }
2852 }
2853 false
2854 }
2855
2856 pub fn entry(&self) -> Option<&'a Entry> {
2857 self.cursor.item()
2858 }
2859
2860 pub fn offset(&self) -> usize {
2861 self.cursor
2862 .start()
2863 .count(self.include_dirs, self.include_ignored)
2864 }
2865}
2866
2867impl<'a> Iterator for Traversal<'a> {
2868 type Item = &'a Entry;
2869
2870 fn next(&mut self) -> Option<Self::Item> {
2871 if let Some(item) = self.entry() {
2872 self.advance();
2873 Some(item)
2874 } else {
2875 None
2876 }
2877 }
2878}
2879
2880#[derive(Debug)]
2881enum TraversalTarget<'a> {
2882 Path(&'a Path),
2883 PathSuccessor(&'a Path),
2884 Count {
2885 count: usize,
2886 include_ignored: bool,
2887 include_dirs: bool,
2888 },
2889}
2890
2891impl<'a, 'b> SeekTarget<'a, EntrySummary, TraversalProgress<'a>> for TraversalTarget<'b> {
2892 fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: &()) -> Ordering {
2893 match self {
2894 TraversalTarget::Path(path) => path.cmp(&cursor_location.max_path),
2895 TraversalTarget::PathSuccessor(path) => {
2896 if !cursor_location.max_path.starts_with(path) {
2897 Ordering::Equal
2898 } else {
2899 Ordering::Greater
2900 }
2901 }
2902 TraversalTarget::Count {
2903 count,
2904 include_dirs,
2905 include_ignored,
2906 } => Ord::cmp(
2907 count,
2908 &cursor_location.count(*include_dirs, *include_ignored),
2909 ),
2910 }
2911 }
2912}
2913
2914struct ChildEntriesIter<'a> {
2915 parent_path: &'a Path,
2916 traversal: Traversal<'a>,
2917}
2918
2919impl<'a> Iterator for ChildEntriesIter<'a> {
2920 type Item = &'a Entry;
2921
2922 fn next(&mut self) -> Option<Self::Item> {
2923 if let Some(item) = self.traversal.entry() {
2924 if item.path.starts_with(&self.parent_path) {
2925 self.traversal.advance_to_sibling();
2926 return Some(item);
2927 }
2928 }
2929 None
2930 }
2931}
2932
2933impl<'a> From<&'a Entry> for proto::Entry {
2934 fn from(entry: &'a Entry) -> Self {
2935 Self {
2936 id: entry.id.to_proto(),
2937 is_dir: entry.is_dir(),
2938 path: entry.path.as_os_str().as_bytes().to_vec(),
2939 inode: entry.inode,
2940 mtime: Some(entry.mtime.into()),
2941 is_symlink: entry.is_symlink,
2942 is_ignored: entry.is_ignored,
2943 }
2944 }
2945}
2946
2947impl<'a> TryFrom<(&'a CharBag, proto::Entry)> for Entry {
2948 type Error = anyhow::Error;
2949
2950 fn try_from((root_char_bag, entry): (&'a CharBag, proto::Entry)) -> Result<Self> {
2951 if let Some(mtime) = entry.mtime {
2952 let kind = if entry.is_dir {
2953 EntryKind::Dir
2954 } else {
2955 let mut char_bag = *root_char_bag;
2956 char_bag.extend(
2957 String::from_utf8_lossy(&entry.path)
2958 .chars()
2959 .map(|c| c.to_ascii_lowercase()),
2960 );
2961 EntryKind::File(char_bag)
2962 };
2963 let path: Arc<Path> = PathBuf::from(OsString::from_vec(entry.path)).into();
2964 Ok(Entry {
2965 id: ProjectEntryId::from_proto(entry.id),
2966 kind,
2967 path,
2968 inode: entry.inode,
2969 mtime: mtime.into(),
2970 is_symlink: entry.is_symlink,
2971 is_ignored: entry.is_ignored,
2972 })
2973 } else {
2974 Err(anyhow!(
2975 "missing mtime in remote worktree entry {:?}",
2976 entry.path
2977 ))
2978 }
2979 }
2980}
2981
2982async fn send_worktree_update(client: &Arc<Client>, update: proto::UpdateWorktree) -> Result<()> {
2983 #[cfg(any(test, feature = "test-support"))]
2984 const MAX_CHUNK_SIZE: usize = 2;
2985 #[cfg(not(any(test, feature = "test-support")))]
2986 const MAX_CHUNK_SIZE: usize = 256;
2987
2988 for update in proto::split_worktree_update(update, MAX_CHUNK_SIZE) {
2989 client.request(update).await?;
2990 }
2991
2992 Ok(())
2993}
2994
2995#[cfg(test)]
2996mod tests {
2997 use super::*;
2998 use anyhow::Result;
2999 use client::test::FakeHttpClient;
3000 use fs::repository::FakeGitRepository;
3001 use fs::{FakeFs, RealFs};
3002 use gpui::{executor::Deterministic, TestAppContext};
3003 use rand::prelude::*;
3004 use serde_json::json;
3005 use std::{
3006 env,
3007 fmt::Write,
3008 time::{SystemTime, UNIX_EPOCH},
3009 };
3010
3011 use util::test::temp_tree;
3012
3013 #[gpui::test]
3014 async fn test_traversal(cx: &mut TestAppContext) {
3015 let fs = FakeFs::new(cx.background());
3016 fs.insert_tree(
3017 "/root",
3018 json!({
3019 ".gitignore": "a/b\n",
3020 "a": {
3021 "b": "",
3022 "c": "",
3023 }
3024 }),
3025 )
3026 .await;
3027
3028 let http_client = FakeHttpClient::with_404_response();
3029 let client = cx.read(|cx| Client::new(http_client, cx));
3030
3031 let tree = Worktree::local(
3032 client,
3033 Arc::from(Path::new("/root")),
3034 true,
3035 fs,
3036 Default::default(),
3037 &mut cx.to_async(),
3038 )
3039 .await
3040 .unwrap();
3041 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3042 .await;
3043
3044 tree.read_with(cx, |tree, _| {
3045 assert_eq!(
3046 tree.entries(false)
3047 .map(|entry| entry.path.as_ref())
3048 .collect::<Vec<_>>(),
3049 vec![
3050 Path::new(""),
3051 Path::new(".gitignore"),
3052 Path::new("a"),
3053 Path::new("a/c"),
3054 ]
3055 );
3056 assert_eq!(
3057 tree.entries(true)
3058 .map(|entry| entry.path.as_ref())
3059 .collect::<Vec<_>>(),
3060 vec![
3061 Path::new(""),
3062 Path::new(".gitignore"),
3063 Path::new("a"),
3064 Path::new("a/b"),
3065 Path::new("a/c"),
3066 ]
3067 );
3068 })
3069 }
3070
3071 #[gpui::test(iterations = 10)]
3072 async fn test_circular_symlinks(executor: Arc<Deterministic>, cx: &mut TestAppContext) {
3073 let fs = FakeFs::new(cx.background());
3074 fs.insert_tree(
3075 "/root",
3076 json!({
3077 "lib": {
3078 "a": {
3079 "a.txt": ""
3080 },
3081 "b": {
3082 "b.txt": ""
3083 }
3084 }
3085 }),
3086 )
3087 .await;
3088 fs.insert_symlink("/root/lib/a/lib", "..".into()).await;
3089 fs.insert_symlink("/root/lib/b/lib", "..".into()).await;
3090
3091 let client = cx.read(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
3092 let tree = Worktree::local(
3093 client,
3094 Arc::from(Path::new("/root")),
3095 true,
3096 fs.clone(),
3097 Default::default(),
3098 &mut cx.to_async(),
3099 )
3100 .await
3101 .unwrap();
3102
3103 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3104 .await;
3105
3106 tree.read_with(cx, |tree, _| {
3107 assert_eq!(
3108 tree.entries(false)
3109 .map(|entry| entry.path.as_ref())
3110 .collect::<Vec<_>>(),
3111 vec![
3112 Path::new(""),
3113 Path::new("lib"),
3114 Path::new("lib/a"),
3115 Path::new("lib/a/a.txt"),
3116 Path::new("lib/a/lib"),
3117 Path::new("lib/b"),
3118 Path::new("lib/b/b.txt"),
3119 Path::new("lib/b/lib"),
3120 ]
3121 );
3122 });
3123
3124 fs.rename(
3125 Path::new("/root/lib/a/lib"),
3126 Path::new("/root/lib/a/lib-2"),
3127 Default::default(),
3128 )
3129 .await
3130 .unwrap();
3131 executor.run_until_parked();
3132 tree.read_with(cx, |tree, _| {
3133 assert_eq!(
3134 tree.entries(false)
3135 .map(|entry| entry.path.as_ref())
3136 .collect::<Vec<_>>(),
3137 vec![
3138 Path::new(""),
3139 Path::new("lib"),
3140 Path::new("lib/a"),
3141 Path::new("lib/a/a.txt"),
3142 Path::new("lib/a/lib-2"),
3143 Path::new("lib/b"),
3144 Path::new("lib/b/b.txt"),
3145 Path::new("lib/b/lib"),
3146 ]
3147 );
3148 });
3149 }
3150
3151 #[gpui::test]
3152 async fn test_rescan_with_gitignore(cx: &mut TestAppContext) {
3153 let parent_dir = temp_tree(json!({
3154 ".gitignore": "ancestor-ignored-file1\nancestor-ignored-file2\n",
3155 "tree": {
3156 ".git": {},
3157 ".gitignore": "ignored-dir\n",
3158 "tracked-dir": {
3159 "tracked-file1": "",
3160 "ancestor-ignored-file1": "",
3161 },
3162 "ignored-dir": {
3163 "ignored-file1": ""
3164 }
3165 }
3166 }));
3167 let dir = parent_dir.path().join("tree");
3168
3169 let client = cx.read(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
3170
3171 let tree = Worktree::local(
3172 client,
3173 dir.as_path(),
3174 true,
3175 Arc::new(RealFs),
3176 Default::default(),
3177 &mut cx.to_async(),
3178 )
3179 .await
3180 .unwrap();
3181 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3182 .await;
3183 tree.flush_fs_events(cx).await;
3184 cx.read(|cx| {
3185 let tree = tree.read(cx);
3186 assert!(
3187 !tree
3188 .entry_for_path("tracked-dir/tracked-file1")
3189 .unwrap()
3190 .is_ignored
3191 );
3192 assert!(
3193 tree.entry_for_path("tracked-dir/ancestor-ignored-file1")
3194 .unwrap()
3195 .is_ignored
3196 );
3197 assert!(
3198 tree.entry_for_path("ignored-dir/ignored-file1")
3199 .unwrap()
3200 .is_ignored
3201 );
3202 });
3203
3204 std::fs::write(dir.join("tracked-dir/tracked-file2"), "").unwrap();
3205 std::fs::write(dir.join("tracked-dir/ancestor-ignored-file2"), "").unwrap();
3206 std::fs::write(dir.join("ignored-dir/ignored-file2"), "").unwrap();
3207 tree.flush_fs_events(cx).await;
3208 cx.read(|cx| {
3209 let tree = tree.read(cx);
3210 assert!(
3211 !tree
3212 .entry_for_path("tracked-dir/tracked-file2")
3213 .unwrap()
3214 .is_ignored
3215 );
3216 assert!(
3217 tree.entry_for_path("tracked-dir/ancestor-ignored-file2")
3218 .unwrap()
3219 .is_ignored
3220 );
3221 assert!(
3222 tree.entry_for_path("ignored-dir/ignored-file2")
3223 .unwrap()
3224 .is_ignored
3225 );
3226 assert!(tree.entry_for_path(".git").unwrap().is_ignored);
3227 });
3228 }
3229
3230 #[gpui::test]
3231 async fn test_git_repository_for_path(cx: &mut TestAppContext) {
3232 let root = temp_tree(json!({
3233 "dir1": {
3234 ".git": {},
3235 "deps": {
3236 "dep1": {
3237 ".git": {},
3238 "src": {
3239 "a.txt": ""
3240 }
3241 }
3242 },
3243 "src": {
3244 "b.txt": ""
3245 }
3246 },
3247 "c.txt": "",
3248
3249 }));
3250
3251 let http_client = FakeHttpClient::with_404_response();
3252 let client = cx.read(|cx| Client::new(http_client, cx));
3253 let tree = Worktree::local(
3254 client,
3255 root.path(),
3256 true,
3257 Arc::new(RealFs),
3258 Default::default(),
3259 &mut cx.to_async(),
3260 )
3261 .await
3262 .unwrap();
3263
3264 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3265 .await;
3266 tree.flush_fs_events(cx).await;
3267
3268 tree.read_with(cx, |tree, _cx| {
3269 let tree = tree.as_local().unwrap();
3270
3271 assert!(tree.repo_for("c.txt".as_ref()).is_none());
3272
3273 let repo = tree.repo_for("dir1/src/b.txt".as_ref()).unwrap();
3274 assert_eq!(repo.content_path.as_ref(), Path::new("dir1"));
3275 assert_eq!(repo.git_dir_path.as_ref(), Path::new("dir1/.git"));
3276
3277 let repo = tree.repo_for("dir1/deps/dep1/src/a.txt".as_ref()).unwrap();
3278 assert_eq!(repo.content_path.as_ref(), Path::new("dir1/deps/dep1"));
3279 assert_eq!(repo.git_dir_path.as_ref(), Path::new("dir1/deps/dep1/.git"),);
3280 });
3281
3282 let original_scan_id = tree.read_with(cx, |tree, _cx| {
3283 let tree = tree.as_local().unwrap();
3284 tree.repo_for("dir1/src/b.txt".as_ref()).unwrap().scan_id
3285 });
3286
3287 std::fs::write(root.path().join("dir1/.git/random_new_file"), "hello").unwrap();
3288 tree.flush_fs_events(cx).await;
3289
3290 tree.read_with(cx, |tree, _cx| {
3291 let tree = tree.as_local().unwrap();
3292 let new_scan_id = tree.repo_for("dir1/src/b.txt".as_ref()).unwrap().scan_id;
3293 assert_ne!(
3294 original_scan_id, new_scan_id,
3295 "original {original_scan_id}, new {new_scan_id}"
3296 );
3297 });
3298
3299 std::fs::remove_dir_all(root.path().join("dir1/.git")).unwrap();
3300 tree.flush_fs_events(cx).await;
3301
3302 tree.read_with(cx, |tree, _cx| {
3303 let tree = tree.as_local().unwrap();
3304
3305 assert!(tree.repo_for("dir1/src/b.txt".as_ref()).is_none());
3306 });
3307 }
3308
3309 #[test]
3310 fn test_changed_repos() {
3311 fn fake_entry(git_dir_path: impl AsRef<Path>, scan_id: usize) -> GitRepositoryEntry {
3312 GitRepositoryEntry {
3313 repo: Arc::new(Mutex::new(FakeGitRepository::default())),
3314 scan_id,
3315 content_path: git_dir_path.as_ref().parent().unwrap().into(),
3316 git_dir_path: git_dir_path.as_ref().into(),
3317 }
3318 }
3319
3320 let prev_repos: Vec<GitRepositoryEntry> = vec![
3321 fake_entry("/.git", 0),
3322 fake_entry("/a/.git", 0),
3323 fake_entry("/a/b/.git", 0),
3324 ];
3325
3326 let new_repos: Vec<GitRepositoryEntry> = vec![
3327 fake_entry("/a/.git", 1),
3328 fake_entry("/a/b/.git", 0),
3329 fake_entry("/a/c/.git", 0),
3330 ];
3331
3332 let res = LocalWorktree::changed_repos(&prev_repos, &new_repos);
3333
3334 // Deletion retained
3335 assert!(res
3336 .iter()
3337 .find(|repo| repo.git_dir_path.as_ref() == Path::new("/.git") && repo.scan_id == 0)
3338 .is_some());
3339
3340 // Update retained
3341 assert!(res
3342 .iter()
3343 .find(|repo| repo.git_dir_path.as_ref() == Path::new("/a/.git") && repo.scan_id == 1)
3344 .is_some());
3345
3346 // Addition retained
3347 assert!(res
3348 .iter()
3349 .find(|repo| repo.git_dir_path.as_ref() == Path::new("/a/c/.git") && repo.scan_id == 0)
3350 .is_some());
3351
3352 // Nochange, not retained
3353 assert!(res
3354 .iter()
3355 .find(|repo| repo.git_dir_path.as_ref() == Path::new("/a/b/.git") && repo.scan_id == 0)
3356 .is_none());
3357 }
3358
3359 #[gpui::test]
3360 async fn test_write_file(cx: &mut TestAppContext) {
3361 let dir = temp_tree(json!({
3362 ".git": {},
3363 ".gitignore": "ignored-dir\n",
3364 "tracked-dir": {},
3365 "ignored-dir": {}
3366 }));
3367
3368 let client = cx.read(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
3369
3370 let tree = Worktree::local(
3371 client,
3372 dir.path(),
3373 true,
3374 Arc::new(RealFs),
3375 Default::default(),
3376 &mut cx.to_async(),
3377 )
3378 .await
3379 .unwrap();
3380 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3381 .await;
3382 tree.flush_fs_events(cx).await;
3383
3384 tree.update(cx, |tree, cx| {
3385 tree.as_local().unwrap().write_file(
3386 Path::new("tracked-dir/file.txt"),
3387 "hello".into(),
3388 Default::default(),
3389 cx,
3390 )
3391 })
3392 .await
3393 .unwrap();
3394 tree.update(cx, |tree, cx| {
3395 tree.as_local().unwrap().write_file(
3396 Path::new("ignored-dir/file.txt"),
3397 "world".into(),
3398 Default::default(),
3399 cx,
3400 )
3401 })
3402 .await
3403 .unwrap();
3404
3405 tree.read_with(cx, |tree, _| {
3406 let tracked = tree.entry_for_path("tracked-dir/file.txt").unwrap();
3407 let ignored = tree.entry_for_path("ignored-dir/file.txt").unwrap();
3408 assert!(!tracked.is_ignored);
3409 assert!(ignored.is_ignored);
3410 });
3411 }
3412
3413 #[gpui::test(iterations = 30)]
3414 async fn test_create_directory(cx: &mut TestAppContext) {
3415 let client = cx.read(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
3416
3417 let fs = FakeFs::new(cx.background());
3418 fs.insert_tree(
3419 "/a",
3420 json!({
3421 "b": {},
3422 "c": {},
3423 "d": {},
3424 }),
3425 )
3426 .await;
3427
3428 let tree = Worktree::local(
3429 client,
3430 "/a".as_ref(),
3431 true,
3432 fs,
3433 Default::default(),
3434 &mut cx.to_async(),
3435 )
3436 .await
3437 .unwrap();
3438
3439 let entry = tree
3440 .update(cx, |tree, cx| {
3441 tree.as_local_mut()
3442 .unwrap()
3443 .create_entry("a/e".as_ref(), true, cx)
3444 })
3445 .await
3446 .unwrap();
3447 assert!(entry.is_dir());
3448
3449 cx.foreground().run_until_parked();
3450 tree.read_with(cx, |tree, _| {
3451 assert_eq!(tree.entry_for_path("a/e").unwrap().kind, EntryKind::Dir);
3452 });
3453 }
3454
3455 #[gpui::test(iterations = 100)]
3456 fn test_random(mut rng: StdRng) {
3457 let operations = env::var("OPERATIONS")
3458 .map(|o| o.parse().unwrap())
3459 .unwrap_or(40);
3460 let initial_entries = env::var("INITIAL_ENTRIES")
3461 .map(|o| o.parse().unwrap())
3462 .unwrap_or(20);
3463
3464 let root_dir = tempdir::TempDir::new("worktree-test").unwrap();
3465 for _ in 0..initial_entries {
3466 randomly_mutate_tree(root_dir.path(), 1.0, &mut rng).unwrap();
3467 }
3468 log::info!("Generated initial tree");
3469
3470 let (notify_tx, _notify_rx) = mpsc::unbounded();
3471 let fs = Arc::new(RealFs);
3472 let next_entry_id = Arc::new(AtomicUsize::new(0));
3473 let mut initial_snapshot = LocalSnapshot {
3474 abs_path: root_dir.path().into(),
3475 removed_entry_ids: Default::default(),
3476 ignores_by_parent_abs_path: Default::default(),
3477 git_repositories: Default::default(),
3478 next_entry_id: next_entry_id.clone(),
3479 snapshot: Snapshot {
3480 id: WorktreeId::from_usize(0),
3481 entries_by_path: Default::default(),
3482 entries_by_id: Default::default(),
3483 root_name: Default::default(),
3484 root_char_bag: Default::default(),
3485 scan_id: 0,
3486 is_complete: true,
3487 },
3488 extension_counts: Default::default(),
3489 };
3490 initial_snapshot.insert_entry(
3491 Entry::new(
3492 Path::new("").into(),
3493 &smol::block_on(fs.metadata(root_dir.path()))
3494 .unwrap()
3495 .unwrap(),
3496 &next_entry_id,
3497 Default::default(),
3498 ),
3499 fs.as_ref(),
3500 );
3501 let mut scanner = BackgroundScanner::new(
3502 Arc::new(Mutex::new(initial_snapshot.clone())),
3503 notify_tx,
3504 fs.clone(),
3505 Arc::new(gpui::executor::Background::new()),
3506 );
3507 smol::block_on(scanner.scan_dirs()).unwrap();
3508 scanner.snapshot().check_invariants();
3509
3510 let mut events = Vec::new();
3511 let mut snapshots = Vec::new();
3512 let mut mutations_len = operations;
3513 while mutations_len > 1 {
3514 if !events.is_empty() && rng.gen_bool(0.4) {
3515 let len = rng.gen_range(0..=events.len());
3516 let to_deliver = events.drain(0..len).collect::<Vec<_>>();
3517 log::info!("Delivering events: {:#?}", to_deliver);
3518 smol::block_on(scanner.process_events(to_deliver));
3519 scanner.snapshot().check_invariants();
3520 } else {
3521 events.extend(randomly_mutate_tree(root_dir.path(), 0.6, &mut rng).unwrap());
3522 mutations_len -= 1;
3523 }
3524
3525 if rng.gen_bool(0.2) {
3526 snapshots.push(scanner.snapshot());
3527 }
3528 }
3529 log::info!("Quiescing: {:#?}", events);
3530 smol::block_on(scanner.process_events(events));
3531 scanner.snapshot().check_invariants();
3532
3533 let (notify_tx, _notify_rx) = mpsc::unbounded();
3534 let mut new_scanner = BackgroundScanner::new(
3535 Arc::new(Mutex::new(initial_snapshot)),
3536 notify_tx,
3537 scanner.fs.clone(),
3538 scanner.executor.clone(),
3539 );
3540 smol::block_on(new_scanner.scan_dirs()).unwrap();
3541 assert_eq!(
3542 scanner.snapshot().to_vec(true),
3543 new_scanner.snapshot().to_vec(true)
3544 );
3545
3546 for mut prev_snapshot in snapshots {
3547 let include_ignored = rng.gen::<bool>();
3548 if !include_ignored {
3549 let mut entries_by_path_edits = Vec::new();
3550 let mut entries_by_id_edits = Vec::new();
3551 for entry in prev_snapshot
3552 .entries_by_id
3553 .cursor::<()>()
3554 .filter(|e| e.is_ignored)
3555 {
3556 entries_by_path_edits.push(Edit::Remove(PathKey(entry.path.clone())));
3557 entries_by_id_edits.push(Edit::Remove(entry.id));
3558 }
3559
3560 prev_snapshot
3561 .entries_by_path
3562 .edit(entries_by_path_edits, &());
3563 prev_snapshot.entries_by_id.edit(entries_by_id_edits, &());
3564 }
3565
3566 let update = scanner
3567 .snapshot()
3568 .build_update(&prev_snapshot, 0, 0, include_ignored);
3569 prev_snapshot.apply_remote_update(update).unwrap();
3570 assert_eq!(
3571 prev_snapshot.to_vec(true),
3572 scanner.snapshot().to_vec(include_ignored)
3573 );
3574 }
3575 }
3576
3577 fn randomly_mutate_tree(
3578 root_path: &Path,
3579 insertion_probability: f64,
3580 rng: &mut impl Rng,
3581 ) -> Result<Vec<fsevent::Event>> {
3582 let root_path = root_path.canonicalize().unwrap();
3583 let (dirs, files) = read_dir_recursive(root_path.clone());
3584
3585 let mut events = Vec::new();
3586 let mut record_event = |path: PathBuf| {
3587 events.push(fsevent::Event {
3588 event_id: SystemTime::now()
3589 .duration_since(UNIX_EPOCH)
3590 .unwrap()
3591 .as_secs(),
3592 flags: fsevent::StreamFlags::empty(),
3593 path,
3594 });
3595 };
3596
3597 if (files.is_empty() && dirs.len() == 1) || rng.gen_bool(insertion_probability) {
3598 let path = dirs.choose(rng).unwrap();
3599 let new_path = path.join(gen_name(rng));
3600
3601 if rng.gen() {
3602 log::info!("Creating dir {:?}", new_path.strip_prefix(root_path)?);
3603 std::fs::create_dir(&new_path)?;
3604 } else {
3605 log::info!("Creating file {:?}", new_path.strip_prefix(root_path)?);
3606 std::fs::write(&new_path, "")?;
3607 }
3608 record_event(new_path);
3609 } else if rng.gen_bool(0.05) {
3610 let ignore_dir_path = dirs.choose(rng).unwrap();
3611 let ignore_path = ignore_dir_path.join(&*GITIGNORE);
3612
3613 let (subdirs, subfiles) = read_dir_recursive(ignore_dir_path.clone());
3614 let files_to_ignore = {
3615 let len = rng.gen_range(0..=subfiles.len());
3616 subfiles.choose_multiple(rng, len)
3617 };
3618 let dirs_to_ignore = {
3619 let len = rng.gen_range(0..subdirs.len());
3620 subdirs.choose_multiple(rng, len)
3621 };
3622
3623 let mut ignore_contents = String::new();
3624 for path_to_ignore in files_to_ignore.chain(dirs_to_ignore) {
3625 writeln!(
3626 ignore_contents,
3627 "{}",
3628 path_to_ignore
3629 .strip_prefix(&ignore_dir_path)?
3630 .to_str()
3631 .unwrap()
3632 )
3633 .unwrap();
3634 }
3635 log::info!(
3636 "Creating {:?} with contents:\n{}",
3637 ignore_path.strip_prefix(&root_path)?,
3638 ignore_contents
3639 );
3640 std::fs::write(&ignore_path, ignore_contents).unwrap();
3641 record_event(ignore_path);
3642 } else {
3643 let old_path = {
3644 let file_path = files.choose(rng);
3645 let dir_path = dirs[1..].choose(rng);
3646 file_path.into_iter().chain(dir_path).choose(rng).unwrap()
3647 };
3648
3649 let is_rename = rng.gen();
3650 if is_rename {
3651 let new_path_parent = dirs
3652 .iter()
3653 .filter(|d| !d.starts_with(old_path))
3654 .choose(rng)
3655 .unwrap();
3656
3657 let overwrite_existing_dir =
3658 !old_path.starts_with(&new_path_parent) && rng.gen_bool(0.3);
3659 let new_path = if overwrite_existing_dir {
3660 std::fs::remove_dir_all(&new_path_parent).ok();
3661 new_path_parent.to_path_buf()
3662 } else {
3663 new_path_parent.join(gen_name(rng))
3664 };
3665
3666 log::info!(
3667 "Renaming {:?} to {}{:?}",
3668 old_path.strip_prefix(&root_path)?,
3669 if overwrite_existing_dir {
3670 "overwrite "
3671 } else {
3672 ""
3673 },
3674 new_path.strip_prefix(&root_path)?
3675 );
3676 std::fs::rename(&old_path, &new_path)?;
3677 record_event(old_path.clone());
3678 record_event(new_path);
3679 } else if old_path.is_dir() {
3680 let (dirs, files) = read_dir_recursive(old_path.clone());
3681
3682 log::info!("Deleting dir {:?}", old_path.strip_prefix(&root_path)?);
3683 std::fs::remove_dir_all(&old_path).unwrap();
3684 for file in files {
3685 record_event(file);
3686 }
3687 for dir in dirs {
3688 record_event(dir);
3689 }
3690 } else {
3691 log::info!("Deleting file {:?}", old_path.strip_prefix(&root_path)?);
3692 std::fs::remove_file(old_path).unwrap();
3693 record_event(old_path.clone());
3694 }
3695 }
3696
3697 Ok(events)
3698 }
3699
3700 fn read_dir_recursive(path: PathBuf) -> (Vec<PathBuf>, Vec<PathBuf>) {
3701 let child_entries = std::fs::read_dir(&path).unwrap();
3702 let mut dirs = vec![path];
3703 let mut files = Vec::new();
3704 for child_entry in child_entries {
3705 let child_path = child_entry.unwrap().path();
3706 if child_path.is_dir() {
3707 let (child_dirs, child_files) = read_dir_recursive(child_path);
3708 dirs.extend(child_dirs);
3709 files.extend(child_files);
3710 } else {
3711 files.push(child_path);
3712 }
3713 }
3714 (dirs, files)
3715 }
3716
3717 fn gen_name(rng: &mut impl Rng) -> String {
3718 (0..6)
3719 .map(|_| rng.sample(rand::distributions::Alphanumeric))
3720 .map(char::from)
3721 .collect()
3722 }
3723
3724 impl LocalSnapshot {
3725 fn check_invariants(&self) {
3726 let mut files = self.files(true, 0);
3727 let mut visible_files = self.files(false, 0);
3728 for entry in self.entries_by_path.cursor::<()>() {
3729 if entry.is_file() {
3730 assert_eq!(files.next().unwrap().inode, entry.inode);
3731 if !entry.is_ignored {
3732 assert_eq!(visible_files.next().unwrap().inode, entry.inode);
3733 }
3734 }
3735 }
3736 assert!(files.next().is_none());
3737 assert!(visible_files.next().is_none());
3738
3739 let mut bfs_paths = Vec::new();
3740 let mut stack = vec![Path::new("")];
3741 while let Some(path) = stack.pop() {
3742 bfs_paths.push(path);
3743 let ix = stack.len();
3744 for child_entry in self.child_entries(path) {
3745 stack.insert(ix, &child_entry.path);
3746 }
3747 }
3748
3749 let dfs_paths_via_iter = self
3750 .entries_by_path
3751 .cursor::<()>()
3752 .map(|e| e.path.as_ref())
3753 .collect::<Vec<_>>();
3754 assert_eq!(bfs_paths, dfs_paths_via_iter);
3755
3756 let dfs_paths_via_traversal = self
3757 .entries(true)
3758 .map(|e| e.path.as_ref())
3759 .collect::<Vec<_>>();
3760 assert_eq!(dfs_paths_via_traversal, dfs_paths_via_iter);
3761
3762 for ignore_parent_abs_path in self.ignores_by_parent_abs_path.keys() {
3763 let ignore_parent_path =
3764 ignore_parent_abs_path.strip_prefix(&self.abs_path).unwrap();
3765 assert!(self.entry_for_path(&ignore_parent_path).is_some());
3766 assert!(self
3767 .entry_for_path(ignore_parent_path.join(&*GITIGNORE))
3768 .is_some());
3769 }
3770
3771 // Ensure extension counts are correct.
3772 let mut expected_extension_counts = HashMap::default();
3773 for extension in self.entries(false).filter_map(|e| e.path.extension()) {
3774 *expected_extension_counts
3775 .entry(extension.into())
3776 .or_insert(0) += 1;
3777 }
3778 assert_eq!(self.extension_counts, expected_extension_counts);
3779 }
3780
3781 fn to_vec(&self, include_ignored: bool) -> Vec<(&Path, u64, bool)> {
3782 let mut paths = Vec::new();
3783 for entry in self.entries_by_path.cursor::<()>() {
3784 if include_ignored || !entry.is_ignored {
3785 paths.push((entry.path.as_ref(), entry.inode, entry.is_ignored));
3786 }
3787 }
3788 paths.sort_by(|a, b| a.0.cmp(b.0));
3789 paths
3790 }
3791 }
3792}