1mod ignore;
2mod worktree_settings;
3#[cfg(test)]
4mod worktree_tests;
5
6use ::ignore::gitignore::{Gitignore, GitignoreBuilder};
7use anyhow::{Context as _, Result, anyhow};
8use clock::ReplicaId;
9use collections::{HashMap, HashSet, VecDeque};
10use fs::{Fs, MTime, PathEvent, RemoveOptions, Watcher, copy_recursive};
11use futures::{
12 FutureExt as _, Stream, StreamExt,
13 channel::{
14 mpsc::{self, UnboundedSender},
15 oneshot,
16 },
17 select_biased,
18 task::Poll,
19};
20use fuzzy::CharBag;
21use git::{
22 COMMIT_MESSAGE, DOT_GIT, FSMONITOR_DAEMON, GITIGNORE, INDEX_LOCK, LFS_DIR,
23 repository::RepoPath, status::GitSummary,
24};
25use gpui::{
26 App, AppContext as _, AsyncApp, BackgroundExecutor, Context, Entity, EventEmitter, Task,
27};
28use ignore::IgnoreStack;
29use language::DiskState;
30
31use parking_lot::Mutex;
32use paths::local_settings_folder_relative_path;
33use postage::{
34 barrier,
35 prelude::{Sink as _, Stream as _},
36 watch,
37};
38use rpc::{
39 AnyProtoClient,
40 proto::{self, FromProto, ToProto, split_worktree_update},
41};
42pub use settings::WorktreeId;
43use settings::{Settings, SettingsLocation, SettingsStore};
44use smallvec::{SmallVec, smallvec};
45use smol::channel::{self, Sender};
46use std::{
47 any::Any,
48 borrow::Borrow as _,
49 cmp::Ordering,
50 collections::hash_map,
51 convert::TryFrom,
52 ffi::OsStr,
53 fmt,
54 future::Future,
55 mem::{self},
56 ops::{Deref, DerefMut},
57 path::{Component, Path, PathBuf},
58 pin::Pin,
59 sync::{
60 Arc,
61 atomic::{AtomicUsize, Ordering::SeqCst},
62 },
63 time::{Duration, Instant},
64};
65use sum_tree::{Bias, Edit, KeyedItem, SeekTarget, SumTree, Summary, TreeMap, TreeSet, Unit};
66use text::{LineEnding, Rope};
67use util::{
68 ResultExt,
69 paths::{PathMatcher, SanitizedPath, home_dir},
70};
71pub use worktree_settings::WorktreeSettings;
72
73pub const FS_WATCH_LATENCY: Duration = Duration::from_millis(100);
74
75/// A set of local or remote files that are being opened as part of a project.
76/// Responsible for tracking related FS (for local)/collab (for remote) events and corresponding updates.
77/// Stores git repositories data and the diagnostics for the file(s).
78///
79/// Has an absolute path, and may be set to be visible in Zed UI or not.
80/// May correspond to a directory or a single file.
81/// Possible examples:
82/// * a drag and dropped file — may be added as an invisible, "ephemeral" entry to the current worktree
83/// * a directory opened in Zed — may be added as a visible entry to the current worktree
84///
85/// Uses [`Entry`] to track the state of each file/directory, can look up absolute paths for entries.
86pub enum Worktree {
87 Local(LocalWorktree),
88 Remote(RemoteWorktree),
89}
90
91/// An entry, created in the worktree.
92#[derive(Debug)]
93pub enum CreatedEntry {
94 /// Got created and indexed by the worktree, receiving a corresponding entry.
95 Included(Entry),
96 /// Got created, but not indexed due to falling under exclusion filters.
97 Excluded { abs_path: PathBuf },
98}
99
100pub struct LoadedFile {
101 pub file: Arc<File>,
102 pub text: String,
103}
104
105pub struct LoadedBinaryFile {
106 pub file: Arc<File>,
107 pub content: Vec<u8>,
108}
109
110pub struct LocalWorktree {
111 snapshot: LocalSnapshot,
112 scan_requests_tx: channel::Sender<ScanRequest>,
113 path_prefixes_to_scan_tx: channel::Sender<PathPrefixScanRequest>,
114 is_scanning: (watch::Sender<bool>, watch::Receiver<bool>),
115 _background_scanner_tasks: Vec<Task<()>>,
116 update_observer: Option<UpdateObservationState>,
117 fs: Arc<dyn Fs>,
118 fs_case_sensitive: bool,
119 visible: bool,
120 next_entry_id: Arc<AtomicUsize>,
121 settings: WorktreeSettings,
122 share_private_files: bool,
123}
124
125pub struct PathPrefixScanRequest {
126 path: Arc<Path>,
127 done: SmallVec<[barrier::Sender; 1]>,
128}
129
130struct ScanRequest {
131 relative_paths: Vec<Arc<Path>>,
132 done: SmallVec<[barrier::Sender; 1]>,
133}
134
135pub struct RemoteWorktree {
136 snapshot: Snapshot,
137 background_snapshot: Arc<Mutex<(Snapshot, Vec<proto::UpdateWorktree>)>>,
138 project_id: u64,
139 client: AnyProtoClient,
140 file_scan_inclusions: PathMatcher,
141 updates_tx: Option<UnboundedSender<proto::UpdateWorktree>>,
142 update_observer: Option<mpsc::UnboundedSender<proto::UpdateWorktree>>,
143 snapshot_subscriptions: VecDeque<(usize, oneshot::Sender<()>)>,
144 replica_id: ReplicaId,
145 visible: bool,
146 disconnected: bool,
147}
148
149#[derive(Clone)]
150pub struct Snapshot {
151 id: WorktreeId,
152 abs_path: SanitizedPath,
153 root_name: String,
154 root_char_bag: CharBag,
155 entries_by_path: SumTree<Entry>,
156 entries_by_id: SumTree<PathEntry>,
157 always_included_entries: Vec<Arc<Path>>,
158
159 /// A number that increases every time the worktree begins scanning
160 /// a set of paths from the filesystem. This scanning could be caused
161 /// by some operation performed on the worktree, such as reading or
162 /// writing a file, or by an event reported by the filesystem.
163 scan_id: usize,
164
165 /// The latest scan id that has completed, and whose preceding scans
166 /// have all completed. The current `scan_id` could be more than one
167 /// greater than the `completed_scan_id` if operations are performed
168 /// on the worktree while it is processing a file-system event.
169 completed_scan_id: usize,
170}
171
172/// This path corresponds to the 'content path' of a repository in relation
173/// to Zed's project root.
174/// In the majority of the cases, this is the folder that contains the .git folder.
175/// But if a sub-folder of a git repository is opened, this corresponds to the
176/// project root and the .git folder is located in a parent directory.
177#[derive(Clone, Debug, Ord, PartialOrd, Eq, PartialEq, Hash)]
178pub enum WorkDirectory {
179 InProject {
180 relative_path: Arc<Path>,
181 },
182 AboveProject {
183 absolute_path: Arc<Path>,
184 location_in_repo: Arc<Path>,
185 },
186}
187
188impl WorkDirectory {
189 #[cfg(test)]
190 fn in_project(path: &str) -> Self {
191 let path = Path::new(path);
192 Self::InProject {
193 relative_path: path.into(),
194 }
195 }
196
197 //#[cfg(test)]
198 //fn canonicalize(&self) -> Self {
199 // match self {
200 // WorkDirectory::InProject { relative_path } => WorkDirectory::InProject {
201 // relative_path: relative_path.clone(),
202 // },
203 // WorkDirectory::AboveProject {
204 // absolute_path,
205 // location_in_repo,
206 // } => WorkDirectory::AboveProject {
207 // absolute_path: absolute_path.canonicalize().unwrap().into(),
208 // location_in_repo: location_in_repo.clone(),
209 // },
210 // }
211 //}
212
213 fn path_key(&self) -> PathKey {
214 match self {
215 WorkDirectory::InProject { relative_path } => PathKey(relative_path.clone()),
216 WorkDirectory::AboveProject { .. } => PathKey(Path::new("").into()),
217 }
218 }
219
220 /// Returns true if the given path is a child of the work directory.
221 ///
222 /// Note that the path may not be a member of this repository, if there
223 /// is a repository in a directory between these two paths
224 /// external .git folder in a parent folder of the project root.
225 #[track_caller]
226 pub fn directory_contains(&self, path: impl AsRef<Path>) -> bool {
227 let path = path.as_ref();
228 debug_assert!(path.is_relative());
229 match self {
230 WorkDirectory::InProject { relative_path } => path.starts_with(relative_path),
231 WorkDirectory::AboveProject { .. } => true,
232 }
233 }
234
235 /// relativize returns the given project path relative to the root folder of the
236 /// repository.
237 /// If the root of the repository (and its .git folder) are located in a parent folder
238 /// of the project root folder, then the returned RepoPath is relative to the root
239 /// of the repository and not a valid path inside the project.
240 pub fn relativize(&self, path: &Path) -> Result<RepoPath> {
241 // path is assumed to be relative to worktree root.
242 debug_assert!(path.is_relative());
243 match self {
244 WorkDirectory::InProject { relative_path } => Ok(path
245 .strip_prefix(relative_path)
246 .map_err(|_| {
247 anyhow!(
248 "could not relativize {:?} against {:?}",
249 path,
250 relative_path
251 )
252 })?
253 .into()),
254 WorkDirectory::AboveProject {
255 location_in_repo, ..
256 } => {
257 // Avoid joining a `/` to location_in_repo in the case of a single-file worktree.
258 if path == Path::new("") {
259 Ok(RepoPath(location_in_repo.clone()))
260 } else {
261 Ok(location_in_repo.join(path).into())
262 }
263 }
264 }
265 }
266
267 /// This is the opposite operation to `relativize` above
268 pub fn try_unrelativize(&self, path: &RepoPath) -> Option<Arc<Path>> {
269 match self {
270 WorkDirectory::InProject { relative_path } => Some(relative_path.join(path).into()),
271 WorkDirectory::AboveProject {
272 location_in_repo, ..
273 } => {
274 // If we fail to strip the prefix, that means this status entry is
275 // external to this worktree, and we definitely won't have an entry_id
276 path.strip_prefix(location_in_repo).ok().map(Into::into)
277 }
278 }
279 }
280
281 pub fn unrelativize(&self, path: &RepoPath) -> Arc<Path> {
282 match self {
283 WorkDirectory::InProject { relative_path } => relative_path.join(path).into(),
284 WorkDirectory::AboveProject {
285 location_in_repo, ..
286 } => {
287 if &path.0 == location_in_repo {
288 // Single-file worktree
289 return location_in_repo
290 .file_name()
291 .map(Path::new)
292 .unwrap_or(Path::new(""))
293 .into();
294 }
295 let mut location_in_repo = &**location_in_repo;
296 let mut parents = PathBuf::new();
297 loop {
298 if let Ok(segment) = path.strip_prefix(location_in_repo) {
299 return parents.join(segment).into();
300 }
301 location_in_repo = location_in_repo.parent().unwrap_or(Path::new(""));
302 parents.push(Component::ParentDir);
303 }
304 }
305 }
306 }
307
308 pub fn display_name(&self) -> String {
309 match self {
310 WorkDirectory::InProject { relative_path } => relative_path.display().to_string(),
311 WorkDirectory::AboveProject {
312 absolute_path,
313 location_in_repo,
314 } => {
315 let num_of_dots = location_in_repo.components().count();
316
317 "../".repeat(num_of_dots)
318 + &absolute_path
319 .file_name()
320 .map(|s| s.to_string_lossy())
321 .unwrap_or_default()
322 + "/"
323 }
324 }
325 }
326}
327
328impl Default for WorkDirectory {
329 fn default() -> Self {
330 Self::InProject {
331 relative_path: Arc::from(Path::new("")),
332 }
333 }
334}
335
336#[derive(Clone, Debug, Ord, PartialOrd, Eq, PartialEq)]
337pub struct WorkDirectoryEntry(ProjectEntryId);
338
339impl Deref for WorkDirectoryEntry {
340 type Target = ProjectEntryId;
341
342 fn deref(&self) -> &Self::Target {
343 &self.0
344 }
345}
346
347impl From<ProjectEntryId> for WorkDirectoryEntry {
348 fn from(value: ProjectEntryId) -> Self {
349 WorkDirectoryEntry(value)
350 }
351}
352
353#[derive(Debug, Clone)]
354pub struct LocalSnapshot {
355 snapshot: Snapshot,
356 /// All of the gitignore files in the worktree, indexed by their relative path.
357 /// The boolean indicates whether the gitignore needs to be updated.
358 ignores_by_parent_abs_path: HashMap<Arc<Path>, (Arc<Gitignore>, bool)>,
359 /// All of the git repositories in the worktree, indexed by the project entry
360 /// id of their parent directory.
361 git_repositories: TreeMap<ProjectEntryId, LocalRepositoryEntry>,
362 /// The file handle of the root dir
363 /// (so we can find it after it's been moved)
364 root_file_handle: Option<Arc<dyn fs::FileHandle>>,
365}
366
367struct BackgroundScannerState {
368 snapshot: LocalSnapshot,
369 scanned_dirs: HashSet<ProjectEntryId>,
370 path_prefixes_to_scan: HashSet<Arc<Path>>,
371 paths_to_scan: HashSet<Arc<Path>>,
372 /// The ids of all of the entries that were removed from the snapshot
373 /// as part of the current update. These entry ids may be re-used
374 /// if the same inode is discovered at a new path, or if the given
375 /// path is re-created after being deleted.
376 removed_entries: HashMap<u64, Entry>,
377 changed_paths: Vec<Arc<Path>>,
378 prev_snapshot: Snapshot,
379}
380
381#[derive(Debug, Clone)]
382struct LocalRepositoryEntry {
383 work_directory_id: ProjectEntryId,
384 work_directory: WorkDirectory,
385 work_directory_abs_path: Arc<Path>,
386 git_dir_scan_id: usize,
387 original_dot_git_abs_path: Arc<Path>,
388 /// Absolute path to the actual .git folder.
389 /// Note: if .git is a file, this points to the folder indicated by the .git file
390 dot_git_dir_abs_path: Arc<Path>,
391 /// Absolute path to the .git file, if we're in a git worktree.
392 dot_git_worktree_abs_path: Option<Arc<Path>>,
393}
394
395impl sum_tree::Item for LocalRepositoryEntry {
396 type Summary = PathSummary<Unit>;
397
398 fn summary(&self, _: &<Self::Summary as Summary>::Context) -> Self::Summary {
399 PathSummary {
400 max_path: self.work_directory.path_key().0,
401 item_summary: Unit,
402 }
403 }
404}
405
406impl KeyedItem for LocalRepositoryEntry {
407 type Key = PathKey;
408
409 fn key(&self) -> Self::Key {
410 self.work_directory.path_key()
411 }
412}
413
414//impl LocalRepositoryEntry {
415// pub fn repo(&self) -> &Arc<dyn GitRepository> {
416// &self.repo_ptr
417// }
418//}
419
420impl Deref for LocalRepositoryEntry {
421 type Target = WorkDirectory;
422
423 fn deref(&self) -> &Self::Target {
424 &self.work_directory
425 }
426}
427
428impl Deref for LocalSnapshot {
429 type Target = Snapshot;
430
431 fn deref(&self) -> &Self::Target {
432 &self.snapshot
433 }
434}
435
436impl DerefMut for LocalSnapshot {
437 fn deref_mut(&mut self) -> &mut Self::Target {
438 &mut self.snapshot
439 }
440}
441
442#[derive(Debug)]
443enum ScanState {
444 Started,
445 Updated {
446 snapshot: LocalSnapshot,
447 changes: UpdatedEntriesSet,
448 barrier: SmallVec<[barrier::Sender; 1]>,
449 scanning: bool,
450 },
451 RootUpdated {
452 new_path: Option<SanitizedPath>,
453 },
454}
455
456struct UpdateObservationState {
457 snapshots_tx: mpsc::UnboundedSender<(LocalSnapshot, UpdatedEntriesSet)>,
458 resume_updates: watch::Sender<()>,
459 _maintain_remote_snapshot: Task<Option<()>>,
460}
461
462#[derive(Clone)]
463pub enum Event {
464 UpdatedEntries(UpdatedEntriesSet),
465 UpdatedGitRepositories(UpdatedGitRepositoriesSet),
466 DeletedEntry(ProjectEntryId),
467}
468
469const EMPTY_PATH: &str = "";
470
471impl EventEmitter<Event> for Worktree {}
472
473impl Worktree {
474 pub async fn local(
475 path: impl Into<Arc<Path>>,
476 visible: bool,
477 fs: Arc<dyn Fs>,
478 next_entry_id: Arc<AtomicUsize>,
479 cx: &mut AsyncApp,
480 ) -> Result<Entity<Self>> {
481 let abs_path = path.into();
482 let metadata = fs
483 .metadata(&abs_path)
484 .await
485 .context("failed to stat worktree path")?;
486
487 let fs_case_sensitive = fs.is_case_sensitive().await.unwrap_or_else(|e| {
488 log::error!(
489 "Failed to determine whether filesystem is case sensitive (falling back to true) due to error: {e:#}"
490 );
491 true
492 });
493
494 let root_file_handle = fs.open_handle(&abs_path).await.log_err();
495
496 cx.new(move |cx: &mut Context<Worktree>| {
497 let mut snapshot = LocalSnapshot {
498 ignores_by_parent_abs_path: Default::default(),
499 git_repositories: Default::default(),
500 snapshot: Snapshot::new(
501 cx.entity_id().as_u64(),
502 abs_path
503 .file_name()
504 .map_or(String::new(), |f| f.to_string_lossy().to_string()),
505 abs_path.clone(),
506 ),
507 root_file_handle,
508 };
509
510 let worktree_id = snapshot.id();
511 let settings_location = Some(SettingsLocation {
512 worktree_id,
513 path: Path::new(EMPTY_PATH),
514 });
515
516 let settings = WorktreeSettings::get(settings_location, cx).clone();
517 cx.observe_global::<SettingsStore>(move |this, cx| {
518 if let Self::Local(this) = this {
519 let settings = WorktreeSettings::get(settings_location, cx).clone();
520 if this.settings != settings {
521 this.settings = settings;
522 this.restart_background_scanners(cx);
523 }
524 }
525 })
526 .detach();
527
528 let share_private_files = false;
529 if let Some(metadata) = metadata {
530 let mut entry = Entry::new(
531 Arc::from(Path::new("")),
532 &metadata,
533 &next_entry_id,
534 snapshot.root_char_bag,
535 None,
536 );
537 if !metadata.is_dir {
538 entry.is_private = !share_private_files
539 && settings.is_path_private(abs_path.file_name().unwrap().as_ref());
540 }
541 snapshot.insert_entry(entry, fs.as_ref());
542 }
543
544 let (scan_requests_tx, scan_requests_rx) = channel::unbounded();
545 let (path_prefixes_to_scan_tx, path_prefixes_to_scan_rx) = channel::unbounded();
546 let mut worktree = LocalWorktree {
547 share_private_files,
548 next_entry_id,
549 snapshot,
550 is_scanning: watch::channel_with(true),
551 update_observer: None,
552 scan_requests_tx,
553 path_prefixes_to_scan_tx,
554 _background_scanner_tasks: Vec::new(),
555 fs,
556 fs_case_sensitive,
557 visible,
558 settings,
559 };
560 worktree.start_background_scanner(scan_requests_rx, path_prefixes_to_scan_rx, cx);
561 Worktree::Local(worktree)
562 })
563 }
564
565 pub fn remote(
566 project_id: u64,
567 replica_id: ReplicaId,
568 worktree: proto::WorktreeMetadata,
569 client: AnyProtoClient,
570 cx: &mut App,
571 ) -> Entity<Self> {
572 cx.new(|cx: &mut Context<Self>| {
573 let snapshot = Snapshot::new(
574 worktree.id,
575 worktree.root_name,
576 Arc::<Path>::from_proto(worktree.abs_path),
577 );
578
579 let background_snapshot = Arc::new(Mutex::new((
580 snapshot.clone(),
581 Vec::<proto::UpdateWorktree>::new(),
582 )));
583 let (background_updates_tx, mut background_updates_rx) =
584 mpsc::unbounded::<proto::UpdateWorktree>();
585 let (mut snapshot_updated_tx, mut snapshot_updated_rx) = watch::channel();
586
587 let worktree_id = snapshot.id();
588 let settings_location = Some(SettingsLocation {
589 worktree_id,
590 path: Path::new(EMPTY_PATH),
591 });
592
593 let settings = WorktreeSettings::get(settings_location, cx).clone();
594 let worktree = RemoteWorktree {
595 client,
596 project_id,
597 replica_id,
598 snapshot,
599 file_scan_inclusions: settings.file_scan_inclusions.clone(),
600 background_snapshot: background_snapshot.clone(),
601 updates_tx: Some(background_updates_tx),
602 update_observer: None,
603 snapshot_subscriptions: Default::default(),
604 visible: worktree.visible,
605 disconnected: false,
606 };
607
608 // Apply updates to a separate snapshot in a background task, then
609 // send them to a foreground task which updates the model.
610 cx.background_spawn(async move {
611 while let Some(update) = background_updates_rx.next().await {
612 {
613 let mut lock = background_snapshot.lock();
614 lock.0
615 .apply_remote_update(update.clone(), &settings.file_scan_inclusions)
616 .log_err();
617 lock.1.push(update);
618 }
619 snapshot_updated_tx.send(()).await.ok();
620 }
621 })
622 .detach();
623
624 // On the foreground task, update to the latest snapshot and notify
625 // any update observer of all updates that led to that snapshot.
626 cx.spawn(async move |this, cx| {
627 while (snapshot_updated_rx.recv().await).is_some() {
628 this.update(cx, |this, cx| {
629 let mut entries_changed = false;
630 let this = this.as_remote_mut().unwrap();
631 {
632 let mut lock = this.background_snapshot.lock();
633 this.snapshot = lock.0.clone();
634 for update in lock.1.drain(..) {
635 entries_changed |= !update.updated_entries.is_empty()
636 || !update.removed_entries.is_empty();
637 if let Some(tx) = &this.update_observer {
638 tx.unbounded_send(update).ok();
639 }
640 }
641 };
642
643 if entries_changed {
644 cx.emit(Event::UpdatedEntries(Arc::default()));
645 }
646 cx.notify();
647 while let Some((scan_id, _)) = this.snapshot_subscriptions.front() {
648 if this.observed_snapshot(*scan_id) {
649 let (_, tx) = this.snapshot_subscriptions.pop_front().unwrap();
650 let _ = tx.send(());
651 } else {
652 break;
653 }
654 }
655 })?;
656 }
657 anyhow::Ok(())
658 })
659 .detach();
660
661 Worktree::Remote(worktree)
662 })
663 }
664
665 pub fn as_local(&self) -> Option<&LocalWorktree> {
666 if let Worktree::Local(worktree) = self {
667 Some(worktree)
668 } else {
669 None
670 }
671 }
672
673 pub fn as_remote(&self) -> Option<&RemoteWorktree> {
674 if let Worktree::Remote(worktree) = self {
675 Some(worktree)
676 } else {
677 None
678 }
679 }
680
681 pub fn as_local_mut(&mut self) -> Option<&mut LocalWorktree> {
682 if let Worktree::Local(worktree) = self {
683 Some(worktree)
684 } else {
685 None
686 }
687 }
688
689 pub fn as_remote_mut(&mut self) -> Option<&mut RemoteWorktree> {
690 if let Worktree::Remote(worktree) = self {
691 Some(worktree)
692 } else {
693 None
694 }
695 }
696
697 pub fn is_local(&self) -> bool {
698 matches!(self, Worktree::Local(_))
699 }
700
701 pub fn is_remote(&self) -> bool {
702 !self.is_local()
703 }
704
705 pub fn settings_location(&self, _: &Context<Self>) -> SettingsLocation<'static> {
706 SettingsLocation {
707 worktree_id: self.id(),
708 path: Path::new(EMPTY_PATH),
709 }
710 }
711
712 pub fn snapshot(&self) -> Snapshot {
713 match self {
714 Worktree::Local(worktree) => worktree.snapshot.snapshot.clone(),
715 Worktree::Remote(worktree) => worktree.snapshot.clone(),
716 }
717 }
718
719 pub fn scan_id(&self) -> usize {
720 match self {
721 Worktree::Local(worktree) => worktree.snapshot.scan_id,
722 Worktree::Remote(worktree) => worktree.snapshot.scan_id,
723 }
724 }
725
726 pub fn metadata_proto(&self) -> proto::WorktreeMetadata {
727 proto::WorktreeMetadata {
728 id: self.id().to_proto(),
729 root_name: self.root_name().to_string(),
730 visible: self.is_visible(),
731 abs_path: self.abs_path().to_proto(),
732 }
733 }
734
735 pub fn completed_scan_id(&self) -> usize {
736 match self {
737 Worktree::Local(worktree) => worktree.snapshot.completed_scan_id,
738 Worktree::Remote(worktree) => worktree.snapshot.completed_scan_id,
739 }
740 }
741
742 pub fn is_visible(&self) -> bool {
743 match self {
744 Worktree::Local(worktree) => worktree.visible,
745 Worktree::Remote(worktree) => worktree.visible,
746 }
747 }
748
749 pub fn replica_id(&self) -> ReplicaId {
750 match self {
751 Worktree::Local(_) => 0,
752 Worktree::Remote(worktree) => worktree.replica_id,
753 }
754 }
755
756 pub fn abs_path(&self) -> Arc<Path> {
757 match self {
758 Worktree::Local(worktree) => worktree.abs_path.clone().into(),
759 Worktree::Remote(worktree) => worktree.abs_path.clone().into(),
760 }
761 }
762
763 pub fn root_file(&self, cx: &Context<Self>) -> Option<Arc<File>> {
764 let entry = self.root_entry()?;
765 Some(File::for_entry(entry.clone(), cx.entity()))
766 }
767
768 pub fn observe_updates<F, Fut>(&mut self, project_id: u64, cx: &Context<Worktree>, callback: F)
769 where
770 F: 'static + Send + Fn(proto::UpdateWorktree) -> Fut,
771 Fut: 'static + Send + Future<Output = bool>,
772 {
773 match self {
774 Worktree::Local(this) => this.observe_updates(project_id, cx, callback),
775 Worktree::Remote(this) => this.observe_updates(project_id, cx, callback),
776 }
777 }
778
779 pub fn stop_observing_updates(&mut self) {
780 match self {
781 Worktree::Local(this) => {
782 this.update_observer.take();
783 }
784 Worktree::Remote(this) => {
785 this.update_observer.take();
786 }
787 }
788 }
789
790 #[cfg(any(test, feature = "test-support"))]
791 pub fn has_update_observer(&self) -> bool {
792 match self {
793 Worktree::Local(this) => this.update_observer.is_some(),
794 Worktree::Remote(this) => this.update_observer.is_some(),
795 }
796 }
797
798 pub fn load_file(&self, path: &Path, cx: &Context<Worktree>) -> Task<Result<LoadedFile>> {
799 match self {
800 Worktree::Local(this) => this.load_file(path, cx),
801 Worktree::Remote(_) => {
802 Task::ready(Err(anyhow!("remote worktrees can't yet load files")))
803 }
804 }
805 }
806
807 pub fn load_binary_file(
808 &self,
809 path: &Path,
810 cx: &Context<Worktree>,
811 ) -> Task<Result<LoadedBinaryFile>> {
812 match self {
813 Worktree::Local(this) => this.load_binary_file(path, cx),
814 Worktree::Remote(_) => {
815 Task::ready(Err(anyhow!("remote worktrees can't yet load binary files")))
816 }
817 }
818 }
819
820 pub fn write_file(
821 &self,
822 path: &Path,
823 text: Rope,
824 line_ending: LineEnding,
825 cx: &Context<Worktree>,
826 ) -> Task<Result<Arc<File>>> {
827 match self {
828 Worktree::Local(this) => this.write_file(path, text, line_ending, cx),
829 Worktree::Remote(_) => {
830 Task::ready(Err(anyhow!("remote worktree can't yet write files")))
831 }
832 }
833 }
834
835 pub fn create_entry(
836 &mut self,
837 path: impl Into<Arc<Path>>,
838 is_directory: bool,
839 cx: &Context<Worktree>,
840 ) -> Task<Result<CreatedEntry>> {
841 let path: Arc<Path> = path.into();
842 let worktree_id = self.id();
843 match self {
844 Worktree::Local(this) => this.create_entry(path, is_directory, cx),
845 Worktree::Remote(this) => {
846 let project_id = this.project_id;
847 let request = this.client.request(proto::CreateProjectEntry {
848 worktree_id: worktree_id.to_proto(),
849 project_id,
850 path: path.as_ref().to_proto(),
851 is_directory,
852 });
853 cx.spawn(async move |this, cx| {
854 let response = request.await?;
855 match response.entry {
856 Some(entry) => this
857 .update(cx, |worktree, cx| {
858 worktree.as_remote_mut().unwrap().insert_entry(
859 entry,
860 response.worktree_scan_id as usize,
861 cx,
862 )
863 })?
864 .await
865 .map(CreatedEntry::Included),
866 None => {
867 let abs_path = this.update(cx, |worktree, _| {
868 worktree
869 .absolutize(&path)
870 .with_context(|| format!("absolutizing {path:?}"))
871 })??;
872 Ok(CreatedEntry::Excluded { abs_path })
873 }
874 }
875 })
876 }
877 }
878 }
879
880 pub fn delete_entry(
881 &mut self,
882 entry_id: ProjectEntryId,
883 trash: bool,
884 cx: &mut Context<Worktree>,
885 ) -> Option<Task<Result<()>>> {
886 let task = match self {
887 Worktree::Local(this) => this.delete_entry(entry_id, trash, cx),
888 Worktree::Remote(this) => this.delete_entry(entry_id, trash, cx),
889 }?;
890
891 let entry = match &*self {
892 Worktree::Local(this) => this.entry_for_id(entry_id),
893 Worktree::Remote(this) => this.entry_for_id(entry_id),
894 }?;
895
896 let mut ids = vec![entry_id];
897 let path = &*entry.path;
898
899 self.get_children_ids_recursive(path, &mut ids);
900
901 for id in ids {
902 cx.emit(Event::DeletedEntry(id));
903 }
904 Some(task)
905 }
906
907 fn get_children_ids_recursive(&self, path: &Path, ids: &mut Vec<ProjectEntryId>) {
908 let children_iter = self.child_entries(path);
909 for child in children_iter {
910 ids.push(child.id);
911 self.get_children_ids_recursive(&child.path, ids);
912 }
913 }
914
915 pub fn rename_entry(
916 &mut self,
917 entry_id: ProjectEntryId,
918 new_path: impl Into<Arc<Path>>,
919 cx: &Context<Self>,
920 ) -> Task<Result<CreatedEntry>> {
921 let new_path = new_path.into();
922 match self {
923 Worktree::Local(this) => this.rename_entry(entry_id, new_path, cx),
924 Worktree::Remote(this) => this.rename_entry(entry_id, new_path, cx),
925 }
926 }
927
928 pub fn copy_entry(
929 &mut self,
930 entry_id: ProjectEntryId,
931 relative_worktree_source_path: Option<PathBuf>,
932 new_path: impl Into<Arc<Path>>,
933 cx: &Context<Self>,
934 ) -> Task<Result<Option<Entry>>> {
935 let new_path: Arc<Path> = new_path.into();
936 match self {
937 Worktree::Local(this) => {
938 this.copy_entry(entry_id, relative_worktree_source_path, new_path, cx)
939 }
940 Worktree::Remote(this) => {
941 let relative_worktree_source_path = relative_worktree_source_path
942 .map(|relative_worktree_source_path| relative_worktree_source_path.to_proto());
943 let response = this.client.request(proto::CopyProjectEntry {
944 project_id: this.project_id,
945 entry_id: entry_id.to_proto(),
946 relative_worktree_source_path,
947 new_path: new_path.to_proto(),
948 });
949 cx.spawn(async move |this, cx| {
950 let response = response.await?;
951 match response.entry {
952 Some(entry) => this
953 .update(cx, |worktree, cx| {
954 worktree.as_remote_mut().unwrap().insert_entry(
955 entry,
956 response.worktree_scan_id as usize,
957 cx,
958 )
959 })?
960 .await
961 .map(Some),
962 None => Ok(None),
963 }
964 })
965 }
966 }
967 }
968
969 pub fn copy_external_entries(
970 &mut self,
971 target_directory: PathBuf,
972 paths: Vec<Arc<Path>>,
973 overwrite_existing_files: bool,
974 cx: &Context<Worktree>,
975 ) -> Task<Result<Vec<ProjectEntryId>>> {
976 match self {
977 Worktree::Local(this) => {
978 this.copy_external_entries(target_directory, paths, overwrite_existing_files, cx)
979 }
980 _ => Task::ready(Err(anyhow!(
981 "Copying external entries is not supported for remote worktrees"
982 ))),
983 }
984 }
985
986 pub fn expand_entry(
987 &mut self,
988 entry_id: ProjectEntryId,
989 cx: &Context<Worktree>,
990 ) -> Option<Task<Result<()>>> {
991 match self {
992 Worktree::Local(this) => this.expand_entry(entry_id, cx),
993 Worktree::Remote(this) => {
994 let response = this.client.request(proto::ExpandProjectEntry {
995 project_id: this.project_id,
996 entry_id: entry_id.to_proto(),
997 });
998 Some(cx.spawn(async move |this, cx| {
999 let response = response.await?;
1000 this.update(cx, |this, _| {
1001 this.as_remote_mut()
1002 .unwrap()
1003 .wait_for_snapshot(response.worktree_scan_id as usize)
1004 })?
1005 .await?;
1006 Ok(())
1007 }))
1008 }
1009 }
1010 }
1011
1012 pub fn expand_all_for_entry(
1013 &mut self,
1014 entry_id: ProjectEntryId,
1015 cx: &Context<Worktree>,
1016 ) -> Option<Task<Result<()>>> {
1017 match self {
1018 Worktree::Local(this) => this.expand_all_for_entry(entry_id, cx),
1019 Worktree::Remote(this) => {
1020 let response = this.client.request(proto::ExpandAllForProjectEntry {
1021 project_id: this.project_id,
1022 entry_id: entry_id.to_proto(),
1023 });
1024 Some(cx.spawn(async move |this, cx| {
1025 let response = response.await?;
1026 this.update(cx, |this, _| {
1027 this.as_remote_mut()
1028 .unwrap()
1029 .wait_for_snapshot(response.worktree_scan_id as usize)
1030 })?
1031 .await?;
1032 Ok(())
1033 }))
1034 }
1035 }
1036 }
1037
1038 pub async fn handle_create_entry(
1039 this: Entity<Self>,
1040 request: proto::CreateProjectEntry,
1041 mut cx: AsyncApp,
1042 ) -> Result<proto::ProjectEntryResponse> {
1043 let (scan_id, entry) = this.update(&mut cx, |this, cx| {
1044 (
1045 this.scan_id(),
1046 this.create_entry(
1047 Arc::<Path>::from_proto(request.path),
1048 request.is_directory,
1049 cx,
1050 ),
1051 )
1052 })?;
1053 Ok(proto::ProjectEntryResponse {
1054 entry: match &entry.await? {
1055 CreatedEntry::Included(entry) => Some(entry.into()),
1056 CreatedEntry::Excluded { .. } => None,
1057 },
1058 worktree_scan_id: scan_id as u64,
1059 })
1060 }
1061
1062 pub async fn handle_delete_entry(
1063 this: Entity<Self>,
1064 request: proto::DeleteProjectEntry,
1065 mut cx: AsyncApp,
1066 ) -> Result<proto::ProjectEntryResponse> {
1067 let (scan_id, task) = this.update(&mut cx, |this, cx| {
1068 (
1069 this.scan_id(),
1070 this.delete_entry(
1071 ProjectEntryId::from_proto(request.entry_id),
1072 request.use_trash,
1073 cx,
1074 ),
1075 )
1076 })?;
1077 task.ok_or_else(|| anyhow!("invalid entry"))?.await?;
1078 Ok(proto::ProjectEntryResponse {
1079 entry: None,
1080 worktree_scan_id: scan_id as u64,
1081 })
1082 }
1083
1084 pub async fn handle_expand_entry(
1085 this: Entity<Self>,
1086 request: proto::ExpandProjectEntry,
1087 mut cx: AsyncApp,
1088 ) -> Result<proto::ExpandProjectEntryResponse> {
1089 let task = this.update(&mut cx, |this, cx| {
1090 this.expand_entry(ProjectEntryId::from_proto(request.entry_id), cx)
1091 })?;
1092 task.ok_or_else(|| anyhow!("no such entry"))?.await?;
1093 let scan_id = this.read_with(&cx, |this, _| this.scan_id())?;
1094 Ok(proto::ExpandProjectEntryResponse {
1095 worktree_scan_id: scan_id as u64,
1096 })
1097 }
1098
1099 pub async fn handle_expand_all_for_entry(
1100 this: Entity<Self>,
1101 request: proto::ExpandAllForProjectEntry,
1102 mut cx: AsyncApp,
1103 ) -> Result<proto::ExpandAllForProjectEntryResponse> {
1104 let task = this.update(&mut cx, |this, cx| {
1105 this.expand_all_for_entry(ProjectEntryId::from_proto(request.entry_id), cx)
1106 })?;
1107 task.ok_or_else(|| anyhow!("no such entry"))?.await?;
1108 let scan_id = this.read_with(&cx, |this, _| this.scan_id())?;
1109 Ok(proto::ExpandAllForProjectEntryResponse {
1110 worktree_scan_id: scan_id as u64,
1111 })
1112 }
1113
1114 pub async fn handle_rename_entry(
1115 this: Entity<Self>,
1116 request: proto::RenameProjectEntry,
1117 mut cx: AsyncApp,
1118 ) -> Result<proto::ProjectEntryResponse> {
1119 let (scan_id, task) = this.update(&mut cx, |this, cx| {
1120 (
1121 this.scan_id(),
1122 this.rename_entry(
1123 ProjectEntryId::from_proto(request.entry_id),
1124 Arc::<Path>::from_proto(request.new_path),
1125 cx,
1126 ),
1127 )
1128 })?;
1129 Ok(proto::ProjectEntryResponse {
1130 entry: match &task.await? {
1131 CreatedEntry::Included(entry) => Some(entry.into()),
1132 CreatedEntry::Excluded { .. } => None,
1133 },
1134 worktree_scan_id: scan_id as u64,
1135 })
1136 }
1137
1138 pub async fn handle_copy_entry(
1139 this: Entity<Self>,
1140 request: proto::CopyProjectEntry,
1141 mut cx: AsyncApp,
1142 ) -> Result<proto::ProjectEntryResponse> {
1143 let (scan_id, task) = this.update(&mut cx, |this, cx| {
1144 let relative_worktree_source_path = request
1145 .relative_worktree_source_path
1146 .map(PathBuf::from_proto);
1147 (
1148 this.scan_id(),
1149 this.copy_entry(
1150 ProjectEntryId::from_proto(request.entry_id),
1151 relative_worktree_source_path,
1152 PathBuf::from_proto(request.new_path),
1153 cx,
1154 ),
1155 )
1156 })?;
1157 Ok(proto::ProjectEntryResponse {
1158 entry: task.await?.as_ref().map(|e| e.into()),
1159 worktree_scan_id: scan_id as u64,
1160 })
1161 }
1162
1163 pub fn dot_git_abs_path(&self, work_directory: &WorkDirectory) -> PathBuf {
1164 let mut path = match work_directory {
1165 WorkDirectory::InProject { relative_path } => self.abs_path().join(relative_path),
1166 WorkDirectory::AboveProject { absolute_path, .. } => absolute_path.as_ref().to_owned(),
1167 };
1168 path.push(".git");
1169 path
1170 }
1171
1172 pub fn is_single_file(&self) -> bool {
1173 self.root_dir().is_none()
1174 }
1175
1176 /// For visible worktrees, returns the path with the worktree name as the first component.
1177 /// Otherwise, returns an absolute path.
1178 pub fn full_path(&self, worktree_relative_path: &Path) -> PathBuf {
1179 let mut full_path = PathBuf::new();
1180
1181 if self.is_visible() {
1182 full_path.push(self.root_name());
1183 } else {
1184 let path = self.abs_path();
1185
1186 if self.is_local() && path.starts_with(home_dir().as_path()) {
1187 full_path.push("~");
1188 full_path.push(path.strip_prefix(home_dir().as_path()).unwrap());
1189 } else {
1190 full_path.push(path)
1191 }
1192 }
1193
1194 if worktree_relative_path.components().next().is_some() {
1195 full_path.push(&worktree_relative_path);
1196 }
1197
1198 full_path
1199 }
1200}
1201
1202impl LocalWorktree {
1203 pub fn fs(&self) -> &Arc<dyn Fs> {
1204 &self.fs
1205 }
1206
1207 pub fn is_path_private(&self, path: &Path) -> bool {
1208 !self.share_private_files && self.settings.is_path_private(path)
1209 }
1210
1211 fn restart_background_scanners(&mut self, cx: &Context<Worktree>) {
1212 let (scan_requests_tx, scan_requests_rx) = channel::unbounded();
1213 let (path_prefixes_to_scan_tx, path_prefixes_to_scan_rx) = channel::unbounded();
1214 self.scan_requests_tx = scan_requests_tx;
1215 self.path_prefixes_to_scan_tx = path_prefixes_to_scan_tx;
1216
1217 self.start_background_scanner(scan_requests_rx, path_prefixes_to_scan_rx, cx);
1218 let always_included_entries = mem::take(&mut self.snapshot.always_included_entries);
1219 log::debug!(
1220 "refreshing entries for the following always included paths: {:?}",
1221 always_included_entries
1222 );
1223
1224 // Cleans up old always included entries to ensure they get updated properly. Otherwise,
1225 // nested always included entries may not get updated and will result in out-of-date info.
1226 self.refresh_entries_for_paths(always_included_entries);
1227 }
1228
1229 fn start_background_scanner(
1230 &mut self,
1231 scan_requests_rx: channel::Receiver<ScanRequest>,
1232 path_prefixes_to_scan_rx: channel::Receiver<PathPrefixScanRequest>,
1233 cx: &Context<Worktree>,
1234 ) {
1235 let snapshot = self.snapshot();
1236 let share_private_files = self.share_private_files;
1237 let next_entry_id = self.next_entry_id.clone();
1238 let fs = self.fs.clone();
1239 let settings = self.settings.clone();
1240 let (scan_states_tx, mut scan_states_rx) = mpsc::unbounded();
1241 let background_scanner = cx.background_spawn({
1242 let abs_path = snapshot.abs_path.as_path().to_path_buf();
1243 let background = cx.background_executor().clone();
1244 async move {
1245 let (events, watcher) = fs.watch(&abs_path, FS_WATCH_LATENCY).await;
1246 let fs_case_sensitive = fs.is_case_sensitive().await.unwrap_or_else(|e| {
1247 log::error!("Failed to determine whether filesystem is case sensitive: {e:#}");
1248 true
1249 });
1250
1251 let mut scanner = BackgroundScanner {
1252 fs,
1253 fs_case_sensitive,
1254 status_updates_tx: scan_states_tx,
1255 executor: background,
1256 scan_requests_rx,
1257 path_prefixes_to_scan_rx,
1258 next_entry_id,
1259 state: Mutex::new(BackgroundScannerState {
1260 prev_snapshot: snapshot.snapshot.clone(),
1261 snapshot,
1262 scanned_dirs: Default::default(),
1263 path_prefixes_to_scan: Default::default(),
1264 paths_to_scan: Default::default(),
1265 removed_entries: Default::default(),
1266 changed_paths: Default::default(),
1267 }),
1268 phase: BackgroundScannerPhase::InitialScan,
1269 share_private_files,
1270 settings,
1271 watcher,
1272 };
1273
1274 scanner
1275 .run(Box::pin(events.map(|events| events.into_iter().collect())))
1276 .await;
1277 }
1278 });
1279 let scan_state_updater = cx.spawn(async move |this, cx| {
1280 while let Some((state, this)) = scan_states_rx.next().await.zip(this.upgrade()) {
1281 this.update(cx, |this, cx| {
1282 let this = this.as_local_mut().unwrap();
1283 match state {
1284 ScanState::Started => {
1285 *this.is_scanning.0.borrow_mut() = true;
1286 }
1287 ScanState::Updated {
1288 snapshot,
1289 changes,
1290 barrier,
1291 scanning,
1292 } => {
1293 *this.is_scanning.0.borrow_mut() = scanning;
1294 this.set_snapshot(snapshot, changes, cx);
1295 drop(barrier);
1296 }
1297 ScanState::RootUpdated { new_path } => {
1298 this.update_abs_path_and_refresh(new_path, cx);
1299 }
1300 }
1301 })
1302 .ok();
1303 }
1304 });
1305 self._background_scanner_tasks = vec![background_scanner, scan_state_updater];
1306 self.is_scanning = watch::channel_with(true);
1307 }
1308
1309 fn set_snapshot(
1310 &mut self,
1311 mut new_snapshot: LocalSnapshot,
1312 entry_changes: UpdatedEntriesSet,
1313 cx: &mut Context<Worktree>,
1314 ) {
1315 let repo_changes = self.changed_repos(&self.snapshot, &mut new_snapshot);
1316 self.snapshot = new_snapshot;
1317
1318 if let Some(share) = self.update_observer.as_mut() {
1319 share
1320 .snapshots_tx
1321 .unbounded_send((self.snapshot.clone(), entry_changes.clone()))
1322 .ok();
1323 }
1324
1325 if !entry_changes.is_empty() {
1326 cx.emit(Event::UpdatedEntries(entry_changes));
1327 }
1328 if !repo_changes.is_empty() {
1329 cx.emit(Event::UpdatedGitRepositories(repo_changes));
1330 }
1331 }
1332
1333 fn changed_repos(
1334 &self,
1335 old_snapshot: &LocalSnapshot,
1336 new_snapshot: &mut LocalSnapshot,
1337 ) -> UpdatedGitRepositoriesSet {
1338 let mut changes = Vec::new();
1339 let mut old_repos = old_snapshot.git_repositories.iter().peekable();
1340 let new_repos = new_snapshot.git_repositories.clone();
1341 let mut new_repos = new_repos.iter().peekable();
1342
1343 loop {
1344 match (new_repos.peek().map(clone), old_repos.peek().map(clone)) {
1345 (Some((new_entry_id, new_repo)), Some((old_entry_id, old_repo))) => {
1346 match Ord::cmp(&new_entry_id, &old_entry_id) {
1347 Ordering::Less => {
1348 changes.push(UpdatedGitRepository {
1349 work_directory_id: new_entry_id,
1350 old_work_directory_abs_path: None,
1351 new_work_directory_abs_path: Some(
1352 new_repo.work_directory_abs_path.clone(),
1353 ),
1354 dot_git_abs_path: Some(new_repo.original_dot_git_abs_path.clone()),
1355 });
1356 new_repos.next();
1357 }
1358 Ordering::Equal => {
1359 if new_repo.git_dir_scan_id != old_repo.git_dir_scan_id
1360 || new_repo.work_directory_abs_path
1361 != old_repo.work_directory_abs_path
1362 {
1363 changes.push(UpdatedGitRepository {
1364 work_directory_id: new_entry_id,
1365 old_work_directory_abs_path: Some(
1366 old_repo.work_directory_abs_path.clone(),
1367 ),
1368 new_work_directory_abs_path: Some(
1369 new_repo.work_directory_abs_path.clone(),
1370 ),
1371 dot_git_abs_path: Some(
1372 new_repo.original_dot_git_abs_path.clone(),
1373 ),
1374 });
1375 }
1376 new_repos.next();
1377 old_repos.next();
1378 }
1379 Ordering::Greater => {
1380 changes.push(UpdatedGitRepository {
1381 work_directory_id: old_entry_id,
1382 old_work_directory_abs_path: Some(
1383 old_repo.work_directory_abs_path.clone(),
1384 ),
1385 new_work_directory_abs_path: None,
1386 dot_git_abs_path: None,
1387 });
1388 old_repos.next();
1389 }
1390 }
1391 }
1392 (Some((entry_id, repo)), None) => {
1393 changes.push(UpdatedGitRepository {
1394 work_directory_id: entry_id,
1395 old_work_directory_abs_path: None,
1396 new_work_directory_abs_path: Some(repo.work_directory_abs_path.clone()),
1397 dot_git_abs_path: Some(repo.original_dot_git_abs_path.clone()),
1398 });
1399 new_repos.next();
1400 }
1401 (None, Some((entry_id, repo))) => {
1402 changes.push(UpdatedGitRepository {
1403 work_directory_id: entry_id,
1404 old_work_directory_abs_path: Some(repo.work_directory_abs_path.clone()),
1405 new_work_directory_abs_path: None,
1406 dot_git_abs_path: Some(repo.original_dot_git_abs_path.clone()),
1407 });
1408 old_repos.next();
1409 }
1410 (None, None) => break,
1411 }
1412 }
1413
1414 fn clone<T: Clone, U: Clone>(value: &(&T, &U)) -> (T, U) {
1415 (value.0.clone(), value.1.clone())
1416 }
1417
1418 changes.into()
1419 }
1420
1421 pub fn scan_complete(&self) -> impl Future<Output = ()> + use<> {
1422 let mut is_scanning_rx = self.is_scanning.1.clone();
1423 async move {
1424 let mut is_scanning = *is_scanning_rx.borrow();
1425 while is_scanning {
1426 if let Some(value) = is_scanning_rx.recv().await {
1427 is_scanning = value;
1428 } else {
1429 break;
1430 }
1431 }
1432 }
1433 }
1434
1435 pub fn snapshot(&self) -> LocalSnapshot {
1436 self.snapshot.clone()
1437 }
1438
1439 pub fn settings(&self) -> WorktreeSettings {
1440 self.settings.clone()
1441 }
1442
1443 fn load_binary_file(
1444 &self,
1445 path: &Path,
1446 cx: &Context<Worktree>,
1447 ) -> Task<Result<LoadedBinaryFile>> {
1448 let path = Arc::from(path);
1449 let abs_path = self.absolutize(&path);
1450 let fs = self.fs.clone();
1451 let entry = self.refresh_entry(path.clone(), None, cx);
1452 let is_private = self.is_path_private(path.as_ref());
1453
1454 let worktree = cx.weak_entity();
1455 cx.background_spawn(async move {
1456 let abs_path = abs_path?;
1457 let content = fs.load_bytes(&abs_path).await?;
1458
1459 let worktree = worktree
1460 .upgrade()
1461 .ok_or_else(|| anyhow!("worktree was dropped"))?;
1462 let file = match entry.await? {
1463 Some(entry) => File::for_entry(entry, worktree),
1464 None => {
1465 let metadata = fs
1466 .metadata(&abs_path)
1467 .await
1468 .with_context(|| {
1469 format!("Loading metadata for excluded file {abs_path:?}")
1470 })?
1471 .with_context(|| {
1472 format!("Excluded file {abs_path:?} got removed during loading")
1473 })?;
1474 Arc::new(File {
1475 entry_id: None,
1476 worktree,
1477 path,
1478 disk_state: DiskState::Present {
1479 mtime: metadata.mtime,
1480 },
1481 is_local: true,
1482 is_private,
1483 })
1484 }
1485 };
1486
1487 Ok(LoadedBinaryFile { file, content })
1488 })
1489 }
1490
1491 fn load_file(&self, path: &Path, cx: &Context<Worktree>) -> Task<Result<LoadedFile>> {
1492 let path = Arc::from(path);
1493 let abs_path = self.absolutize(&path);
1494 let fs = self.fs.clone();
1495 let entry = self.refresh_entry(path.clone(), None, cx);
1496 let is_private = self.is_path_private(path.as_ref());
1497
1498 cx.spawn(async move |this, _cx| {
1499 let abs_path = abs_path?;
1500 // WARN: Temporary workaround for #27283.
1501 // We are not efficient with our memory usage per file, and use in excess of 64GB for a 10GB file
1502 // Therefore, as a temporary workaround to prevent system freezes, we just bail before opening a file
1503 // if it is too large
1504 // 5GB seems to be more reasonable, peaking at ~16GB, while 6GB jumps up to >24GB which seems like a
1505 // reasonable limit
1506 {
1507 const FILE_SIZE_MAX: u64 = 6 * 1024 * 1024 * 1024; // 6GB
1508 if let Ok(Some(metadata)) = fs.metadata(&abs_path).await {
1509 if metadata.len >= FILE_SIZE_MAX {
1510 anyhow::bail!("File is too large to load");
1511 }
1512 }
1513 }
1514 let text = fs.load(&abs_path).await?;
1515
1516 let worktree = this
1517 .upgrade()
1518 .ok_or_else(|| anyhow!("worktree was dropped"))?;
1519 let file = match entry.await? {
1520 Some(entry) => File::for_entry(entry, worktree),
1521 None => {
1522 let metadata = fs
1523 .metadata(&abs_path)
1524 .await
1525 .with_context(|| {
1526 format!("Loading metadata for excluded file {abs_path:?}")
1527 })?
1528 .with_context(|| {
1529 format!("Excluded file {abs_path:?} got removed during loading")
1530 })?;
1531 Arc::new(File {
1532 entry_id: None,
1533 worktree,
1534 path,
1535 disk_state: DiskState::Present {
1536 mtime: metadata.mtime,
1537 },
1538 is_local: true,
1539 is_private,
1540 })
1541 }
1542 };
1543
1544 Ok(LoadedFile { file, text })
1545 })
1546 }
1547
1548 /// Find the lowest path in the worktree's datastructures that is an ancestor
1549 fn lowest_ancestor(&self, path: &Path) -> PathBuf {
1550 let mut lowest_ancestor = None;
1551 for path in path.ancestors() {
1552 if self.entry_for_path(path).is_some() {
1553 lowest_ancestor = Some(path.to_path_buf());
1554 break;
1555 }
1556 }
1557
1558 lowest_ancestor.unwrap_or_else(|| PathBuf::from(""))
1559 }
1560
1561 fn create_entry(
1562 &self,
1563 path: impl Into<Arc<Path>>,
1564 is_dir: bool,
1565 cx: &Context<Worktree>,
1566 ) -> Task<Result<CreatedEntry>> {
1567 let path = path.into();
1568 let abs_path = match self.absolutize(&path) {
1569 Ok(path) => path,
1570 Err(e) => return Task::ready(Err(e.context(format!("absolutizing path {path:?}")))),
1571 };
1572 let path_excluded = self.settings.is_path_excluded(&abs_path);
1573 let fs = self.fs.clone();
1574 let task_abs_path = abs_path.clone();
1575 let write = cx.background_spawn(async move {
1576 if is_dir {
1577 fs.create_dir(&task_abs_path)
1578 .await
1579 .with_context(|| format!("creating directory {task_abs_path:?}"))
1580 } else {
1581 fs.save(&task_abs_path, &Rope::default(), LineEnding::default())
1582 .await
1583 .with_context(|| format!("creating file {task_abs_path:?}"))
1584 }
1585 });
1586
1587 let lowest_ancestor = self.lowest_ancestor(&path);
1588 cx.spawn(async move |this, cx| {
1589 write.await?;
1590 if path_excluded {
1591 return Ok(CreatedEntry::Excluded { abs_path });
1592 }
1593
1594 let (result, refreshes) = this.update(cx, |this, cx| {
1595 let mut refreshes = Vec::new();
1596 let refresh_paths = path.strip_prefix(&lowest_ancestor).unwrap();
1597 for refresh_path in refresh_paths.ancestors() {
1598 if refresh_path == Path::new("") {
1599 continue;
1600 }
1601 let refresh_full_path = lowest_ancestor.join(refresh_path);
1602
1603 refreshes.push(this.as_local_mut().unwrap().refresh_entry(
1604 refresh_full_path.into(),
1605 None,
1606 cx,
1607 ));
1608 }
1609 (
1610 this.as_local_mut().unwrap().refresh_entry(path, None, cx),
1611 refreshes,
1612 )
1613 })?;
1614 for refresh in refreshes {
1615 refresh.await.log_err();
1616 }
1617
1618 Ok(result
1619 .await?
1620 .map(CreatedEntry::Included)
1621 .unwrap_or_else(|| CreatedEntry::Excluded { abs_path }))
1622 })
1623 }
1624
1625 fn write_file(
1626 &self,
1627 path: impl Into<Arc<Path>>,
1628 text: Rope,
1629 line_ending: LineEnding,
1630 cx: &Context<Worktree>,
1631 ) -> Task<Result<Arc<File>>> {
1632 let path = path.into();
1633 let fs = self.fs.clone();
1634 let is_private = self.is_path_private(&path);
1635 let Ok(abs_path) = self.absolutize(&path) else {
1636 return Task::ready(Err(anyhow!("invalid path {path:?}")));
1637 };
1638
1639 let write = cx.background_spawn({
1640 let fs = fs.clone();
1641 let abs_path = abs_path.clone();
1642 async move { fs.save(&abs_path, &text, line_ending).await }
1643 });
1644
1645 cx.spawn(async move |this, cx| {
1646 write.await?;
1647 let entry = this
1648 .update(cx, |this, cx| {
1649 this.as_local_mut()
1650 .unwrap()
1651 .refresh_entry(path.clone(), None, cx)
1652 })?
1653 .await?;
1654 let worktree = this.upgrade().ok_or_else(|| anyhow!("worktree dropped"))?;
1655 if let Some(entry) = entry {
1656 Ok(File::for_entry(entry, worktree))
1657 } else {
1658 let metadata = fs
1659 .metadata(&abs_path)
1660 .await
1661 .with_context(|| {
1662 format!("Fetching metadata after saving the excluded buffer {abs_path:?}")
1663 })?
1664 .with_context(|| {
1665 format!("Excluded buffer {path:?} got removed during saving")
1666 })?;
1667 Ok(Arc::new(File {
1668 worktree,
1669 path,
1670 disk_state: DiskState::Present {
1671 mtime: metadata.mtime,
1672 },
1673 entry_id: None,
1674 is_local: true,
1675 is_private,
1676 }))
1677 }
1678 })
1679 }
1680
1681 fn delete_entry(
1682 &self,
1683 entry_id: ProjectEntryId,
1684 trash: bool,
1685 cx: &Context<Worktree>,
1686 ) -> Option<Task<Result<()>>> {
1687 let entry = self.entry_for_id(entry_id)?.clone();
1688 let abs_path = self.absolutize(&entry.path);
1689 let fs = self.fs.clone();
1690
1691 let delete = cx.background_spawn(async move {
1692 if entry.is_file() {
1693 if trash {
1694 fs.trash_file(&abs_path?, Default::default()).await?;
1695 } else {
1696 fs.remove_file(&abs_path?, Default::default()).await?;
1697 }
1698 } else if trash {
1699 fs.trash_dir(
1700 &abs_path?,
1701 RemoveOptions {
1702 recursive: true,
1703 ignore_if_not_exists: false,
1704 },
1705 )
1706 .await?;
1707 } else {
1708 fs.remove_dir(
1709 &abs_path?,
1710 RemoveOptions {
1711 recursive: true,
1712 ignore_if_not_exists: false,
1713 },
1714 )
1715 .await?;
1716 }
1717 anyhow::Ok(entry.path)
1718 });
1719
1720 Some(cx.spawn(async move |this, cx| {
1721 let path = delete.await?;
1722 this.update(cx, |this, _| {
1723 this.as_local_mut()
1724 .unwrap()
1725 .refresh_entries_for_paths(vec![path])
1726 })?
1727 .recv()
1728 .await;
1729 Ok(())
1730 }))
1731 }
1732
1733 /// Rename an entry.
1734 ///
1735 /// `new_path` is the new relative path to the worktree root.
1736 /// If the root entry is renamed then `new_path` is the new root name instead.
1737 fn rename_entry(
1738 &self,
1739 entry_id: ProjectEntryId,
1740 new_path: impl Into<Arc<Path>>,
1741 cx: &Context<Worktree>,
1742 ) -> Task<Result<CreatedEntry>> {
1743 let old_path = match self.entry_for_id(entry_id) {
1744 Some(entry) => entry.path.clone(),
1745 None => return Task::ready(Err(anyhow!("no entry to rename for id {entry_id:?}"))),
1746 };
1747 let new_path = new_path.into();
1748 let abs_old_path = self.absolutize(&old_path);
1749
1750 let is_root_entry = self.root_entry().is_some_and(|e| e.id == entry_id);
1751 let abs_new_path = if is_root_entry {
1752 let Some(root_parent_path) = self.abs_path().parent() else {
1753 return Task::ready(Err(anyhow!("no parent for path {:?}", self.abs_path)));
1754 };
1755 root_parent_path.join(&new_path)
1756 } else {
1757 let Ok(absolutize_path) = self.absolutize(&new_path) else {
1758 return Task::ready(Err(anyhow!("absolutizing path {new_path:?}")));
1759 };
1760 absolutize_path
1761 };
1762 let abs_path = abs_new_path.clone();
1763 let fs = self.fs.clone();
1764 let case_sensitive = self.fs_case_sensitive;
1765 let rename = cx.background_spawn(async move {
1766 let abs_old_path = abs_old_path?;
1767 let abs_new_path = abs_new_path;
1768
1769 let abs_old_path_lower = abs_old_path.to_str().map(|p| p.to_lowercase());
1770 let abs_new_path_lower = abs_new_path.to_str().map(|p| p.to_lowercase());
1771
1772 // If we're on a case-insensitive FS and we're doing a case-only rename (i.e. `foobar` to `FOOBAR`)
1773 // we want to overwrite, because otherwise we run into a file-already-exists error.
1774 let overwrite = !case_sensitive
1775 && abs_old_path != abs_new_path
1776 && abs_old_path_lower == abs_new_path_lower;
1777
1778 fs.rename(
1779 &abs_old_path,
1780 &abs_new_path,
1781 fs::RenameOptions {
1782 overwrite,
1783 ..Default::default()
1784 },
1785 )
1786 .await
1787 .with_context(|| format!("Renaming {abs_old_path:?} into {abs_new_path:?}"))
1788 });
1789
1790 cx.spawn(async move |this, cx| {
1791 rename.await?;
1792 Ok(this
1793 .update(cx, |this, cx| {
1794 let local = this.as_local_mut().unwrap();
1795 if is_root_entry {
1796 // We eagerly update `abs_path` and refresh this worktree.
1797 // Otherwise, the FS watcher would do it on the `RootUpdated` event,
1798 // but with a noticeable delay, so we handle it proactively.
1799 local.update_abs_path_and_refresh(
1800 Some(SanitizedPath::from(abs_path.clone())),
1801 cx,
1802 );
1803 Task::ready(Ok(this.root_entry().cloned()))
1804 } else {
1805 local.refresh_entry(new_path.clone(), Some(old_path), cx)
1806 }
1807 })?
1808 .await?
1809 .map(CreatedEntry::Included)
1810 .unwrap_or_else(|| CreatedEntry::Excluded { abs_path }))
1811 })
1812 }
1813
1814 fn copy_entry(
1815 &self,
1816 entry_id: ProjectEntryId,
1817 relative_worktree_source_path: Option<PathBuf>,
1818 new_path: impl Into<Arc<Path>>,
1819 cx: &Context<Worktree>,
1820 ) -> Task<Result<Option<Entry>>> {
1821 let old_path = match self.entry_for_id(entry_id) {
1822 Some(entry) => entry.path.clone(),
1823 None => return Task::ready(Ok(None)),
1824 };
1825 let new_path = new_path.into();
1826 let abs_old_path =
1827 if let Some(relative_worktree_source_path) = relative_worktree_source_path {
1828 Ok(self.abs_path().join(relative_worktree_source_path))
1829 } else {
1830 self.absolutize(&old_path)
1831 };
1832 let abs_new_path = self.absolutize(&new_path);
1833 let fs = self.fs.clone();
1834 let copy = cx.background_spawn(async move {
1835 copy_recursive(
1836 fs.as_ref(),
1837 &abs_old_path?,
1838 &abs_new_path?,
1839 Default::default(),
1840 )
1841 .await
1842 });
1843
1844 cx.spawn(async move |this, cx| {
1845 copy.await?;
1846 this.update(cx, |this, cx| {
1847 this.as_local_mut()
1848 .unwrap()
1849 .refresh_entry(new_path.clone(), None, cx)
1850 })?
1851 .await
1852 })
1853 }
1854
1855 pub fn copy_external_entries(
1856 &self,
1857 target_directory: PathBuf,
1858 paths: Vec<Arc<Path>>,
1859 overwrite_existing_files: bool,
1860 cx: &Context<Worktree>,
1861 ) -> Task<Result<Vec<ProjectEntryId>>> {
1862 let worktree_path = self.abs_path().clone();
1863 let fs = self.fs.clone();
1864 let paths = paths
1865 .into_iter()
1866 .filter_map(|source| {
1867 let file_name = source.file_name()?;
1868 let mut target = target_directory.clone();
1869 target.push(file_name);
1870
1871 // Do not allow copying the same file to itself.
1872 if source.as_ref() != target.as_path() {
1873 Some((source, target))
1874 } else {
1875 None
1876 }
1877 })
1878 .collect::<Vec<_>>();
1879
1880 let paths_to_refresh = paths
1881 .iter()
1882 .filter_map(|(_, target)| Some(target.strip_prefix(&worktree_path).ok()?.into()))
1883 .collect::<Vec<_>>();
1884
1885 cx.spawn(async move |this, cx| {
1886 cx.background_spawn(async move {
1887 for (source, target) in paths {
1888 copy_recursive(
1889 fs.as_ref(),
1890 &source,
1891 &target,
1892 fs::CopyOptions {
1893 overwrite: overwrite_existing_files,
1894 ..Default::default()
1895 },
1896 )
1897 .await
1898 .with_context(|| {
1899 anyhow!("Failed to copy file from {source:?} to {target:?}")
1900 })?;
1901 }
1902 Ok::<(), anyhow::Error>(())
1903 })
1904 .await
1905 .log_err();
1906 let mut refresh = cx.read_entity(
1907 &this.upgrade().with_context(|| "Dropped worktree")?,
1908 |this, _| {
1909 Ok::<postage::barrier::Receiver, anyhow::Error>(
1910 this.as_local()
1911 .with_context(|| "Worktree is not local")?
1912 .refresh_entries_for_paths(paths_to_refresh.clone()),
1913 )
1914 },
1915 )??;
1916
1917 cx.background_spawn(async move {
1918 refresh.next().await;
1919 Ok::<(), anyhow::Error>(())
1920 })
1921 .await
1922 .log_err();
1923
1924 let this = this.upgrade().with_context(|| "Dropped worktree")?;
1925 cx.read_entity(&this, |this, _| {
1926 paths_to_refresh
1927 .iter()
1928 .filter_map(|path| Some(this.entry_for_path(path)?.id))
1929 .collect()
1930 })
1931 })
1932 }
1933
1934 fn expand_entry(
1935 &self,
1936 entry_id: ProjectEntryId,
1937 cx: &Context<Worktree>,
1938 ) -> Option<Task<Result<()>>> {
1939 let path = self.entry_for_id(entry_id)?.path.clone();
1940 let mut refresh = self.refresh_entries_for_paths(vec![path]);
1941 Some(cx.background_spawn(async move {
1942 refresh.next().await;
1943 Ok(())
1944 }))
1945 }
1946
1947 fn expand_all_for_entry(
1948 &self,
1949 entry_id: ProjectEntryId,
1950 cx: &Context<Worktree>,
1951 ) -> Option<Task<Result<()>>> {
1952 let path = self.entry_for_id(entry_id).unwrap().path.clone();
1953 let mut rx = self.add_path_prefix_to_scan(path.clone());
1954 Some(cx.background_spawn(async move {
1955 rx.next().await;
1956 Ok(())
1957 }))
1958 }
1959
1960 fn refresh_entries_for_paths(&self, paths: Vec<Arc<Path>>) -> barrier::Receiver {
1961 let (tx, rx) = barrier::channel();
1962 self.scan_requests_tx
1963 .try_send(ScanRequest {
1964 relative_paths: paths,
1965 done: smallvec![tx],
1966 })
1967 .ok();
1968 rx
1969 }
1970
1971 #[cfg(feature = "test-support")]
1972 pub fn manually_refresh_entries_for_paths(&self, paths: Vec<Arc<Path>>) -> barrier::Receiver {
1973 self.refresh_entries_for_paths(paths)
1974 }
1975
1976 pub fn add_path_prefix_to_scan(&self, path_prefix: Arc<Path>) -> barrier::Receiver {
1977 let (tx, rx) = barrier::channel();
1978 self.path_prefixes_to_scan_tx
1979 .try_send(PathPrefixScanRequest {
1980 path: path_prefix,
1981 done: smallvec![tx],
1982 })
1983 .ok();
1984 rx
1985 }
1986
1987 fn refresh_entry(
1988 &self,
1989 path: Arc<Path>,
1990 old_path: Option<Arc<Path>>,
1991 cx: &Context<Worktree>,
1992 ) -> Task<Result<Option<Entry>>> {
1993 if self.settings.is_path_excluded(&path) {
1994 return Task::ready(Ok(None));
1995 }
1996 let paths = if let Some(old_path) = old_path.as_ref() {
1997 vec![old_path.clone(), path.clone()]
1998 } else {
1999 vec![path.clone()]
2000 };
2001 let t0 = Instant::now();
2002 let mut refresh = self.refresh_entries_for_paths(paths);
2003 cx.spawn(async move |this, cx| {
2004 refresh.recv().await;
2005 log::trace!("refreshed entry {path:?} in {:?}", t0.elapsed());
2006 let new_entry = this.update(cx, |this, _| {
2007 this.entry_for_path(path)
2008 .cloned()
2009 .ok_or_else(|| anyhow!("failed to read path after update"))
2010 })??;
2011 Ok(Some(new_entry))
2012 })
2013 }
2014
2015 fn observe_updates<F, Fut>(&mut self, project_id: u64, cx: &Context<Worktree>, callback: F)
2016 where
2017 F: 'static + Send + Fn(proto::UpdateWorktree) -> Fut,
2018 Fut: 'static + Send + Future<Output = bool>,
2019 {
2020 if let Some(observer) = self.update_observer.as_mut() {
2021 *observer.resume_updates.borrow_mut() = ();
2022 return;
2023 }
2024
2025 let (resume_updates_tx, mut resume_updates_rx) = watch::channel::<()>();
2026 let (snapshots_tx, mut snapshots_rx) =
2027 mpsc::unbounded::<(LocalSnapshot, UpdatedEntriesSet)>();
2028 snapshots_tx
2029 .unbounded_send((self.snapshot(), Arc::default()))
2030 .ok();
2031
2032 let worktree_id = cx.entity_id().as_u64();
2033 let _maintain_remote_snapshot = cx.background_spawn(async move {
2034 let mut is_first = true;
2035 while let Some((snapshot, entry_changes)) = snapshots_rx.next().await {
2036 let update = if is_first {
2037 is_first = false;
2038 snapshot.build_initial_update(project_id, worktree_id)
2039 } else {
2040 snapshot.build_update(project_id, worktree_id, entry_changes)
2041 };
2042
2043 for update in proto::split_worktree_update(update) {
2044 let _ = resume_updates_rx.try_recv();
2045 loop {
2046 let result = callback(update.clone());
2047 if result.await {
2048 break;
2049 } else {
2050 log::info!("waiting to resume updates");
2051 if resume_updates_rx.next().await.is_none() {
2052 return Some(());
2053 }
2054 }
2055 }
2056 }
2057 }
2058 Some(())
2059 });
2060
2061 self.update_observer = Some(UpdateObservationState {
2062 snapshots_tx,
2063 resume_updates: resume_updates_tx,
2064 _maintain_remote_snapshot,
2065 });
2066 }
2067
2068 pub fn share_private_files(&mut self, cx: &Context<Worktree>) {
2069 self.share_private_files = true;
2070 self.restart_background_scanners(cx);
2071 }
2072
2073 fn update_abs_path_and_refresh(
2074 &mut self,
2075 new_path: Option<SanitizedPath>,
2076 cx: &Context<Worktree>,
2077 ) {
2078 if let Some(new_path) = new_path {
2079 self.snapshot.git_repositories = Default::default();
2080 self.snapshot.ignores_by_parent_abs_path = Default::default();
2081 let root_name = new_path
2082 .as_path()
2083 .file_name()
2084 .map_or(String::new(), |f| f.to_string_lossy().to_string());
2085 self.snapshot.update_abs_path(new_path, root_name);
2086 }
2087 self.restart_background_scanners(cx);
2088 }
2089}
2090
2091impl RemoteWorktree {
2092 pub fn project_id(&self) -> u64 {
2093 self.project_id
2094 }
2095
2096 pub fn client(&self) -> AnyProtoClient {
2097 self.client.clone()
2098 }
2099
2100 pub fn disconnected_from_host(&mut self) {
2101 self.updates_tx.take();
2102 self.snapshot_subscriptions.clear();
2103 self.disconnected = true;
2104 }
2105
2106 pub fn update_from_remote(&self, update: proto::UpdateWorktree) {
2107 if let Some(updates_tx) = &self.updates_tx {
2108 updates_tx
2109 .unbounded_send(update)
2110 .expect("consumer runs to completion");
2111 }
2112 }
2113
2114 fn observe_updates<F, Fut>(&mut self, project_id: u64, cx: &Context<Worktree>, callback: F)
2115 where
2116 F: 'static + Send + Fn(proto::UpdateWorktree) -> Fut,
2117 Fut: 'static + Send + Future<Output = bool>,
2118 {
2119 let (tx, mut rx) = mpsc::unbounded();
2120 let initial_update = self
2121 .snapshot
2122 .build_initial_update(project_id, self.id().to_proto());
2123 self.update_observer = Some(tx);
2124 cx.spawn(async move |this, cx| {
2125 let mut update = initial_update;
2126 'outer: loop {
2127 // SSH projects use a special project ID of 0, and we need to
2128 // remap it to the correct one here.
2129 update.project_id = project_id;
2130
2131 for chunk in split_worktree_update(update) {
2132 if !callback(chunk).await {
2133 break 'outer;
2134 }
2135 }
2136
2137 if let Some(next_update) = rx.next().await {
2138 update = next_update;
2139 } else {
2140 break;
2141 }
2142 }
2143 this.update(cx, |this, _| {
2144 let this = this.as_remote_mut().unwrap();
2145 this.update_observer.take();
2146 })
2147 })
2148 .detach();
2149 }
2150
2151 fn observed_snapshot(&self, scan_id: usize) -> bool {
2152 self.completed_scan_id >= scan_id
2153 }
2154
2155 pub fn wait_for_snapshot(
2156 &mut self,
2157 scan_id: usize,
2158 ) -> impl Future<Output = Result<()>> + use<> {
2159 let (tx, rx) = oneshot::channel();
2160 if self.observed_snapshot(scan_id) {
2161 let _ = tx.send(());
2162 } else if self.disconnected {
2163 drop(tx);
2164 } else {
2165 match self
2166 .snapshot_subscriptions
2167 .binary_search_by_key(&scan_id, |probe| probe.0)
2168 {
2169 Ok(ix) | Err(ix) => self.snapshot_subscriptions.insert(ix, (scan_id, tx)),
2170 }
2171 }
2172
2173 async move {
2174 rx.await?;
2175 Ok(())
2176 }
2177 }
2178
2179 fn insert_entry(
2180 &mut self,
2181 entry: proto::Entry,
2182 scan_id: usize,
2183 cx: &Context<Worktree>,
2184 ) -> Task<Result<Entry>> {
2185 let wait_for_snapshot = self.wait_for_snapshot(scan_id);
2186 cx.spawn(async move |this, cx| {
2187 wait_for_snapshot.await?;
2188 this.update(cx, |worktree, _| {
2189 let worktree = worktree.as_remote_mut().unwrap();
2190 let snapshot = &mut worktree.background_snapshot.lock().0;
2191 let entry = snapshot.insert_entry(entry, &worktree.file_scan_inclusions);
2192 worktree.snapshot = snapshot.clone();
2193 entry
2194 })?
2195 })
2196 }
2197
2198 fn delete_entry(
2199 &self,
2200 entry_id: ProjectEntryId,
2201 trash: bool,
2202 cx: &Context<Worktree>,
2203 ) -> Option<Task<Result<()>>> {
2204 let response = self.client.request(proto::DeleteProjectEntry {
2205 project_id: self.project_id,
2206 entry_id: entry_id.to_proto(),
2207 use_trash: trash,
2208 });
2209 Some(cx.spawn(async move |this, cx| {
2210 let response = response.await?;
2211 let scan_id = response.worktree_scan_id as usize;
2212
2213 this.update(cx, move |this, _| {
2214 this.as_remote_mut().unwrap().wait_for_snapshot(scan_id)
2215 })?
2216 .await?;
2217
2218 this.update(cx, |this, _| {
2219 let this = this.as_remote_mut().unwrap();
2220 let snapshot = &mut this.background_snapshot.lock().0;
2221 snapshot.delete_entry(entry_id);
2222 this.snapshot = snapshot.clone();
2223 })
2224 }))
2225 }
2226
2227 fn rename_entry(
2228 &self,
2229 entry_id: ProjectEntryId,
2230 new_path: impl Into<Arc<Path>>,
2231 cx: &Context<Worktree>,
2232 ) -> Task<Result<CreatedEntry>> {
2233 let new_path: Arc<Path> = new_path.into();
2234 let response = self.client.request(proto::RenameProjectEntry {
2235 project_id: self.project_id,
2236 entry_id: entry_id.to_proto(),
2237 new_path: new_path.as_ref().to_proto(),
2238 });
2239 cx.spawn(async move |this, cx| {
2240 let response = response.await?;
2241 match response.entry {
2242 Some(entry) => this
2243 .update(cx, |this, cx| {
2244 this.as_remote_mut().unwrap().insert_entry(
2245 entry,
2246 response.worktree_scan_id as usize,
2247 cx,
2248 )
2249 })?
2250 .await
2251 .map(CreatedEntry::Included),
2252 None => {
2253 let abs_path = this.update(cx, |worktree, _| {
2254 worktree
2255 .absolutize(&new_path)
2256 .with_context(|| format!("absolutizing {new_path:?}"))
2257 })??;
2258 Ok(CreatedEntry::Excluded { abs_path })
2259 }
2260 }
2261 })
2262 }
2263}
2264
2265impl Snapshot {
2266 pub fn new(id: u64, root_name: String, abs_path: Arc<Path>) -> Self {
2267 Snapshot {
2268 id: WorktreeId::from_usize(id as usize),
2269 abs_path: abs_path.into(),
2270 root_char_bag: root_name.chars().map(|c| c.to_ascii_lowercase()).collect(),
2271 root_name,
2272 always_included_entries: Default::default(),
2273 entries_by_path: Default::default(),
2274 entries_by_id: Default::default(),
2275 scan_id: 1,
2276 completed_scan_id: 0,
2277 }
2278 }
2279
2280 pub fn id(&self) -> WorktreeId {
2281 self.id
2282 }
2283
2284 // TODO:
2285 // Consider the following:
2286 //
2287 // ```rust
2288 // let abs_path: Arc<Path> = snapshot.abs_path(); // e.g. "C:\Users\user\Desktop\project"
2289 // let some_non_trimmed_path = Path::new("\\\\?\\C:\\Users\\user\\Desktop\\project\\main.rs");
2290 // // The caller perform some actions here:
2291 // some_non_trimmed_path.strip_prefix(abs_path); // This fails
2292 // some_non_trimmed_path.starts_with(abs_path); // This fails too
2293 // ```
2294 //
2295 // This is definitely a bug, but it's not clear if we should handle it here or not.
2296 pub fn abs_path(&self) -> &Arc<Path> {
2297 self.abs_path.as_path()
2298 }
2299
2300 fn build_initial_update(&self, project_id: u64, worktree_id: u64) -> proto::UpdateWorktree {
2301 let mut updated_entries = self
2302 .entries_by_path
2303 .iter()
2304 .map(proto::Entry::from)
2305 .collect::<Vec<_>>();
2306 updated_entries.sort_unstable_by_key(|e| e.id);
2307
2308 proto::UpdateWorktree {
2309 project_id,
2310 worktree_id,
2311 abs_path: self.abs_path().to_proto(),
2312 root_name: self.root_name().to_string(),
2313 updated_entries,
2314 removed_entries: Vec::new(),
2315 scan_id: self.scan_id as u64,
2316 is_last_update: self.completed_scan_id == self.scan_id,
2317 // Sent in separate messages.
2318 updated_repositories: Vec::new(),
2319 removed_repositories: Vec::new(),
2320 }
2321 }
2322
2323 pub fn work_directory_abs_path(&self, work_directory: &WorkDirectory) -> Result<PathBuf> {
2324 match work_directory {
2325 WorkDirectory::InProject { relative_path } => self.absolutize(relative_path),
2326 WorkDirectory::AboveProject { absolute_path, .. } => {
2327 Ok(absolute_path.as_ref().to_owned())
2328 }
2329 }
2330 }
2331
2332 pub fn absolutize(&self, path: &Path) -> Result<PathBuf> {
2333 if path
2334 .components()
2335 .any(|component| !matches!(component, std::path::Component::Normal(_)))
2336 {
2337 return Err(anyhow!("invalid path"));
2338 }
2339 if path.file_name().is_some() {
2340 Ok(self.abs_path.as_path().join(path))
2341 } else {
2342 Ok(self.abs_path.as_path().to_path_buf())
2343 }
2344 }
2345
2346 pub fn contains_entry(&self, entry_id: ProjectEntryId) -> bool {
2347 self.entries_by_id.get(&entry_id, &()).is_some()
2348 }
2349
2350 fn insert_entry(
2351 &mut self,
2352 entry: proto::Entry,
2353 always_included_paths: &PathMatcher,
2354 ) -> Result<Entry> {
2355 let entry = Entry::try_from((&self.root_char_bag, always_included_paths, entry))?;
2356 let old_entry = self.entries_by_id.insert_or_replace(
2357 PathEntry {
2358 id: entry.id,
2359 path: entry.path.clone(),
2360 is_ignored: entry.is_ignored,
2361 scan_id: 0,
2362 },
2363 &(),
2364 );
2365 if let Some(old_entry) = old_entry {
2366 self.entries_by_path.remove(&PathKey(old_entry.path), &());
2367 }
2368 self.entries_by_path.insert_or_replace(entry.clone(), &());
2369 Ok(entry)
2370 }
2371
2372 fn delete_entry(&mut self, entry_id: ProjectEntryId) -> Option<Arc<Path>> {
2373 let removed_entry = self.entries_by_id.remove(&entry_id, &())?;
2374 self.entries_by_path = {
2375 let mut cursor = self.entries_by_path.cursor::<TraversalProgress>(&());
2376 let mut new_entries_by_path =
2377 cursor.slice(&TraversalTarget::path(&removed_entry.path), Bias::Left, &());
2378 while let Some(entry) = cursor.item() {
2379 if entry.path.starts_with(&removed_entry.path) {
2380 self.entries_by_id.remove(&entry.id, &());
2381 cursor.next(&());
2382 } else {
2383 break;
2384 }
2385 }
2386 new_entries_by_path.append(cursor.suffix(&()), &());
2387 new_entries_by_path
2388 };
2389
2390 Some(removed_entry.path)
2391 }
2392
2393 fn update_abs_path(&mut self, abs_path: SanitizedPath, root_name: String) {
2394 self.abs_path = abs_path;
2395 if root_name != self.root_name {
2396 self.root_char_bag = root_name.chars().map(|c| c.to_ascii_lowercase()).collect();
2397 self.root_name = root_name;
2398 }
2399 }
2400
2401 fn apply_remote_update(
2402 &mut self,
2403 update: proto::UpdateWorktree,
2404 always_included_paths: &PathMatcher,
2405 ) -> Result<()> {
2406 log::debug!(
2407 "applying remote worktree update. {} entries updated, {} removed",
2408 update.updated_entries.len(),
2409 update.removed_entries.len()
2410 );
2411 self.update_abs_path(
2412 SanitizedPath::from(PathBuf::from_proto(update.abs_path)),
2413 update.root_name,
2414 );
2415
2416 let mut entries_by_path_edits = Vec::new();
2417 let mut entries_by_id_edits = Vec::new();
2418
2419 for entry_id in update.removed_entries {
2420 let entry_id = ProjectEntryId::from_proto(entry_id);
2421 entries_by_id_edits.push(Edit::Remove(entry_id));
2422 if let Some(entry) = self.entry_for_id(entry_id) {
2423 entries_by_path_edits.push(Edit::Remove(PathKey(entry.path.clone())));
2424 }
2425 }
2426
2427 for entry in update.updated_entries {
2428 let entry = Entry::try_from((&self.root_char_bag, always_included_paths, entry))?;
2429 if let Some(PathEntry { path, .. }) = self.entries_by_id.get(&entry.id, &()) {
2430 entries_by_path_edits.push(Edit::Remove(PathKey(path.clone())));
2431 }
2432 if let Some(old_entry) = self.entries_by_path.get(&PathKey(entry.path.clone()), &()) {
2433 if old_entry.id != entry.id {
2434 entries_by_id_edits.push(Edit::Remove(old_entry.id));
2435 }
2436 }
2437 entries_by_id_edits.push(Edit::Insert(PathEntry {
2438 id: entry.id,
2439 path: entry.path.clone(),
2440 is_ignored: entry.is_ignored,
2441 scan_id: 0,
2442 }));
2443 entries_by_path_edits.push(Edit::Insert(entry));
2444 }
2445
2446 self.entries_by_path.edit(entries_by_path_edits, &());
2447 self.entries_by_id.edit(entries_by_id_edits, &());
2448
2449 self.scan_id = update.scan_id as usize;
2450 if update.is_last_update {
2451 self.completed_scan_id = update.scan_id as usize;
2452 }
2453
2454 Ok(())
2455 }
2456
2457 pub fn entry_count(&self) -> usize {
2458 self.entries_by_path.summary().count
2459 }
2460
2461 pub fn visible_entry_count(&self) -> usize {
2462 self.entries_by_path.summary().non_ignored_count
2463 }
2464
2465 pub fn dir_count(&self) -> usize {
2466 let summary = self.entries_by_path.summary();
2467 summary.count - summary.file_count
2468 }
2469
2470 pub fn visible_dir_count(&self) -> usize {
2471 let summary = self.entries_by_path.summary();
2472 summary.non_ignored_count - summary.non_ignored_file_count
2473 }
2474
2475 pub fn file_count(&self) -> usize {
2476 self.entries_by_path.summary().file_count
2477 }
2478
2479 pub fn visible_file_count(&self) -> usize {
2480 self.entries_by_path.summary().non_ignored_file_count
2481 }
2482
2483 fn traverse_from_offset(
2484 &self,
2485 include_files: bool,
2486 include_dirs: bool,
2487 include_ignored: bool,
2488 start_offset: usize,
2489 ) -> Traversal {
2490 let mut cursor = self.entries_by_path.cursor(&());
2491 cursor.seek(
2492 &TraversalTarget::Count {
2493 count: start_offset,
2494 include_files,
2495 include_dirs,
2496 include_ignored,
2497 },
2498 Bias::Right,
2499 &(),
2500 );
2501 Traversal {
2502 snapshot: self,
2503 cursor,
2504 include_files,
2505 include_dirs,
2506 include_ignored,
2507 }
2508 }
2509
2510 pub fn traverse_from_path(
2511 &self,
2512 include_files: bool,
2513 include_dirs: bool,
2514 include_ignored: bool,
2515 path: &Path,
2516 ) -> Traversal {
2517 Traversal::new(self, include_files, include_dirs, include_ignored, path)
2518 }
2519
2520 pub fn files(&self, include_ignored: bool, start: usize) -> Traversal {
2521 self.traverse_from_offset(true, false, include_ignored, start)
2522 }
2523
2524 pub fn directories(&self, include_ignored: bool, start: usize) -> Traversal {
2525 self.traverse_from_offset(false, true, include_ignored, start)
2526 }
2527
2528 pub fn entries(&self, include_ignored: bool, start: usize) -> Traversal {
2529 self.traverse_from_offset(true, true, include_ignored, start)
2530 }
2531
2532 pub fn paths(&self) -> impl Iterator<Item = &Arc<Path>> {
2533 let empty_path = Path::new("");
2534 self.entries_by_path
2535 .cursor::<()>(&())
2536 .filter(move |entry| entry.path.as_ref() != empty_path)
2537 .map(|entry| &entry.path)
2538 }
2539
2540 pub fn child_entries<'a>(&'a self, parent_path: &'a Path) -> ChildEntriesIter<'a> {
2541 let options = ChildEntriesOptions {
2542 include_files: true,
2543 include_dirs: true,
2544 include_ignored: true,
2545 };
2546 self.child_entries_with_options(parent_path, options)
2547 }
2548
2549 pub fn child_entries_with_options<'a>(
2550 &'a self,
2551 parent_path: &'a Path,
2552 options: ChildEntriesOptions,
2553 ) -> ChildEntriesIter<'a> {
2554 let mut cursor = self.entries_by_path.cursor(&());
2555 cursor.seek(&TraversalTarget::path(parent_path), Bias::Right, &());
2556 let traversal = Traversal {
2557 snapshot: self,
2558 cursor,
2559 include_files: options.include_files,
2560 include_dirs: options.include_dirs,
2561 include_ignored: options.include_ignored,
2562 };
2563 ChildEntriesIter {
2564 traversal,
2565 parent_path,
2566 }
2567 }
2568
2569 pub fn root_entry(&self) -> Option<&Entry> {
2570 self.entry_for_path("")
2571 }
2572
2573 /// TODO: what's the difference between `root_dir` and `abs_path`?
2574 /// is there any? if so, document it.
2575 pub fn root_dir(&self) -> Option<Arc<Path>> {
2576 self.root_entry()
2577 .filter(|entry| entry.is_dir())
2578 .map(|_| self.abs_path().clone())
2579 }
2580
2581 pub fn root_name(&self) -> &str {
2582 &self.root_name
2583 }
2584
2585 pub fn scan_id(&self) -> usize {
2586 self.scan_id
2587 }
2588
2589 pub fn entry_for_path(&self, path: impl AsRef<Path>) -> Option<&Entry> {
2590 let path = path.as_ref();
2591 debug_assert!(path.is_relative());
2592 self.traverse_from_path(true, true, true, path)
2593 .entry()
2594 .and_then(|entry| {
2595 if entry.path.as_ref() == path {
2596 Some(entry)
2597 } else {
2598 None
2599 }
2600 })
2601 }
2602
2603 pub fn entry_for_id(&self, id: ProjectEntryId) -> Option<&Entry> {
2604 let entry = self.entries_by_id.get(&id, &())?;
2605 self.entry_for_path(&entry.path)
2606 }
2607
2608 pub fn inode_for_path(&self, path: impl AsRef<Path>) -> Option<u64> {
2609 self.entry_for_path(path.as_ref()).map(|e| e.inode)
2610 }
2611}
2612
2613impl LocalSnapshot {
2614 fn local_repo_for_work_directory_path(&self, path: &Path) -> Option<&LocalRepositoryEntry> {
2615 self.git_repositories
2616 .iter()
2617 .map(|(_, entry)| entry)
2618 .find(|entry| entry.work_directory.path_key() == PathKey(path.into()))
2619 }
2620
2621 fn build_update(
2622 &self,
2623 project_id: u64,
2624 worktree_id: u64,
2625 entry_changes: UpdatedEntriesSet,
2626 ) -> proto::UpdateWorktree {
2627 let mut updated_entries = Vec::new();
2628 let mut removed_entries = Vec::new();
2629
2630 for (_, entry_id, path_change) in entry_changes.iter() {
2631 if let PathChange::Removed = path_change {
2632 removed_entries.push(entry_id.0 as u64);
2633 } else if let Some(entry) = self.entry_for_id(*entry_id) {
2634 updated_entries.push(proto::Entry::from(entry));
2635 }
2636 }
2637
2638 removed_entries.sort_unstable();
2639 updated_entries.sort_unstable_by_key(|e| e.id);
2640
2641 // TODO - optimize, knowing that removed_entries are sorted.
2642 removed_entries.retain(|id| updated_entries.binary_search_by_key(id, |e| e.id).is_err());
2643
2644 proto::UpdateWorktree {
2645 project_id,
2646 worktree_id,
2647 abs_path: self.abs_path().to_proto(),
2648 root_name: self.root_name().to_string(),
2649 updated_entries,
2650 removed_entries,
2651 scan_id: self.scan_id as u64,
2652 is_last_update: self.completed_scan_id == self.scan_id,
2653 // Sent in separate messages.
2654 updated_repositories: Vec::new(),
2655 removed_repositories: Vec::new(),
2656 }
2657 }
2658
2659 fn insert_entry(&mut self, mut entry: Entry, fs: &dyn Fs) -> Entry {
2660 if entry.is_file() && entry.path.file_name() == Some(&GITIGNORE) {
2661 let abs_path = self.abs_path.as_path().join(&entry.path);
2662 match smol::block_on(build_gitignore(&abs_path, fs)) {
2663 Ok(ignore) => {
2664 self.ignores_by_parent_abs_path
2665 .insert(abs_path.parent().unwrap().into(), (Arc::new(ignore), true));
2666 }
2667 Err(error) => {
2668 log::error!(
2669 "error loading .gitignore file {:?} - {:?}",
2670 &entry.path,
2671 error
2672 );
2673 }
2674 }
2675 }
2676
2677 if entry.kind == EntryKind::PendingDir {
2678 if let Some(existing_entry) =
2679 self.entries_by_path.get(&PathKey(entry.path.clone()), &())
2680 {
2681 entry.kind = existing_entry.kind;
2682 }
2683 }
2684
2685 let scan_id = self.scan_id;
2686 let removed = self.entries_by_path.insert_or_replace(entry.clone(), &());
2687 if let Some(removed) = removed {
2688 if removed.id != entry.id {
2689 self.entries_by_id.remove(&removed.id, &());
2690 }
2691 }
2692 self.entries_by_id.insert_or_replace(
2693 PathEntry {
2694 id: entry.id,
2695 path: entry.path.clone(),
2696 is_ignored: entry.is_ignored,
2697 scan_id,
2698 },
2699 &(),
2700 );
2701
2702 entry
2703 }
2704
2705 fn ancestor_inodes_for_path(&self, path: &Path) -> TreeSet<u64> {
2706 let mut inodes = TreeSet::default();
2707 for ancestor in path.ancestors().skip(1) {
2708 if let Some(entry) = self.entry_for_path(ancestor) {
2709 inodes.insert(entry.inode);
2710 }
2711 }
2712 inodes
2713 }
2714
2715 fn ignore_stack_for_abs_path(&self, abs_path: &Path, is_dir: bool) -> Arc<IgnoreStack> {
2716 let mut new_ignores = Vec::new();
2717 for (index, ancestor) in abs_path.ancestors().enumerate() {
2718 if index > 0 {
2719 if let Some((ignore, _)) = self.ignores_by_parent_abs_path.get(ancestor) {
2720 new_ignores.push((ancestor, Some(ignore.clone())));
2721 } else {
2722 new_ignores.push((ancestor, None));
2723 }
2724 }
2725 if ancestor.join(*DOT_GIT).exists() {
2726 break;
2727 }
2728 }
2729
2730 let mut ignore_stack = IgnoreStack::none();
2731 for (parent_abs_path, ignore) in new_ignores.into_iter().rev() {
2732 if ignore_stack.is_abs_path_ignored(parent_abs_path, true) {
2733 ignore_stack = IgnoreStack::all();
2734 break;
2735 } else if let Some(ignore) = ignore {
2736 ignore_stack = ignore_stack.append(parent_abs_path.into(), ignore);
2737 }
2738 }
2739
2740 if ignore_stack.is_abs_path_ignored(abs_path, is_dir) {
2741 ignore_stack = IgnoreStack::all();
2742 }
2743
2744 ignore_stack
2745 }
2746
2747 #[cfg(test)]
2748 fn expanded_entries(&self) -> impl Iterator<Item = &Entry> {
2749 self.entries_by_path
2750 .cursor::<()>(&())
2751 .filter(|entry| entry.kind == EntryKind::Dir && (entry.is_external || entry.is_ignored))
2752 }
2753
2754 #[cfg(test)]
2755 pub fn check_invariants(&self, git_state: bool) {
2756 use pretty_assertions::assert_eq;
2757
2758 assert_eq!(
2759 self.entries_by_path
2760 .cursor::<()>(&())
2761 .map(|e| (&e.path, e.id))
2762 .collect::<Vec<_>>(),
2763 self.entries_by_id
2764 .cursor::<()>(&())
2765 .map(|e| (&e.path, e.id))
2766 .collect::<collections::BTreeSet<_>>()
2767 .into_iter()
2768 .collect::<Vec<_>>(),
2769 "entries_by_path and entries_by_id are inconsistent"
2770 );
2771
2772 let mut files = self.files(true, 0);
2773 let mut visible_files = self.files(false, 0);
2774 for entry in self.entries_by_path.cursor::<()>(&()) {
2775 if entry.is_file() {
2776 assert_eq!(files.next().unwrap().inode, entry.inode);
2777 if (!entry.is_ignored && !entry.is_external) || entry.is_always_included {
2778 assert_eq!(visible_files.next().unwrap().inode, entry.inode);
2779 }
2780 }
2781 }
2782
2783 assert!(files.next().is_none());
2784 assert!(visible_files.next().is_none());
2785
2786 let mut bfs_paths = Vec::new();
2787 let mut stack = self
2788 .root_entry()
2789 .map(|e| e.path.as_ref())
2790 .into_iter()
2791 .collect::<Vec<_>>();
2792 while let Some(path) = stack.pop() {
2793 bfs_paths.push(path);
2794 let ix = stack.len();
2795 for child_entry in self.child_entries(path) {
2796 stack.insert(ix, &child_entry.path);
2797 }
2798 }
2799
2800 let dfs_paths_via_iter = self
2801 .entries_by_path
2802 .cursor::<()>(&())
2803 .map(|e| e.path.as_ref())
2804 .collect::<Vec<_>>();
2805 assert_eq!(bfs_paths, dfs_paths_via_iter);
2806
2807 let dfs_paths_via_traversal = self
2808 .entries(true, 0)
2809 .map(|e| e.path.as_ref())
2810 .collect::<Vec<_>>();
2811 assert_eq!(dfs_paths_via_traversal, dfs_paths_via_iter);
2812
2813 if git_state {
2814 for ignore_parent_abs_path in self.ignores_by_parent_abs_path.keys() {
2815 let ignore_parent_path = ignore_parent_abs_path
2816 .strip_prefix(self.abs_path.as_path())
2817 .unwrap();
2818 assert!(self.entry_for_path(ignore_parent_path).is_some());
2819 assert!(
2820 self.entry_for_path(ignore_parent_path.join(*GITIGNORE))
2821 .is_some()
2822 );
2823 }
2824 }
2825 }
2826
2827 #[cfg(test)]
2828 pub fn entries_without_ids(&self, include_ignored: bool) -> Vec<(&Path, u64, bool)> {
2829 let mut paths = Vec::new();
2830 for entry in self.entries_by_path.cursor::<()>(&()) {
2831 if include_ignored || !entry.is_ignored {
2832 paths.push((entry.path.as_ref(), entry.inode, entry.is_ignored));
2833 }
2834 }
2835 paths.sort_by(|a, b| a.0.cmp(b.0));
2836 paths
2837 }
2838}
2839
2840impl BackgroundScannerState {
2841 fn should_scan_directory(&self, entry: &Entry) -> bool {
2842 (!entry.is_external && (!entry.is_ignored || entry.is_always_included))
2843 || entry.path.file_name() == Some(*DOT_GIT)
2844 || entry.path.file_name() == Some(local_settings_folder_relative_path().as_os_str())
2845 || self.scanned_dirs.contains(&entry.id) // If we've ever scanned it, keep scanning
2846 || self
2847 .paths_to_scan
2848 .iter()
2849 .any(|p| p.starts_with(&entry.path))
2850 || self
2851 .path_prefixes_to_scan
2852 .iter()
2853 .any(|p| entry.path.starts_with(p))
2854 }
2855
2856 fn enqueue_scan_dir(&self, abs_path: Arc<Path>, entry: &Entry, scan_job_tx: &Sender<ScanJob>) {
2857 let path = entry.path.clone();
2858 let ignore_stack = self.snapshot.ignore_stack_for_abs_path(&abs_path, true);
2859 let mut ancestor_inodes = self.snapshot.ancestor_inodes_for_path(&path);
2860
2861 if !ancestor_inodes.contains(&entry.inode) {
2862 ancestor_inodes.insert(entry.inode);
2863 scan_job_tx
2864 .try_send(ScanJob {
2865 abs_path,
2866 path,
2867 ignore_stack,
2868 scan_queue: scan_job_tx.clone(),
2869 ancestor_inodes,
2870 is_external: entry.is_external,
2871 })
2872 .unwrap();
2873 }
2874 }
2875
2876 fn reuse_entry_id(&mut self, entry: &mut Entry) {
2877 if let Some(mtime) = entry.mtime {
2878 // If an entry with the same inode was removed from the worktree during this scan,
2879 // then it *might* represent the same file or directory. But the OS might also have
2880 // re-used the inode for a completely different file or directory.
2881 //
2882 // Conditionally reuse the old entry's id:
2883 // * if the mtime is the same, the file was probably been renamed.
2884 // * if the path is the same, the file may just have been updated
2885 if let Some(removed_entry) = self.removed_entries.remove(&entry.inode) {
2886 if removed_entry.mtime == Some(mtime) || removed_entry.path == entry.path {
2887 entry.id = removed_entry.id;
2888 }
2889 } else if let Some(existing_entry) = self.snapshot.entry_for_path(&entry.path) {
2890 entry.id = existing_entry.id;
2891 }
2892 }
2893 }
2894
2895 fn insert_entry(&mut self, mut entry: Entry, fs: &dyn Fs, watcher: &dyn Watcher) -> Entry {
2896 self.reuse_entry_id(&mut entry);
2897 let entry = self.snapshot.insert_entry(entry, fs);
2898 if entry.path.file_name() == Some(&DOT_GIT) {
2899 self.insert_git_repository(entry.path.clone(), fs, watcher);
2900 }
2901
2902 #[cfg(test)]
2903 self.snapshot.check_invariants(false);
2904
2905 entry
2906 }
2907
2908 fn populate_dir(
2909 &mut self,
2910 parent_path: &Arc<Path>,
2911 entries: impl IntoIterator<Item = Entry>,
2912 ignore: Option<Arc<Gitignore>>,
2913 ) {
2914 let mut parent_entry = if let Some(parent_entry) = self
2915 .snapshot
2916 .entries_by_path
2917 .get(&PathKey(parent_path.clone()), &())
2918 {
2919 parent_entry.clone()
2920 } else {
2921 log::warn!(
2922 "populating a directory {:?} that has been removed",
2923 parent_path
2924 );
2925 return;
2926 };
2927
2928 match parent_entry.kind {
2929 EntryKind::PendingDir | EntryKind::UnloadedDir => parent_entry.kind = EntryKind::Dir,
2930 EntryKind::Dir => {}
2931 _ => return,
2932 }
2933
2934 if let Some(ignore) = ignore {
2935 let abs_parent_path = self.snapshot.abs_path.as_path().join(parent_path).into();
2936 self.snapshot
2937 .ignores_by_parent_abs_path
2938 .insert(abs_parent_path, (ignore, false));
2939 }
2940
2941 let parent_entry_id = parent_entry.id;
2942 self.scanned_dirs.insert(parent_entry_id);
2943 let mut entries_by_path_edits = vec![Edit::Insert(parent_entry)];
2944 let mut entries_by_id_edits = Vec::new();
2945
2946 for entry in entries {
2947 entries_by_id_edits.push(Edit::Insert(PathEntry {
2948 id: entry.id,
2949 path: entry.path.clone(),
2950 is_ignored: entry.is_ignored,
2951 scan_id: self.snapshot.scan_id,
2952 }));
2953 entries_by_path_edits.push(Edit::Insert(entry));
2954 }
2955
2956 self.snapshot
2957 .entries_by_path
2958 .edit(entries_by_path_edits, &());
2959 self.snapshot.entries_by_id.edit(entries_by_id_edits, &());
2960
2961 if let Err(ix) = self.changed_paths.binary_search(parent_path) {
2962 self.changed_paths.insert(ix, parent_path.clone());
2963 }
2964
2965 #[cfg(test)]
2966 self.snapshot.check_invariants(false);
2967 }
2968
2969 fn remove_path(&mut self, path: &Path) {
2970 log::trace!("background scanner removing path {path:?}");
2971 let mut new_entries;
2972 let removed_entries;
2973 {
2974 let mut cursor = self
2975 .snapshot
2976 .entries_by_path
2977 .cursor::<TraversalProgress>(&());
2978 new_entries = cursor.slice(&TraversalTarget::path(path), Bias::Left, &());
2979 removed_entries = cursor.slice(&TraversalTarget::successor(path), Bias::Left, &());
2980 new_entries.append(cursor.suffix(&()), &());
2981 }
2982 self.snapshot.entries_by_path = new_entries;
2983
2984 let mut removed_ids = Vec::with_capacity(removed_entries.summary().count);
2985 for entry in removed_entries.cursor::<()>(&()) {
2986 match self.removed_entries.entry(entry.inode) {
2987 hash_map::Entry::Occupied(mut e) => {
2988 let prev_removed_entry = e.get_mut();
2989 if entry.id > prev_removed_entry.id {
2990 *prev_removed_entry = entry.clone();
2991 }
2992 }
2993 hash_map::Entry::Vacant(e) => {
2994 e.insert(entry.clone());
2995 }
2996 }
2997
2998 if entry.path.file_name() == Some(&GITIGNORE) {
2999 let abs_parent_path = self
3000 .snapshot
3001 .abs_path
3002 .as_path()
3003 .join(entry.path.parent().unwrap());
3004 if let Some((_, needs_update)) = self
3005 .snapshot
3006 .ignores_by_parent_abs_path
3007 .get_mut(abs_parent_path.as_path())
3008 {
3009 *needs_update = true;
3010 }
3011 }
3012
3013 if let Err(ix) = removed_ids.binary_search(&entry.id) {
3014 removed_ids.insert(ix, entry.id);
3015 }
3016 }
3017
3018 self.snapshot.entries_by_id.edit(
3019 removed_ids.iter().map(|&id| Edit::Remove(id)).collect(),
3020 &(),
3021 );
3022 self.snapshot
3023 .git_repositories
3024 .retain(|id, _| removed_ids.binary_search(id).is_err());
3025
3026 #[cfg(test)]
3027 self.snapshot.check_invariants(false);
3028 }
3029
3030 fn insert_git_repository(
3031 &mut self,
3032 dot_git_path: Arc<Path>,
3033 fs: &dyn Fs,
3034 watcher: &dyn Watcher,
3035 ) {
3036 let work_dir_path: Arc<Path> = match dot_git_path.parent() {
3037 Some(parent_dir) => {
3038 // Guard against repositories inside the repository metadata
3039 if parent_dir.iter().any(|component| component == *DOT_GIT) {
3040 log::debug!(
3041 "not building git repository for nested `.git` directory, `.git` path in the worktree: {dot_git_path:?}"
3042 );
3043 return;
3044 };
3045 log::debug!(
3046 "building git repository, `.git` path in the worktree: {dot_git_path:?}"
3047 );
3048
3049 parent_dir.into()
3050 }
3051 None => {
3052 // `dot_git_path.parent().is_none()` means `.git` directory is the opened worktree itself,
3053 // no files inside that directory are tracked by git, so no need to build the repo around it
3054 log::debug!(
3055 "not building git repository for the worktree itself, `.git` path in the worktree: {dot_git_path:?}"
3056 );
3057 return;
3058 }
3059 };
3060
3061 self.insert_git_repository_for_path(
3062 WorkDirectory::InProject {
3063 relative_path: work_dir_path,
3064 },
3065 dot_git_path,
3066 fs,
3067 watcher,
3068 );
3069 }
3070
3071 fn insert_git_repository_for_path(
3072 &mut self,
3073 work_directory: WorkDirectory,
3074 dot_git_path: Arc<Path>,
3075 fs: &dyn Fs,
3076 watcher: &dyn Watcher,
3077 ) -> Option<LocalRepositoryEntry> {
3078 log::trace!("insert git repository for {dot_git_path:?}");
3079 let work_dir_entry = self.snapshot.entry_for_path(work_directory.path_key().0)?;
3080 let work_directory_abs_path = self
3081 .snapshot
3082 .work_directory_abs_path(&work_directory)
3083 .log_err()?;
3084
3085 if self
3086 .snapshot
3087 .git_repositories
3088 .get(&work_dir_entry.id)
3089 .is_some()
3090 {
3091 log::trace!("existing git repository for {work_directory:?}");
3092 return None;
3093 }
3094
3095 let dot_git_abs_path = self.snapshot.abs_path.as_path().join(&dot_git_path);
3096
3097 // TODO add these watchers without building a whole repository by parsing .git-with-indirection
3098 let t0 = Instant::now();
3099 let repository = fs.open_repo(&dot_git_abs_path)?;
3100 log::trace!("opened git repo for {dot_git_abs_path:?}");
3101
3102 let repository_path = repository.path();
3103 watcher.add(&repository_path).log_err()?;
3104
3105 let actual_dot_git_dir_abs_path = repository.main_repository_path();
3106 let dot_git_worktree_abs_path = if actual_dot_git_dir_abs_path == dot_git_abs_path {
3107 None
3108 } else {
3109 // The two paths could be different because we opened a git worktree.
3110 // When that happens:
3111 //
3112 // * `dot_git_abs_path` is a file that points to the worktree-subdirectory in the actual
3113 // .git directory.
3114 //
3115 // * `repository_path` is the worktree-subdirectory.
3116 //
3117 // * `actual_dot_git_dir_abs_path` is the path to the actual .git directory. In git
3118 // documentation this is called the "commondir".
3119 watcher.add(&dot_git_abs_path).log_err()?;
3120 Some(Arc::from(dot_git_abs_path.as_path()))
3121 };
3122
3123 log::trace!("constructed libgit2 repo in {:?}", t0.elapsed());
3124
3125 let work_directory_id = work_dir_entry.id;
3126
3127 let local_repository = LocalRepositoryEntry {
3128 work_directory_id,
3129 work_directory,
3130 git_dir_scan_id: 0,
3131 original_dot_git_abs_path: dot_git_abs_path.as_path().into(),
3132 dot_git_dir_abs_path: actual_dot_git_dir_abs_path.into(),
3133 work_directory_abs_path: work_directory_abs_path.as_path().into(),
3134 dot_git_worktree_abs_path,
3135 };
3136
3137 self.snapshot
3138 .git_repositories
3139 .insert(work_directory_id, local_repository.clone());
3140
3141 log::trace!("inserting new local git repository");
3142 Some(local_repository)
3143 }
3144}
3145
3146async fn is_git_dir(path: &Path, fs: &dyn Fs) -> bool {
3147 if path.file_name() == Some(&*DOT_GIT) {
3148 return true;
3149 }
3150
3151 // If we're in a bare repository, we are not inside a `.git` folder. In a
3152 // bare repository, the root folder contains what would normally be in the
3153 // `.git` folder.
3154 let head_metadata = fs.metadata(&path.join("HEAD")).await;
3155 if !matches!(head_metadata, Ok(Some(_))) {
3156 return false;
3157 }
3158 let config_metadata = fs.metadata(&path.join("config")).await;
3159 matches!(config_metadata, Ok(Some(_)))
3160}
3161
3162async fn build_gitignore(abs_path: &Path, fs: &dyn Fs) -> Result<Gitignore> {
3163 let contents = fs.load(abs_path).await?;
3164 let parent = abs_path.parent().unwrap_or_else(|| Path::new("/"));
3165 let mut builder = GitignoreBuilder::new(parent);
3166 for line in contents.lines() {
3167 builder.add_line(Some(abs_path.into()), line)?;
3168 }
3169 Ok(builder.build()?)
3170}
3171
3172impl Deref for Worktree {
3173 type Target = Snapshot;
3174
3175 fn deref(&self) -> &Self::Target {
3176 match self {
3177 Worktree::Local(worktree) => &worktree.snapshot,
3178 Worktree::Remote(worktree) => &worktree.snapshot,
3179 }
3180 }
3181}
3182
3183impl Deref for LocalWorktree {
3184 type Target = LocalSnapshot;
3185
3186 fn deref(&self) -> &Self::Target {
3187 &self.snapshot
3188 }
3189}
3190
3191impl Deref for RemoteWorktree {
3192 type Target = Snapshot;
3193
3194 fn deref(&self) -> &Self::Target {
3195 &self.snapshot
3196 }
3197}
3198
3199impl fmt::Debug for LocalWorktree {
3200 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3201 self.snapshot.fmt(f)
3202 }
3203}
3204
3205impl fmt::Debug for Snapshot {
3206 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3207 struct EntriesById<'a>(&'a SumTree<PathEntry>);
3208 struct EntriesByPath<'a>(&'a SumTree<Entry>);
3209
3210 impl fmt::Debug for EntriesByPath<'_> {
3211 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3212 f.debug_map()
3213 .entries(self.0.iter().map(|entry| (&entry.path, entry.id)))
3214 .finish()
3215 }
3216 }
3217
3218 impl fmt::Debug for EntriesById<'_> {
3219 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3220 f.debug_list().entries(self.0.iter()).finish()
3221 }
3222 }
3223
3224 f.debug_struct("Snapshot")
3225 .field("id", &self.id)
3226 .field("root_name", &self.root_name)
3227 .field("entries_by_path", &EntriesByPath(&self.entries_by_path))
3228 .field("entries_by_id", &EntriesById(&self.entries_by_id))
3229 .finish()
3230 }
3231}
3232
3233#[derive(Clone, PartialEq)]
3234pub struct File {
3235 pub worktree: Entity<Worktree>,
3236 pub path: Arc<Path>,
3237 pub disk_state: DiskState,
3238 pub entry_id: Option<ProjectEntryId>,
3239 pub is_local: bool,
3240 pub is_private: bool,
3241}
3242
3243impl language::File for File {
3244 fn as_local(&self) -> Option<&dyn language::LocalFile> {
3245 if self.is_local { Some(self) } else { None }
3246 }
3247
3248 fn disk_state(&self) -> DiskState {
3249 self.disk_state
3250 }
3251
3252 fn path(&self) -> &Arc<Path> {
3253 &self.path
3254 }
3255
3256 fn full_path(&self, cx: &App) -> PathBuf {
3257 self.worktree.read(cx).full_path(&self.path)
3258 }
3259
3260 /// Returns the last component of this handle's absolute path. If this handle refers to the root
3261 /// of its worktree, then this method will return the name of the worktree itself.
3262 fn file_name<'a>(&'a self, cx: &'a App) -> &'a OsStr {
3263 self.path
3264 .file_name()
3265 .unwrap_or_else(|| OsStr::new(&self.worktree.read(cx).root_name))
3266 }
3267
3268 fn worktree_id(&self, cx: &App) -> WorktreeId {
3269 self.worktree.read(cx).id()
3270 }
3271
3272 fn to_proto(&self, cx: &App) -> rpc::proto::File {
3273 rpc::proto::File {
3274 worktree_id: self.worktree.read(cx).id().to_proto(),
3275 entry_id: self.entry_id.map(|id| id.to_proto()),
3276 path: self.path.as_ref().to_proto(),
3277 mtime: self.disk_state.mtime().map(|time| time.into()),
3278 is_deleted: self.disk_state == DiskState::Deleted,
3279 }
3280 }
3281
3282 fn is_private(&self) -> bool {
3283 self.is_private
3284 }
3285}
3286
3287impl language::LocalFile for File {
3288 fn abs_path(&self, cx: &App) -> PathBuf {
3289 let worktree_path = &self.worktree.read(cx).abs_path();
3290 if self.path.as_ref() == Path::new("") {
3291 worktree_path.to_path_buf()
3292 } else {
3293 worktree_path.join(&self.path)
3294 }
3295 }
3296
3297 fn load(&self, cx: &App) -> Task<Result<String>> {
3298 let worktree = self.worktree.read(cx).as_local().unwrap();
3299 let abs_path = worktree.absolutize(&self.path);
3300 let fs = worktree.fs.clone();
3301 cx.background_spawn(async move { fs.load(&abs_path?).await })
3302 }
3303
3304 fn load_bytes(&self, cx: &App) -> Task<Result<Vec<u8>>> {
3305 let worktree = self.worktree.read(cx).as_local().unwrap();
3306 let abs_path = worktree.absolutize(&self.path);
3307 let fs = worktree.fs.clone();
3308 cx.background_spawn(async move { fs.load_bytes(&abs_path?).await })
3309 }
3310}
3311
3312impl File {
3313 pub fn for_entry(entry: Entry, worktree: Entity<Worktree>) -> Arc<Self> {
3314 Arc::new(Self {
3315 worktree,
3316 path: entry.path.clone(),
3317 disk_state: if let Some(mtime) = entry.mtime {
3318 DiskState::Present { mtime }
3319 } else {
3320 DiskState::New
3321 },
3322 entry_id: Some(entry.id),
3323 is_local: true,
3324 is_private: entry.is_private,
3325 })
3326 }
3327
3328 pub fn from_proto(
3329 proto: rpc::proto::File,
3330 worktree: Entity<Worktree>,
3331 cx: &App,
3332 ) -> Result<Self> {
3333 let worktree_id = worktree
3334 .read(cx)
3335 .as_remote()
3336 .ok_or_else(|| anyhow!("not remote"))?
3337 .id();
3338
3339 if worktree_id.to_proto() != proto.worktree_id {
3340 return Err(anyhow!("worktree id does not match file"));
3341 }
3342
3343 let disk_state = if proto.is_deleted {
3344 DiskState::Deleted
3345 } else {
3346 if let Some(mtime) = proto.mtime.map(&Into::into) {
3347 DiskState::Present { mtime }
3348 } else {
3349 DiskState::New
3350 }
3351 };
3352
3353 Ok(Self {
3354 worktree,
3355 path: Arc::<Path>::from_proto(proto.path),
3356 disk_state,
3357 entry_id: proto.entry_id.map(ProjectEntryId::from_proto),
3358 is_local: false,
3359 is_private: false,
3360 })
3361 }
3362
3363 pub fn from_dyn(file: Option<&Arc<dyn language::File>>) -> Option<&Self> {
3364 file.and_then(|f| {
3365 let f: &dyn language::File = f.borrow();
3366 let f: &dyn Any = f;
3367 f.downcast_ref()
3368 })
3369 }
3370
3371 pub fn worktree_id(&self, cx: &App) -> WorktreeId {
3372 self.worktree.read(cx).id()
3373 }
3374
3375 pub fn project_entry_id(&self, _: &App) -> Option<ProjectEntryId> {
3376 match self.disk_state {
3377 DiskState::Deleted => None,
3378 _ => self.entry_id,
3379 }
3380 }
3381}
3382
3383#[derive(Clone, Debug, PartialEq, Eq)]
3384pub struct Entry {
3385 pub id: ProjectEntryId,
3386 pub kind: EntryKind,
3387 pub path: Arc<Path>,
3388 pub inode: u64,
3389 pub mtime: Option<MTime>,
3390
3391 pub canonical_path: Option<Arc<Path>>,
3392 /// Whether this entry is ignored by Git.
3393 ///
3394 /// We only scan ignored entries once the directory is expanded and
3395 /// exclude them from searches.
3396 pub is_ignored: bool,
3397
3398 /// Whether this entry is always included in searches.
3399 ///
3400 /// This is used for entries that are always included in searches, even
3401 /// if they are ignored by git. Overridden by file_scan_exclusions.
3402 pub is_always_included: bool,
3403
3404 /// Whether this entry's canonical path is outside of the worktree.
3405 /// This means the entry is only accessible from the worktree root via a
3406 /// symlink.
3407 ///
3408 /// We only scan entries outside of the worktree once the symlinked
3409 /// directory is expanded. External entries are treated like gitignored
3410 /// entries in that they are not included in searches.
3411 pub is_external: bool,
3412
3413 /// Whether this entry is considered to be a `.env` file.
3414 pub is_private: bool,
3415 /// The entry's size on disk, in bytes.
3416 pub size: u64,
3417 pub char_bag: CharBag,
3418 pub is_fifo: bool,
3419}
3420
3421#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3422pub enum EntryKind {
3423 UnloadedDir,
3424 PendingDir,
3425 Dir,
3426 File,
3427}
3428
3429#[derive(Clone, Copy, Debug, PartialEq)]
3430pub enum PathChange {
3431 /// A filesystem entry was was created.
3432 Added,
3433 /// A filesystem entry was removed.
3434 Removed,
3435 /// A filesystem entry was updated.
3436 Updated,
3437 /// A filesystem entry was either updated or added. We don't know
3438 /// whether or not it already existed, because the path had not
3439 /// been loaded before the event.
3440 AddedOrUpdated,
3441 /// A filesystem entry was found during the initial scan of the worktree.
3442 Loaded,
3443}
3444
3445#[derive(Clone, Debug, PartialEq, Eq)]
3446pub struct UpdatedGitRepository {
3447 /// ID of the repository's working directory.
3448 ///
3449 /// For a repo that's above the worktree root, this is the ID of the worktree root, and hence not unique.
3450 /// It's included here to aid the GitStore in detecting when a repository's working directory is renamed.
3451 pub work_directory_id: ProjectEntryId,
3452 pub old_work_directory_abs_path: Option<Arc<Path>>,
3453 pub new_work_directory_abs_path: Option<Arc<Path>>,
3454 /// For a normal git repository checkout, the absolute path to the .git directory.
3455 /// For a worktree, the absolute path to the worktree's subdirectory inside the .git directory.
3456 pub dot_git_abs_path: Option<Arc<Path>>,
3457}
3458
3459pub type UpdatedEntriesSet = Arc<[(Arc<Path>, ProjectEntryId, PathChange)]>;
3460pub type UpdatedGitRepositoriesSet = Arc<[UpdatedGitRepository]>;
3461
3462#[derive(Clone, Debug)]
3463pub struct PathProgress<'a> {
3464 pub max_path: &'a Path,
3465}
3466
3467#[derive(Clone, Debug)]
3468pub struct PathSummary<S> {
3469 pub max_path: Arc<Path>,
3470 pub item_summary: S,
3471}
3472
3473impl<S: Summary> Summary for PathSummary<S> {
3474 type Context = S::Context;
3475
3476 fn zero(cx: &Self::Context) -> Self {
3477 Self {
3478 max_path: Path::new("").into(),
3479 item_summary: S::zero(cx),
3480 }
3481 }
3482
3483 fn add_summary(&mut self, rhs: &Self, cx: &Self::Context) {
3484 self.max_path = rhs.max_path.clone();
3485 self.item_summary.add_summary(&rhs.item_summary, cx);
3486 }
3487}
3488
3489impl<'a, S: Summary> sum_tree::Dimension<'a, PathSummary<S>> for PathProgress<'a> {
3490 fn zero(_: &<PathSummary<S> as Summary>::Context) -> Self {
3491 Self {
3492 max_path: Path::new(""),
3493 }
3494 }
3495
3496 fn add_summary(
3497 &mut self,
3498 summary: &'a PathSummary<S>,
3499 _: &<PathSummary<S> as Summary>::Context,
3500 ) {
3501 self.max_path = summary.max_path.as_ref()
3502 }
3503}
3504
3505impl<'a> sum_tree::Dimension<'a, PathSummary<GitSummary>> for GitSummary {
3506 fn zero(_cx: &()) -> Self {
3507 Default::default()
3508 }
3509
3510 fn add_summary(&mut self, summary: &'a PathSummary<GitSummary>, _: &()) {
3511 *self += summary.item_summary
3512 }
3513}
3514
3515impl<'a> sum_tree::SeekTarget<'a, PathSummary<GitSummary>, (TraversalProgress<'a>, GitSummary)>
3516 for PathTarget<'_>
3517{
3518 fn cmp(&self, cursor_location: &(TraversalProgress<'a>, GitSummary), _: &()) -> Ordering {
3519 self.cmp_path(&cursor_location.0.max_path)
3520 }
3521}
3522
3523impl<'a, S: Summary> sum_tree::Dimension<'a, PathSummary<S>> for PathKey {
3524 fn zero(_: &S::Context) -> Self {
3525 Default::default()
3526 }
3527
3528 fn add_summary(&mut self, summary: &'a PathSummary<S>, _: &S::Context) {
3529 self.0 = summary.max_path.clone();
3530 }
3531}
3532
3533impl<'a, S: Summary> sum_tree::Dimension<'a, PathSummary<S>> for TraversalProgress<'a> {
3534 fn zero(_cx: &S::Context) -> Self {
3535 Default::default()
3536 }
3537
3538 fn add_summary(&mut self, summary: &'a PathSummary<S>, _: &S::Context) {
3539 self.max_path = summary.max_path.as_ref();
3540 }
3541}
3542
3543impl Entry {
3544 fn new(
3545 path: Arc<Path>,
3546 metadata: &fs::Metadata,
3547 next_entry_id: &AtomicUsize,
3548 root_char_bag: CharBag,
3549 canonical_path: Option<Arc<Path>>,
3550 ) -> Self {
3551 let char_bag = char_bag_for_path(root_char_bag, &path);
3552 Self {
3553 id: ProjectEntryId::new(next_entry_id),
3554 kind: if metadata.is_dir {
3555 EntryKind::PendingDir
3556 } else {
3557 EntryKind::File
3558 },
3559 path,
3560 inode: metadata.inode,
3561 mtime: Some(metadata.mtime),
3562 size: metadata.len,
3563 canonical_path,
3564 is_ignored: false,
3565 is_always_included: false,
3566 is_external: false,
3567 is_private: false,
3568 char_bag,
3569 is_fifo: metadata.is_fifo,
3570 }
3571 }
3572
3573 pub fn is_created(&self) -> bool {
3574 self.mtime.is_some()
3575 }
3576
3577 pub fn is_dir(&self) -> bool {
3578 self.kind.is_dir()
3579 }
3580
3581 pub fn is_file(&self) -> bool {
3582 self.kind.is_file()
3583 }
3584}
3585
3586impl EntryKind {
3587 pub fn is_dir(&self) -> bool {
3588 matches!(
3589 self,
3590 EntryKind::Dir | EntryKind::PendingDir | EntryKind::UnloadedDir
3591 )
3592 }
3593
3594 pub fn is_unloaded(&self) -> bool {
3595 matches!(self, EntryKind::UnloadedDir)
3596 }
3597
3598 pub fn is_file(&self) -> bool {
3599 matches!(self, EntryKind::File)
3600 }
3601}
3602
3603impl sum_tree::Item for Entry {
3604 type Summary = EntrySummary;
3605
3606 fn summary(&self, _cx: &()) -> Self::Summary {
3607 let non_ignored_count = if (self.is_ignored || self.is_external) && !self.is_always_included
3608 {
3609 0
3610 } else {
3611 1
3612 };
3613 let file_count;
3614 let non_ignored_file_count;
3615 if self.is_file() {
3616 file_count = 1;
3617 non_ignored_file_count = non_ignored_count;
3618 } else {
3619 file_count = 0;
3620 non_ignored_file_count = 0;
3621 }
3622
3623 EntrySummary {
3624 max_path: self.path.clone(),
3625 count: 1,
3626 non_ignored_count,
3627 file_count,
3628 non_ignored_file_count,
3629 }
3630 }
3631}
3632
3633impl sum_tree::KeyedItem for Entry {
3634 type Key = PathKey;
3635
3636 fn key(&self) -> Self::Key {
3637 PathKey(self.path.clone())
3638 }
3639}
3640
3641#[derive(Clone, Debug)]
3642pub struct EntrySummary {
3643 max_path: Arc<Path>,
3644 count: usize,
3645 non_ignored_count: usize,
3646 file_count: usize,
3647 non_ignored_file_count: usize,
3648}
3649
3650impl Default for EntrySummary {
3651 fn default() -> Self {
3652 Self {
3653 max_path: Arc::from(Path::new("")),
3654 count: 0,
3655 non_ignored_count: 0,
3656 file_count: 0,
3657 non_ignored_file_count: 0,
3658 }
3659 }
3660}
3661
3662impl sum_tree::Summary for EntrySummary {
3663 type Context = ();
3664
3665 fn zero(_cx: &()) -> Self {
3666 Default::default()
3667 }
3668
3669 fn add_summary(&mut self, rhs: &Self, _: &()) {
3670 self.max_path = rhs.max_path.clone();
3671 self.count += rhs.count;
3672 self.non_ignored_count += rhs.non_ignored_count;
3673 self.file_count += rhs.file_count;
3674 self.non_ignored_file_count += rhs.non_ignored_file_count;
3675 }
3676}
3677
3678#[derive(Clone, Debug)]
3679struct PathEntry {
3680 id: ProjectEntryId,
3681 path: Arc<Path>,
3682 is_ignored: bool,
3683 scan_id: usize,
3684}
3685
3686impl sum_tree::Item for PathEntry {
3687 type Summary = PathEntrySummary;
3688
3689 fn summary(&self, _cx: &()) -> Self::Summary {
3690 PathEntrySummary { max_id: self.id }
3691 }
3692}
3693
3694impl sum_tree::KeyedItem for PathEntry {
3695 type Key = ProjectEntryId;
3696
3697 fn key(&self) -> Self::Key {
3698 self.id
3699 }
3700}
3701
3702#[derive(Clone, Debug, Default)]
3703struct PathEntrySummary {
3704 max_id: ProjectEntryId,
3705}
3706
3707impl sum_tree::Summary for PathEntrySummary {
3708 type Context = ();
3709
3710 fn zero(_cx: &Self::Context) -> Self {
3711 Default::default()
3712 }
3713
3714 fn add_summary(&mut self, summary: &Self, _: &Self::Context) {
3715 self.max_id = summary.max_id;
3716 }
3717}
3718
3719impl<'a> sum_tree::Dimension<'a, PathEntrySummary> for ProjectEntryId {
3720 fn zero(_cx: &()) -> Self {
3721 Default::default()
3722 }
3723
3724 fn add_summary(&mut self, summary: &'a PathEntrySummary, _: &()) {
3725 *self = summary.max_id;
3726 }
3727}
3728
3729#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
3730pub struct PathKey(pub Arc<Path>);
3731
3732impl Default for PathKey {
3733 fn default() -> Self {
3734 Self(Path::new("").into())
3735 }
3736}
3737
3738impl<'a> sum_tree::Dimension<'a, EntrySummary> for PathKey {
3739 fn zero(_cx: &()) -> Self {
3740 Default::default()
3741 }
3742
3743 fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
3744 self.0 = summary.max_path.clone();
3745 }
3746}
3747
3748struct BackgroundScanner {
3749 state: Mutex<BackgroundScannerState>,
3750 fs: Arc<dyn Fs>,
3751 fs_case_sensitive: bool,
3752 status_updates_tx: UnboundedSender<ScanState>,
3753 executor: BackgroundExecutor,
3754 scan_requests_rx: channel::Receiver<ScanRequest>,
3755 path_prefixes_to_scan_rx: channel::Receiver<PathPrefixScanRequest>,
3756 next_entry_id: Arc<AtomicUsize>,
3757 phase: BackgroundScannerPhase,
3758 watcher: Arc<dyn Watcher>,
3759 settings: WorktreeSettings,
3760 share_private_files: bool,
3761}
3762
3763#[derive(Copy, Clone, PartialEq)]
3764enum BackgroundScannerPhase {
3765 InitialScan,
3766 EventsReceivedDuringInitialScan,
3767 Events,
3768}
3769
3770impl BackgroundScanner {
3771 async fn run(&mut self, mut fs_events_rx: Pin<Box<dyn Send + Stream<Item = Vec<PathEvent>>>>) {
3772 // If the worktree root does not contain a git repository, then find
3773 // the git repository in an ancestor directory. Find any gitignore files
3774 // in ancestor directories.
3775 let root_abs_path = self.state.lock().snapshot.abs_path.clone();
3776 let (ignores, repo) = discover_ancestor_git_repo(self.fs.clone(), &root_abs_path).await;
3777 self.state
3778 .lock()
3779 .snapshot
3780 .ignores_by_parent_abs_path
3781 .extend(ignores);
3782 let containing_git_repository = repo.and_then(|(ancestor_dot_git, work_directory)| {
3783 self.state.lock().insert_git_repository_for_path(
3784 work_directory,
3785 ancestor_dot_git.as_path().into(),
3786 self.fs.as_ref(),
3787 self.watcher.as_ref(),
3788 )?;
3789 Some(ancestor_dot_git)
3790 });
3791
3792 log::info!("containing git repository: {containing_git_repository:?}");
3793
3794 let (scan_job_tx, scan_job_rx) = channel::unbounded();
3795 {
3796 let mut state = self.state.lock();
3797 state.snapshot.scan_id += 1;
3798 if let Some(mut root_entry) = state.snapshot.root_entry().cloned() {
3799 let ignore_stack = state
3800 .snapshot
3801 .ignore_stack_for_abs_path(root_abs_path.as_path(), true);
3802 if ignore_stack.is_abs_path_ignored(root_abs_path.as_path(), true) {
3803 root_entry.is_ignored = true;
3804 state.insert_entry(root_entry.clone(), self.fs.as_ref(), self.watcher.as_ref());
3805 }
3806 state.enqueue_scan_dir(root_abs_path.into(), &root_entry, &scan_job_tx);
3807 }
3808 };
3809
3810 // Perform an initial scan of the directory.
3811 drop(scan_job_tx);
3812 self.scan_dirs(true, scan_job_rx).await;
3813 {
3814 let mut state = self.state.lock();
3815 state.snapshot.completed_scan_id = state.snapshot.scan_id;
3816 }
3817
3818 self.send_status_update(false, SmallVec::new());
3819
3820 // Process any any FS events that occurred while performing the initial scan.
3821 // For these events, update events cannot be as precise, because we didn't
3822 // have the previous state loaded yet.
3823 self.phase = BackgroundScannerPhase::EventsReceivedDuringInitialScan;
3824 if let Poll::Ready(Some(mut paths)) = futures::poll!(fs_events_rx.next()) {
3825 while let Poll::Ready(Some(more_paths)) = futures::poll!(fs_events_rx.next()) {
3826 paths.extend(more_paths);
3827 }
3828 self.process_events(paths.into_iter().map(Into::into).collect())
3829 .await;
3830 }
3831 if let Some(abs_path) = containing_git_repository {
3832 self.process_events(vec![abs_path]).await;
3833 }
3834
3835 // Continue processing events until the worktree is dropped.
3836 self.phase = BackgroundScannerPhase::Events;
3837
3838 loop {
3839 select_biased! {
3840 // Process any path refresh requests from the worktree. Prioritize
3841 // these before handling changes reported by the filesystem.
3842 request = self.next_scan_request().fuse() => {
3843 let Ok(request) = request else { break };
3844 if !self.process_scan_request(request, false).await {
3845 return;
3846 }
3847 }
3848
3849 path_prefix_request = self.path_prefixes_to_scan_rx.recv().fuse() => {
3850 let Ok(request) = path_prefix_request else { break };
3851 log::trace!("adding path prefix {:?}", request.path);
3852
3853 let did_scan = self.forcibly_load_paths(&[request.path.clone()]).await;
3854 if did_scan {
3855 let abs_path =
3856 {
3857 let mut state = self.state.lock();
3858 state.path_prefixes_to_scan.insert(request.path.clone());
3859 state.snapshot.abs_path.as_path().join(&request.path)
3860 };
3861
3862 if let Some(abs_path) = self.fs.canonicalize(&abs_path).await.log_err() {
3863 self.process_events(vec![abs_path]).await;
3864 }
3865 }
3866 self.send_status_update(false, request.done);
3867 }
3868
3869 paths = fs_events_rx.next().fuse() => {
3870 let Some(mut paths) = paths else { break };
3871 while let Poll::Ready(Some(more_paths)) = futures::poll!(fs_events_rx.next()) {
3872 paths.extend(more_paths);
3873 }
3874 self.process_events(paths.into_iter().map(Into::into).collect()).await;
3875 }
3876 }
3877 }
3878 }
3879
3880 async fn process_scan_request(&self, mut request: ScanRequest, scanning: bool) -> bool {
3881 log::debug!("rescanning paths {:?}", request.relative_paths);
3882
3883 request.relative_paths.sort_unstable();
3884 self.forcibly_load_paths(&request.relative_paths).await;
3885
3886 let root_path = self.state.lock().snapshot.abs_path.clone();
3887 let root_canonical_path = match self.fs.canonicalize(root_path.as_path()).await {
3888 Ok(path) => SanitizedPath::from(path),
3889 Err(err) => {
3890 log::error!("failed to canonicalize root path: {}", err);
3891 return true;
3892 }
3893 };
3894 let abs_paths = request
3895 .relative_paths
3896 .iter()
3897 .map(|path| {
3898 if path.file_name().is_some() {
3899 root_canonical_path.as_path().join(path).to_path_buf()
3900 } else {
3901 root_canonical_path.as_path().to_path_buf()
3902 }
3903 })
3904 .collect::<Vec<_>>();
3905
3906 {
3907 let mut state = self.state.lock();
3908 let is_idle = state.snapshot.completed_scan_id == state.snapshot.scan_id;
3909 state.snapshot.scan_id += 1;
3910 if is_idle {
3911 state.snapshot.completed_scan_id = state.snapshot.scan_id;
3912 }
3913 }
3914
3915 self.reload_entries_for_paths(
3916 root_path,
3917 root_canonical_path,
3918 &request.relative_paths,
3919 abs_paths,
3920 None,
3921 )
3922 .await;
3923
3924 self.send_status_update(scanning, request.done)
3925 }
3926
3927 async fn process_events(&self, mut abs_paths: Vec<PathBuf>) {
3928 let root_path = self.state.lock().snapshot.abs_path.clone();
3929 let root_canonical_path = match self.fs.canonicalize(root_path.as_path()).await {
3930 Ok(path) => SanitizedPath::from(path),
3931 Err(err) => {
3932 let new_path = self
3933 .state
3934 .lock()
3935 .snapshot
3936 .root_file_handle
3937 .clone()
3938 .and_then(|handle| handle.current_path(&self.fs).log_err())
3939 .map(SanitizedPath::from)
3940 .filter(|new_path| *new_path != root_path);
3941
3942 if let Some(new_path) = new_path.as_ref() {
3943 log::info!(
3944 "root renamed from {} to {}",
3945 root_path.as_path().display(),
3946 new_path.as_path().display()
3947 )
3948 } else {
3949 log::warn!("root path could not be canonicalized: {}", err);
3950 }
3951 self.status_updates_tx
3952 .unbounded_send(ScanState::RootUpdated { new_path })
3953 .ok();
3954 return;
3955 }
3956 };
3957
3958 // Certain directories may have FS changes, but do not lead to git data changes that Zed cares about.
3959 // Ignore these, to avoid Zed unnecessarily rescanning git metadata.
3960 let skipped_files_in_dot_git = HashSet::from_iter([*COMMIT_MESSAGE, *INDEX_LOCK]);
3961 let skipped_dirs_in_dot_git = [*FSMONITOR_DAEMON, *LFS_DIR];
3962
3963 let mut relative_paths = Vec::with_capacity(abs_paths.len());
3964 let mut dot_git_abs_paths = Vec::new();
3965 abs_paths.sort_unstable();
3966 abs_paths.dedup_by(|a, b| a.starts_with(b));
3967 abs_paths.retain(|abs_path| {
3968 let abs_path = SanitizedPath::from(abs_path);
3969
3970 let snapshot = &self.state.lock().snapshot;
3971 {
3972 let mut is_git_related = false;
3973
3974 let dot_git_paths = abs_path.as_path().ancestors().find_map(|ancestor| {
3975 if smol::block_on(is_git_dir(ancestor, self.fs.as_ref())) {
3976 let path_in_git_dir = abs_path.as_path().strip_prefix(ancestor).expect("stripping off the ancestor");
3977 Some((ancestor.to_owned(), path_in_git_dir.to_owned()))
3978 } else {
3979 None
3980 }
3981 });
3982
3983 if let Some((dot_git_abs_path, path_in_git_dir)) = dot_git_paths {
3984 if skipped_files_in_dot_git.contains(path_in_git_dir.as_os_str()) || skipped_dirs_in_dot_git.iter().any(|skipped_git_subdir| path_in_git_dir.starts_with(skipped_git_subdir)) {
3985 log::debug!("ignoring event {abs_path:?} as it's in the .git directory among skipped files or directories");
3986 return false;
3987 }
3988
3989 is_git_related = true;
3990 if !dot_git_abs_paths.contains(&dot_git_abs_path) {
3991 dot_git_abs_paths.push(dot_git_abs_path);
3992 }
3993 }
3994
3995 let relative_path: Arc<Path> =
3996 if let Ok(path) = abs_path.strip_prefix(&root_canonical_path) {
3997 path.into()
3998 } else {
3999 if is_git_related {
4000 log::debug!(
4001 "ignoring event {abs_path:?}, since it's in git dir outside of root path {root_canonical_path:?}",
4002 );
4003 } else {
4004 log::error!(
4005 "ignoring event {abs_path:?} outside of root path {root_canonical_path:?}",
4006 );
4007 }
4008 return false;
4009 };
4010
4011 if abs_path.0.file_name() == Some(*GITIGNORE) {
4012 for (_, repo) in snapshot.git_repositories.iter().filter(|(_, repo)| repo.directory_contains(&relative_path)) {
4013 if !dot_git_abs_paths.iter().any(|dot_git_abs_path| dot_git_abs_path == repo.dot_git_dir_abs_path.as_ref()) {
4014 dot_git_abs_paths.push(repo.dot_git_dir_abs_path.to_path_buf());
4015 }
4016 }
4017 }
4018
4019 let parent_dir_is_loaded = relative_path.parent().map_or(true, |parent| {
4020 snapshot
4021 .entry_for_path(parent)
4022 .map_or(false, |entry| entry.kind == EntryKind::Dir)
4023 });
4024 if !parent_dir_is_loaded {
4025 log::debug!("ignoring event {relative_path:?} within unloaded directory");
4026 return false;
4027 }
4028
4029 if self.settings.is_path_excluded(&relative_path) {
4030 if !is_git_related {
4031 log::debug!("ignoring FS event for excluded path {relative_path:?}");
4032 }
4033 return false;
4034 }
4035
4036 relative_paths.push(relative_path);
4037 true
4038 }
4039 });
4040
4041 if relative_paths.is_empty() && dot_git_abs_paths.is_empty() {
4042 return;
4043 }
4044
4045 self.state.lock().snapshot.scan_id += 1;
4046
4047 let (scan_job_tx, scan_job_rx) = channel::unbounded();
4048 log::debug!("received fs events {:?}", relative_paths);
4049 self.reload_entries_for_paths(
4050 root_path,
4051 root_canonical_path,
4052 &relative_paths,
4053 abs_paths,
4054 Some(scan_job_tx.clone()),
4055 )
4056 .await;
4057
4058 self.update_ignore_statuses(scan_job_tx).await;
4059 self.scan_dirs(false, scan_job_rx).await;
4060
4061 if !dot_git_abs_paths.is_empty() {
4062 self.update_git_repositories(dot_git_abs_paths);
4063 }
4064
4065 {
4066 let mut state = self.state.lock();
4067 state.snapshot.completed_scan_id = state.snapshot.scan_id;
4068 for (_, entry) in mem::take(&mut state.removed_entries) {
4069 state.scanned_dirs.remove(&entry.id);
4070 }
4071 }
4072 self.send_status_update(false, SmallVec::new());
4073 // send_status_update_inner(phase, state, status_update_tx, false, SmallVec::new());
4074 }
4075
4076 async fn forcibly_load_paths(&self, paths: &[Arc<Path>]) -> bool {
4077 let (scan_job_tx, scan_job_rx) = channel::unbounded();
4078 {
4079 let mut state = self.state.lock();
4080 let root_path = state.snapshot.abs_path.clone();
4081 for path in paths {
4082 for ancestor in path.ancestors() {
4083 if let Some(entry) = state.snapshot.entry_for_path(ancestor) {
4084 if entry.kind == EntryKind::UnloadedDir {
4085 let abs_path = root_path.as_path().join(ancestor);
4086 state.enqueue_scan_dir(abs_path.into(), entry, &scan_job_tx);
4087 state.paths_to_scan.insert(path.clone());
4088 break;
4089 }
4090 }
4091 }
4092 }
4093 drop(scan_job_tx);
4094 }
4095 while let Ok(job) = scan_job_rx.recv().await {
4096 self.scan_dir(&job).await.log_err();
4097 }
4098
4099 !mem::take(&mut self.state.lock().paths_to_scan).is_empty()
4100 }
4101
4102 async fn scan_dirs(
4103 &self,
4104 enable_progress_updates: bool,
4105 scan_jobs_rx: channel::Receiver<ScanJob>,
4106 ) {
4107 if self
4108 .status_updates_tx
4109 .unbounded_send(ScanState::Started)
4110 .is_err()
4111 {
4112 return;
4113 }
4114
4115 let progress_update_count = AtomicUsize::new(0);
4116 self.executor
4117 .scoped(|scope| {
4118 for _ in 0..self.executor.num_cpus() {
4119 scope.spawn(async {
4120 let mut last_progress_update_count = 0;
4121 let progress_update_timer = self.progress_timer(enable_progress_updates).fuse();
4122 futures::pin_mut!(progress_update_timer);
4123
4124 loop {
4125 select_biased! {
4126 // Process any path refresh requests before moving on to process
4127 // the scan queue, so that user operations are prioritized.
4128 request = self.next_scan_request().fuse() => {
4129 let Ok(request) = request else { break };
4130 if !self.process_scan_request(request, true).await {
4131 return;
4132 }
4133 }
4134
4135 // Send periodic progress updates to the worktree. Use an atomic counter
4136 // to ensure that only one of the workers sends a progress update after
4137 // the update interval elapses.
4138 _ = progress_update_timer => {
4139 match progress_update_count.compare_exchange(
4140 last_progress_update_count,
4141 last_progress_update_count + 1,
4142 SeqCst,
4143 SeqCst
4144 ) {
4145 Ok(_) => {
4146 last_progress_update_count += 1;
4147 self.send_status_update(true, SmallVec::new());
4148 }
4149 Err(count) => {
4150 last_progress_update_count = count;
4151 }
4152 }
4153 progress_update_timer.set(self.progress_timer(enable_progress_updates).fuse());
4154 }
4155
4156 // Recursively load directories from the file system.
4157 job = scan_jobs_rx.recv().fuse() => {
4158 let Ok(job) = job else { break };
4159 if let Err(err) = self.scan_dir(&job).await {
4160 if job.path.as_ref() != Path::new("") {
4161 log::error!("error scanning directory {:?}: {}", job.abs_path, err);
4162 }
4163 }
4164 }
4165 }
4166 }
4167 });
4168 }
4169 })
4170 .await;
4171 }
4172
4173 fn send_status_update(&self, scanning: bool, barrier: SmallVec<[barrier::Sender; 1]>) -> bool {
4174 let mut state = self.state.lock();
4175 if state.changed_paths.is_empty() && scanning {
4176 return true;
4177 }
4178
4179 let new_snapshot = state.snapshot.clone();
4180 let old_snapshot = mem::replace(&mut state.prev_snapshot, new_snapshot.snapshot.clone());
4181 let changes = build_diff(
4182 self.phase,
4183 &old_snapshot,
4184 &new_snapshot,
4185 &state.changed_paths,
4186 );
4187 state.changed_paths.clear();
4188
4189 self.status_updates_tx
4190 .unbounded_send(ScanState::Updated {
4191 snapshot: new_snapshot,
4192 changes,
4193 scanning,
4194 barrier,
4195 })
4196 .is_ok()
4197 }
4198
4199 async fn scan_dir(&self, job: &ScanJob) -> Result<()> {
4200 let root_abs_path;
4201 let root_char_bag;
4202 {
4203 let snapshot = &self.state.lock().snapshot;
4204 if self.settings.is_path_excluded(&job.path) {
4205 log::error!("skipping excluded directory {:?}", job.path);
4206 return Ok(());
4207 }
4208 log::trace!("scanning directory {:?}", job.path);
4209 root_abs_path = snapshot.abs_path().clone();
4210 root_char_bag = snapshot.root_char_bag;
4211 }
4212
4213 let next_entry_id = self.next_entry_id.clone();
4214 let mut ignore_stack = job.ignore_stack.clone();
4215 let mut new_ignore = None;
4216 let mut root_canonical_path = None;
4217 let mut new_entries: Vec<Entry> = Vec::new();
4218 let mut new_jobs: Vec<Option<ScanJob>> = Vec::new();
4219 let mut child_paths = self
4220 .fs
4221 .read_dir(&job.abs_path)
4222 .await?
4223 .filter_map(|entry| async {
4224 match entry {
4225 Ok(entry) => Some(entry),
4226 Err(error) => {
4227 log::error!("error processing entry {:?}", error);
4228 None
4229 }
4230 }
4231 })
4232 .collect::<Vec<_>>()
4233 .await;
4234
4235 // Ensure that .git and .gitignore are processed first.
4236 swap_to_front(&mut child_paths, *GITIGNORE);
4237 swap_to_front(&mut child_paths, *DOT_GIT);
4238
4239 for child_abs_path in child_paths {
4240 let child_abs_path: Arc<Path> = child_abs_path.into();
4241 let child_name = child_abs_path.file_name().unwrap();
4242 let child_path: Arc<Path> = job.path.join(child_name).into();
4243
4244 if child_name == *DOT_GIT {
4245 let mut state = self.state.lock();
4246 state.insert_git_repository(
4247 child_path.clone(),
4248 self.fs.as_ref(),
4249 self.watcher.as_ref(),
4250 );
4251 } else if child_name == *GITIGNORE {
4252 match build_gitignore(&child_abs_path, self.fs.as_ref()).await {
4253 Ok(ignore) => {
4254 let ignore = Arc::new(ignore);
4255 ignore_stack = ignore_stack.append(job.abs_path.clone(), ignore.clone());
4256 new_ignore = Some(ignore);
4257 }
4258 Err(error) => {
4259 log::error!(
4260 "error loading .gitignore file {:?} - {:?}",
4261 child_name,
4262 error
4263 );
4264 }
4265 }
4266 }
4267
4268 if self.settings.is_path_excluded(&child_path) {
4269 log::debug!("skipping excluded child entry {child_path:?}");
4270 self.state.lock().remove_path(&child_path);
4271 continue;
4272 }
4273
4274 let child_metadata = match self.fs.metadata(&child_abs_path).await {
4275 Ok(Some(metadata)) => metadata,
4276 Ok(None) => continue,
4277 Err(err) => {
4278 log::error!("error processing {child_abs_path:?}: {err:?}");
4279 continue;
4280 }
4281 };
4282
4283 let mut child_entry = Entry::new(
4284 child_path.clone(),
4285 &child_metadata,
4286 &next_entry_id,
4287 root_char_bag,
4288 None,
4289 );
4290
4291 if job.is_external {
4292 child_entry.is_external = true;
4293 } else if child_metadata.is_symlink {
4294 let canonical_path = match self.fs.canonicalize(&child_abs_path).await {
4295 Ok(path) => path,
4296 Err(err) => {
4297 log::error!(
4298 "error reading target of symlink {:?}: {:?}",
4299 child_abs_path,
4300 err
4301 );
4302 continue;
4303 }
4304 };
4305
4306 // lazily canonicalize the root path in order to determine if
4307 // symlinks point outside of the worktree.
4308 let root_canonical_path = match &root_canonical_path {
4309 Some(path) => path,
4310 None => match self.fs.canonicalize(&root_abs_path).await {
4311 Ok(path) => root_canonical_path.insert(path),
4312 Err(err) => {
4313 log::error!("error canonicalizing root {:?}: {:?}", root_abs_path, err);
4314 continue;
4315 }
4316 },
4317 };
4318
4319 if !canonical_path.starts_with(root_canonical_path) {
4320 child_entry.is_external = true;
4321 }
4322
4323 child_entry.canonical_path = Some(canonical_path.into());
4324 }
4325
4326 if child_entry.is_dir() {
4327 child_entry.is_ignored = ignore_stack.is_abs_path_ignored(&child_abs_path, true);
4328 child_entry.is_always_included = self.settings.is_path_always_included(&child_path);
4329
4330 // Avoid recursing until crash in the case of a recursive symlink
4331 if job.ancestor_inodes.contains(&child_entry.inode) {
4332 new_jobs.push(None);
4333 } else {
4334 let mut ancestor_inodes = job.ancestor_inodes.clone();
4335 ancestor_inodes.insert(child_entry.inode);
4336
4337 new_jobs.push(Some(ScanJob {
4338 abs_path: child_abs_path.clone(),
4339 path: child_path,
4340 is_external: child_entry.is_external,
4341 ignore_stack: if child_entry.is_ignored {
4342 IgnoreStack::all()
4343 } else {
4344 ignore_stack.clone()
4345 },
4346 ancestor_inodes,
4347 scan_queue: job.scan_queue.clone(),
4348 }));
4349 }
4350 } else {
4351 child_entry.is_ignored = ignore_stack.is_abs_path_ignored(&child_abs_path, false);
4352 child_entry.is_always_included = self.settings.is_path_always_included(&child_path);
4353 }
4354
4355 {
4356 let relative_path = job.path.join(child_name);
4357 if self.is_path_private(&relative_path) {
4358 log::debug!("detected private file: {relative_path:?}");
4359 child_entry.is_private = true;
4360 }
4361 }
4362
4363 new_entries.push(child_entry);
4364 }
4365
4366 let mut state = self.state.lock();
4367
4368 // Identify any subdirectories that should not be scanned.
4369 let mut job_ix = 0;
4370 for entry in &mut new_entries {
4371 state.reuse_entry_id(entry);
4372 if entry.is_dir() {
4373 if state.should_scan_directory(entry) {
4374 job_ix += 1;
4375 } else {
4376 log::debug!("defer scanning directory {:?}", entry.path);
4377 entry.kind = EntryKind::UnloadedDir;
4378 new_jobs.remove(job_ix);
4379 }
4380 }
4381 if entry.is_always_included {
4382 state
4383 .snapshot
4384 .always_included_entries
4385 .push(entry.path.clone());
4386 }
4387 }
4388
4389 state.populate_dir(&job.path, new_entries, new_ignore);
4390 self.watcher.add(job.abs_path.as_ref()).log_err();
4391
4392 for new_job in new_jobs.into_iter().flatten() {
4393 job.scan_queue
4394 .try_send(new_job)
4395 .expect("channel is unbounded");
4396 }
4397
4398 Ok(())
4399 }
4400
4401 /// All list arguments should be sorted before calling this function
4402 async fn reload_entries_for_paths(
4403 &self,
4404 root_abs_path: SanitizedPath,
4405 root_canonical_path: SanitizedPath,
4406 relative_paths: &[Arc<Path>],
4407 abs_paths: Vec<PathBuf>,
4408 scan_queue_tx: Option<Sender<ScanJob>>,
4409 ) {
4410 // grab metadata for all requested paths
4411 let metadata = futures::future::join_all(
4412 abs_paths
4413 .iter()
4414 .map(|abs_path| async move {
4415 let metadata = self.fs.metadata(abs_path).await?;
4416 if let Some(metadata) = metadata {
4417 let canonical_path = self.fs.canonicalize(abs_path).await?;
4418
4419 // If we're on a case-insensitive filesystem (default on macOS), we want
4420 // to only ignore metadata for non-symlink files if their absolute-path matches
4421 // the canonical-path.
4422 // Because if not, this might be a case-only-renaming (`mv test.txt TEST.TXT`)
4423 // and we want to ignore the metadata for the old path (`test.txt`) so it's
4424 // treated as removed.
4425 if !self.fs_case_sensitive && !metadata.is_symlink {
4426 let canonical_file_name = canonical_path.file_name();
4427 let file_name = abs_path.file_name();
4428 if canonical_file_name != file_name {
4429 return Ok(None);
4430 }
4431 }
4432
4433 anyhow::Ok(Some((metadata, SanitizedPath::from(canonical_path))))
4434 } else {
4435 Ok(None)
4436 }
4437 })
4438 .collect::<Vec<_>>(),
4439 )
4440 .await;
4441
4442 let mut new_ancestor_repo = if relative_paths
4443 .iter()
4444 .any(|path| path.as_ref() == Path::new(""))
4445 {
4446 Some(discover_ancestor_git_repo(self.fs.clone(), &root_abs_path).await)
4447 } else {
4448 None
4449 };
4450
4451 let mut state = self.state.lock();
4452 let doing_recursive_update = scan_queue_tx.is_some();
4453
4454 // Remove any entries for paths that no longer exist or are being recursively
4455 // refreshed. Do this before adding any new entries, so that renames can be
4456 // detected regardless of the order of the paths.
4457 for (path, metadata) in relative_paths.iter().zip(metadata.iter()) {
4458 if matches!(metadata, Ok(None)) || doing_recursive_update {
4459 log::trace!("remove path {:?}", path);
4460 state.remove_path(path);
4461 }
4462 }
4463
4464 for (path, metadata) in relative_paths.iter().zip(metadata.into_iter()) {
4465 let abs_path: Arc<Path> = root_abs_path.as_path().join(path).into();
4466 match metadata {
4467 Ok(Some((metadata, canonical_path))) => {
4468 let ignore_stack = state
4469 .snapshot
4470 .ignore_stack_for_abs_path(&abs_path, metadata.is_dir);
4471 let is_external = !canonical_path.starts_with(&root_canonical_path);
4472 let mut fs_entry = Entry::new(
4473 path.clone(),
4474 &metadata,
4475 self.next_entry_id.as_ref(),
4476 state.snapshot.root_char_bag,
4477 if metadata.is_symlink {
4478 Some(canonical_path.as_path().to_path_buf().into())
4479 } else {
4480 None
4481 },
4482 );
4483
4484 let is_dir = fs_entry.is_dir();
4485 fs_entry.is_ignored = ignore_stack.is_abs_path_ignored(&abs_path, is_dir);
4486 fs_entry.is_external = is_external;
4487 fs_entry.is_private = self.is_path_private(path);
4488 fs_entry.is_always_included = self.settings.is_path_always_included(path);
4489
4490 if let (Some(scan_queue_tx), true) = (&scan_queue_tx, is_dir) {
4491 if state.should_scan_directory(&fs_entry)
4492 || (fs_entry.path.as_os_str().is_empty()
4493 && abs_path.file_name() == Some(*DOT_GIT))
4494 {
4495 state.enqueue_scan_dir(abs_path, &fs_entry, scan_queue_tx);
4496 } else {
4497 fs_entry.kind = EntryKind::UnloadedDir;
4498 }
4499 }
4500
4501 state.insert_entry(fs_entry.clone(), self.fs.as_ref(), self.watcher.as_ref());
4502
4503 if path.as_ref() == Path::new("") {
4504 if let Some((ignores, repo)) = new_ancestor_repo.take() {
4505 log::trace!("updating ancestor git repository");
4506 state.snapshot.ignores_by_parent_abs_path.extend(ignores);
4507 if let Some((ancestor_dot_git, work_directory)) = repo {
4508 state.insert_git_repository_for_path(
4509 work_directory,
4510 ancestor_dot_git.as_path().into(),
4511 self.fs.as_ref(),
4512 self.watcher.as_ref(),
4513 );
4514 }
4515 }
4516 }
4517 }
4518 Ok(None) => {
4519 self.remove_repo_path(path, &mut state.snapshot);
4520 }
4521 Err(err) => {
4522 log::error!("error reading file {abs_path:?} on event: {err:#}");
4523 }
4524 }
4525 }
4526
4527 util::extend_sorted(
4528 &mut state.changed_paths,
4529 relative_paths.iter().cloned(),
4530 usize::MAX,
4531 Ord::cmp,
4532 );
4533 }
4534
4535 fn remove_repo_path(&self, path: &Arc<Path>, snapshot: &mut LocalSnapshot) -> Option<()> {
4536 if !path
4537 .components()
4538 .any(|component| component.as_os_str() == *DOT_GIT)
4539 {
4540 if let Some(local_repo) = snapshot.local_repo_for_work_directory_path(path) {
4541 let id = local_repo.work_directory_id;
4542 log::debug!("remove repo path: {:?}", path);
4543 snapshot.git_repositories.remove(&id);
4544 return Some(());
4545 }
4546 }
4547
4548 Some(())
4549 }
4550
4551 async fn update_ignore_statuses(&self, scan_job_tx: Sender<ScanJob>) {
4552 let mut ignores_to_update = Vec::new();
4553 let (ignore_queue_tx, ignore_queue_rx) = channel::unbounded();
4554 let prev_snapshot;
4555 {
4556 let snapshot = &mut self.state.lock().snapshot;
4557 let abs_path = snapshot.abs_path.clone();
4558 snapshot
4559 .ignores_by_parent_abs_path
4560 .retain(|parent_abs_path, (_, needs_update)| {
4561 if let Ok(parent_path) = parent_abs_path.strip_prefix(abs_path.as_path()) {
4562 if *needs_update {
4563 *needs_update = false;
4564 if snapshot.snapshot.entry_for_path(parent_path).is_some() {
4565 ignores_to_update.push(parent_abs_path.clone());
4566 }
4567 }
4568
4569 let ignore_path = parent_path.join(*GITIGNORE);
4570 if snapshot.snapshot.entry_for_path(ignore_path).is_none() {
4571 return false;
4572 }
4573 }
4574 true
4575 });
4576
4577 ignores_to_update.sort_unstable();
4578 let mut ignores_to_update = ignores_to_update.into_iter().peekable();
4579 while let Some(parent_abs_path) = ignores_to_update.next() {
4580 while ignores_to_update
4581 .peek()
4582 .map_or(false, |p| p.starts_with(&parent_abs_path))
4583 {
4584 ignores_to_update.next().unwrap();
4585 }
4586
4587 let ignore_stack = snapshot.ignore_stack_for_abs_path(&parent_abs_path, true);
4588 ignore_queue_tx
4589 .send_blocking(UpdateIgnoreStatusJob {
4590 abs_path: parent_abs_path,
4591 ignore_stack,
4592 ignore_queue: ignore_queue_tx.clone(),
4593 scan_queue: scan_job_tx.clone(),
4594 })
4595 .unwrap();
4596 }
4597
4598 prev_snapshot = snapshot.clone();
4599 }
4600 drop(ignore_queue_tx);
4601
4602 self.executor
4603 .scoped(|scope| {
4604 for _ in 0..self.executor.num_cpus() {
4605 scope.spawn(async {
4606 loop {
4607 select_biased! {
4608 // Process any path refresh requests before moving on to process
4609 // the queue of ignore statuses.
4610 request = self.next_scan_request().fuse() => {
4611 let Ok(request) = request else { break };
4612 if !self.process_scan_request(request, true).await {
4613 return;
4614 }
4615 }
4616
4617 // Recursively process directories whose ignores have changed.
4618 job = ignore_queue_rx.recv().fuse() => {
4619 let Ok(job) = job else { break };
4620 self.update_ignore_status(job, &prev_snapshot).await;
4621 }
4622 }
4623 }
4624 });
4625 }
4626 })
4627 .await;
4628 }
4629
4630 async fn update_ignore_status(&self, job: UpdateIgnoreStatusJob, snapshot: &LocalSnapshot) {
4631 log::trace!("update ignore status {:?}", job.abs_path);
4632
4633 let mut ignore_stack = job.ignore_stack;
4634 if let Some((ignore, _)) = snapshot.ignores_by_parent_abs_path.get(&job.abs_path) {
4635 ignore_stack = ignore_stack.append(job.abs_path.clone(), ignore.clone());
4636 }
4637
4638 let mut entries_by_id_edits = Vec::new();
4639 let mut entries_by_path_edits = Vec::new();
4640 let path = job
4641 .abs_path
4642 .strip_prefix(snapshot.abs_path.as_path())
4643 .unwrap();
4644
4645 for mut entry in snapshot.child_entries(path).cloned() {
4646 let was_ignored = entry.is_ignored;
4647 let abs_path: Arc<Path> = snapshot.abs_path().join(&entry.path).into();
4648 entry.is_ignored = ignore_stack.is_abs_path_ignored(&abs_path, entry.is_dir());
4649
4650 if entry.is_dir() {
4651 let child_ignore_stack = if entry.is_ignored {
4652 IgnoreStack::all()
4653 } else {
4654 ignore_stack.clone()
4655 };
4656
4657 // Scan any directories that were previously ignored and weren't previously scanned.
4658 if was_ignored && !entry.is_ignored && entry.kind.is_unloaded() {
4659 let state = self.state.lock();
4660 if state.should_scan_directory(&entry) {
4661 state.enqueue_scan_dir(abs_path.clone(), &entry, &job.scan_queue);
4662 }
4663 }
4664
4665 job.ignore_queue
4666 .send(UpdateIgnoreStatusJob {
4667 abs_path: abs_path.clone(),
4668 ignore_stack: child_ignore_stack,
4669 ignore_queue: job.ignore_queue.clone(),
4670 scan_queue: job.scan_queue.clone(),
4671 })
4672 .await
4673 .unwrap();
4674 }
4675
4676 if entry.is_ignored != was_ignored {
4677 let mut path_entry = snapshot.entries_by_id.get(&entry.id, &()).unwrap().clone();
4678 path_entry.scan_id = snapshot.scan_id;
4679 path_entry.is_ignored = entry.is_ignored;
4680 entries_by_id_edits.push(Edit::Insert(path_entry));
4681 entries_by_path_edits.push(Edit::Insert(entry));
4682 }
4683 }
4684
4685 let state = &mut self.state.lock();
4686 for edit in &entries_by_path_edits {
4687 if let Edit::Insert(entry) = edit {
4688 if let Err(ix) = state.changed_paths.binary_search(&entry.path) {
4689 state.changed_paths.insert(ix, entry.path.clone());
4690 }
4691 }
4692 }
4693
4694 state
4695 .snapshot
4696 .entries_by_path
4697 .edit(entries_by_path_edits, &());
4698 state.snapshot.entries_by_id.edit(entries_by_id_edits, &());
4699 }
4700
4701 fn update_git_repositories(&self, dot_git_paths: Vec<PathBuf>) {
4702 log::trace!("reloading repositories: {dot_git_paths:?}");
4703 let mut state = self.state.lock();
4704 let scan_id = state.snapshot.scan_id;
4705 for dot_git_dir in dot_git_paths {
4706 let existing_repository_entry =
4707 state
4708 .snapshot
4709 .git_repositories
4710 .iter()
4711 .find_map(|(_, repo)| {
4712 if repo.dot_git_dir_abs_path.as_ref() == &dot_git_dir
4713 || repo.dot_git_worktree_abs_path.as_deref() == Some(&dot_git_dir)
4714 {
4715 Some(repo.clone())
4716 } else {
4717 None
4718 }
4719 });
4720
4721 match existing_repository_entry {
4722 None => {
4723 let Ok(relative) = dot_git_dir.strip_prefix(state.snapshot.abs_path()) else {
4724 return;
4725 };
4726 state.insert_git_repository(
4727 relative.into(),
4728 self.fs.as_ref(),
4729 self.watcher.as_ref(),
4730 );
4731 }
4732 Some(local_repository) => {
4733 state.snapshot.git_repositories.update(
4734 &local_repository.work_directory_id,
4735 |entry| {
4736 entry.git_dir_scan_id = scan_id;
4737 },
4738 );
4739 }
4740 };
4741 }
4742
4743 // Remove any git repositories whose .git entry no longer exists.
4744 let snapshot = &mut state.snapshot;
4745 let mut ids_to_preserve = HashSet::default();
4746 for (&work_directory_id, entry) in snapshot.git_repositories.iter() {
4747 let exists_in_snapshot = snapshot
4748 .entry_for_id(work_directory_id)
4749 .map_or(false, |entry| {
4750 snapshot.entry_for_path(entry.path.join(*DOT_GIT)).is_some()
4751 });
4752
4753 if exists_in_snapshot
4754 || matches!(
4755 smol::block_on(self.fs.metadata(&entry.dot_git_dir_abs_path)),
4756 Ok(Some(_))
4757 )
4758 {
4759 ids_to_preserve.insert(work_directory_id);
4760 }
4761 }
4762
4763 snapshot
4764 .git_repositories
4765 .retain(|work_directory_id, _| ids_to_preserve.contains(work_directory_id));
4766 }
4767
4768 async fn progress_timer(&self, running: bool) {
4769 if !running {
4770 return futures::future::pending().await;
4771 }
4772
4773 #[cfg(any(test, feature = "test-support"))]
4774 if self.fs.is_fake() {
4775 return self.executor.simulate_random_delay().await;
4776 }
4777
4778 smol::Timer::after(FS_WATCH_LATENCY).await;
4779 }
4780
4781 fn is_path_private(&self, path: &Path) -> bool {
4782 !self.share_private_files && self.settings.is_path_private(path)
4783 }
4784
4785 async fn next_scan_request(&self) -> Result<ScanRequest> {
4786 let mut request = self.scan_requests_rx.recv().await?;
4787 while let Ok(next_request) = self.scan_requests_rx.try_recv() {
4788 request.relative_paths.extend(next_request.relative_paths);
4789 request.done.extend(next_request.done);
4790 }
4791 Ok(request)
4792 }
4793}
4794
4795async fn discover_ancestor_git_repo(
4796 fs: Arc<dyn Fs>,
4797 root_abs_path: &SanitizedPath,
4798) -> (
4799 HashMap<Arc<Path>, (Arc<Gitignore>, bool)>,
4800 Option<(PathBuf, WorkDirectory)>,
4801) {
4802 let mut ignores = HashMap::default();
4803 for (index, ancestor) in root_abs_path.as_path().ancestors().enumerate() {
4804 if index != 0 {
4805 if Some(ancestor) == fs.home_dir().as_deref() {
4806 // Unless $HOME is itself the worktree root, don't consider it as a
4807 // containing git repository---expensive and likely unwanted.
4808 break;
4809 } else if let Ok(ignore) =
4810 build_gitignore(&ancestor.join(*GITIGNORE), fs.as_ref()).await
4811 {
4812 ignores.insert(ancestor.into(), (ignore.into(), false));
4813 }
4814 }
4815
4816 let ancestor_dot_git = ancestor.join(*DOT_GIT);
4817 log::trace!("considering ancestor: {ancestor_dot_git:?}");
4818 // Check whether the directory or file called `.git` exists (in the
4819 // case of worktrees it's a file.)
4820 if fs
4821 .metadata(&ancestor_dot_git)
4822 .await
4823 .is_ok_and(|metadata| metadata.is_some())
4824 {
4825 if index != 0 {
4826 // We canonicalize, since the FS events use the canonicalized path.
4827 if let Some(ancestor_dot_git) = fs.canonicalize(&ancestor_dot_git).await.log_err() {
4828 let location_in_repo = root_abs_path
4829 .as_path()
4830 .strip_prefix(ancestor)
4831 .unwrap()
4832 .into();
4833 log::info!("inserting parent git repo for this worktree: {location_in_repo:?}");
4834 // We associate the external git repo with our root folder and
4835 // also mark where in the git repo the root folder is located.
4836 return (
4837 ignores,
4838 Some((
4839 ancestor_dot_git,
4840 WorkDirectory::AboveProject {
4841 absolute_path: ancestor.into(),
4842 location_in_repo,
4843 },
4844 )),
4845 );
4846 };
4847 }
4848
4849 // Reached root of git repository.
4850 break;
4851 }
4852 }
4853
4854 (ignores, None)
4855}
4856
4857fn build_diff(
4858 phase: BackgroundScannerPhase,
4859 old_snapshot: &Snapshot,
4860 new_snapshot: &Snapshot,
4861 event_paths: &[Arc<Path>],
4862) -> UpdatedEntriesSet {
4863 use BackgroundScannerPhase::*;
4864 use PathChange::{Added, AddedOrUpdated, Loaded, Removed, Updated};
4865
4866 // Identify which paths have changed. Use the known set of changed
4867 // parent paths to optimize the search.
4868 let mut changes = Vec::new();
4869 let mut old_paths = old_snapshot.entries_by_path.cursor::<PathKey>(&());
4870 let mut new_paths = new_snapshot.entries_by_path.cursor::<PathKey>(&());
4871 let mut last_newly_loaded_dir_path = None;
4872 old_paths.next(&());
4873 new_paths.next(&());
4874 for path in event_paths {
4875 let path = PathKey(path.clone());
4876 if old_paths.item().map_or(false, |e| e.path < path.0) {
4877 old_paths.seek_forward(&path, Bias::Left, &());
4878 }
4879 if new_paths.item().map_or(false, |e| e.path < path.0) {
4880 new_paths.seek_forward(&path, Bias::Left, &());
4881 }
4882 loop {
4883 match (old_paths.item(), new_paths.item()) {
4884 (Some(old_entry), Some(new_entry)) => {
4885 if old_entry.path > path.0
4886 && new_entry.path > path.0
4887 && !old_entry.path.starts_with(&path.0)
4888 && !new_entry.path.starts_with(&path.0)
4889 {
4890 break;
4891 }
4892
4893 match Ord::cmp(&old_entry.path, &new_entry.path) {
4894 Ordering::Less => {
4895 changes.push((old_entry.path.clone(), old_entry.id, Removed));
4896 old_paths.next(&());
4897 }
4898 Ordering::Equal => {
4899 if phase == EventsReceivedDuringInitialScan {
4900 if old_entry.id != new_entry.id {
4901 changes.push((old_entry.path.clone(), old_entry.id, Removed));
4902 }
4903 // If the worktree was not fully initialized when this event was generated,
4904 // we can't know whether this entry was added during the scan or whether
4905 // it was merely updated.
4906 changes.push((
4907 new_entry.path.clone(),
4908 new_entry.id,
4909 AddedOrUpdated,
4910 ));
4911 } else if old_entry.id != new_entry.id {
4912 changes.push((old_entry.path.clone(), old_entry.id, Removed));
4913 changes.push((new_entry.path.clone(), new_entry.id, Added));
4914 } else if old_entry != new_entry {
4915 if old_entry.kind.is_unloaded() {
4916 last_newly_loaded_dir_path = Some(&new_entry.path);
4917 changes.push((new_entry.path.clone(), new_entry.id, Loaded));
4918 } else {
4919 changes.push((new_entry.path.clone(), new_entry.id, Updated));
4920 }
4921 }
4922 old_paths.next(&());
4923 new_paths.next(&());
4924 }
4925 Ordering::Greater => {
4926 let is_newly_loaded = phase == InitialScan
4927 || last_newly_loaded_dir_path
4928 .as_ref()
4929 .map_or(false, |dir| new_entry.path.starts_with(dir));
4930 changes.push((
4931 new_entry.path.clone(),
4932 new_entry.id,
4933 if is_newly_loaded { Loaded } else { Added },
4934 ));
4935 new_paths.next(&());
4936 }
4937 }
4938 }
4939 (Some(old_entry), None) => {
4940 changes.push((old_entry.path.clone(), old_entry.id, Removed));
4941 old_paths.next(&());
4942 }
4943 (None, Some(new_entry)) => {
4944 let is_newly_loaded = phase == InitialScan
4945 || last_newly_loaded_dir_path
4946 .as_ref()
4947 .map_or(false, |dir| new_entry.path.starts_with(dir));
4948 changes.push((
4949 new_entry.path.clone(),
4950 new_entry.id,
4951 if is_newly_loaded { Loaded } else { Added },
4952 ));
4953 new_paths.next(&());
4954 }
4955 (None, None) => break,
4956 }
4957 }
4958 }
4959
4960 changes.into()
4961}
4962
4963fn swap_to_front(child_paths: &mut Vec<PathBuf>, file: &OsStr) {
4964 let position = child_paths
4965 .iter()
4966 .position(|path| path.file_name().unwrap() == file);
4967 if let Some(position) = position {
4968 let temp = child_paths.remove(position);
4969 child_paths.insert(0, temp);
4970 }
4971}
4972
4973fn char_bag_for_path(root_char_bag: CharBag, path: &Path) -> CharBag {
4974 let mut result = root_char_bag;
4975 result.extend(
4976 path.to_string_lossy()
4977 .chars()
4978 .map(|c| c.to_ascii_lowercase()),
4979 );
4980 result
4981}
4982
4983#[derive(Debug)]
4984struct ScanJob {
4985 abs_path: Arc<Path>,
4986 path: Arc<Path>,
4987 ignore_stack: Arc<IgnoreStack>,
4988 scan_queue: Sender<ScanJob>,
4989 ancestor_inodes: TreeSet<u64>,
4990 is_external: bool,
4991}
4992
4993struct UpdateIgnoreStatusJob {
4994 abs_path: Arc<Path>,
4995 ignore_stack: Arc<IgnoreStack>,
4996 ignore_queue: Sender<UpdateIgnoreStatusJob>,
4997 scan_queue: Sender<ScanJob>,
4998}
4999
5000pub trait WorktreeModelHandle {
5001 #[cfg(any(test, feature = "test-support"))]
5002 fn flush_fs_events<'a>(
5003 &self,
5004 cx: &'a mut gpui::TestAppContext,
5005 ) -> futures::future::LocalBoxFuture<'a, ()>;
5006
5007 #[cfg(any(test, feature = "test-support"))]
5008 fn flush_fs_events_in_root_git_repository<'a>(
5009 &self,
5010 cx: &'a mut gpui::TestAppContext,
5011 ) -> futures::future::LocalBoxFuture<'a, ()>;
5012}
5013
5014impl WorktreeModelHandle for Entity<Worktree> {
5015 // When the worktree's FS event stream sometimes delivers "redundant" events for FS changes that
5016 // occurred before the worktree was constructed. These events can cause the worktree to perform
5017 // extra directory scans, and emit extra scan-state notifications.
5018 //
5019 // This function mutates the worktree's directory and waits for those mutations to be picked up,
5020 // to ensure that all redundant FS events have already been processed.
5021 #[cfg(any(test, feature = "test-support"))]
5022 fn flush_fs_events<'a>(
5023 &self,
5024 cx: &'a mut gpui::TestAppContext,
5025 ) -> futures::future::LocalBoxFuture<'a, ()> {
5026 let file_name = "fs-event-sentinel";
5027
5028 let tree = self.clone();
5029 let (fs, root_path) = self.update(cx, |tree, _| {
5030 let tree = tree.as_local().unwrap();
5031 (tree.fs.clone(), tree.abs_path().clone())
5032 });
5033
5034 async move {
5035 fs.create_file(&root_path.join(file_name), Default::default())
5036 .await
5037 .unwrap();
5038
5039 let mut events = cx.events(&tree);
5040 while events.next().await.is_some() {
5041 if tree.update(cx, |tree, _| tree.entry_for_path(file_name).is_some()) {
5042 break;
5043 }
5044 }
5045
5046 fs.remove_file(&root_path.join(file_name), Default::default())
5047 .await
5048 .unwrap();
5049 while events.next().await.is_some() {
5050 if tree.update(cx, |tree, _| tree.entry_for_path(file_name).is_none()) {
5051 break;
5052 }
5053 }
5054
5055 cx.update(|cx| tree.read(cx).as_local().unwrap().scan_complete())
5056 .await;
5057 }
5058 .boxed_local()
5059 }
5060
5061 // This function is similar to flush_fs_events, except that it waits for events to be flushed in
5062 // the .git folder of the root repository.
5063 // The reason for its existence is that a repository's .git folder might live *outside* of the
5064 // worktree and thus its FS events might go through a different path.
5065 // In order to flush those, we need to create artificial events in the .git folder and wait
5066 // for the repository to be reloaded.
5067 #[cfg(any(test, feature = "test-support"))]
5068 fn flush_fs_events_in_root_git_repository<'a>(
5069 &self,
5070 cx: &'a mut gpui::TestAppContext,
5071 ) -> futures::future::LocalBoxFuture<'a, ()> {
5072 let file_name = "fs-event-sentinel";
5073
5074 let tree = self.clone();
5075 let (fs, root_path, mut git_dir_scan_id) = self.update(cx, |tree, _| {
5076 let tree = tree.as_local().unwrap();
5077 let local_repo_entry = tree
5078 .git_repositories
5079 .values()
5080 .min_by_key(|local_repo_entry| local_repo_entry.work_directory.clone())
5081 .unwrap();
5082 (
5083 tree.fs.clone(),
5084 local_repo_entry.dot_git_dir_abs_path.clone(),
5085 local_repo_entry.git_dir_scan_id,
5086 )
5087 });
5088
5089 let scan_id_increased = |tree: &mut Worktree, git_dir_scan_id: &mut usize| {
5090 let tree = tree.as_local().unwrap();
5091 // let repository = tree.repositories.first().unwrap();
5092 let local_repo_entry = tree
5093 .git_repositories
5094 .values()
5095 .min_by_key(|local_repo_entry| local_repo_entry.work_directory.clone())
5096 .unwrap();
5097
5098 if local_repo_entry.git_dir_scan_id > *git_dir_scan_id {
5099 *git_dir_scan_id = local_repo_entry.git_dir_scan_id;
5100 true
5101 } else {
5102 false
5103 }
5104 };
5105
5106 async move {
5107 fs.create_file(&root_path.join(file_name), Default::default())
5108 .await
5109 .unwrap();
5110
5111 let mut events = cx.events(&tree);
5112 while events.next().await.is_some() {
5113 if tree.update(cx, |tree, _| scan_id_increased(tree, &mut git_dir_scan_id)) {
5114 break;
5115 }
5116 }
5117
5118 fs.remove_file(&root_path.join(file_name), Default::default())
5119 .await
5120 .unwrap();
5121
5122 while events.next().await.is_some() {
5123 if tree.update(cx, |tree, _| scan_id_increased(tree, &mut git_dir_scan_id)) {
5124 break;
5125 }
5126 }
5127
5128 cx.update(|cx| tree.read(cx).as_local().unwrap().scan_complete())
5129 .await;
5130 }
5131 .boxed_local()
5132 }
5133}
5134
5135#[derive(Clone, Debug)]
5136struct TraversalProgress<'a> {
5137 max_path: &'a Path,
5138 count: usize,
5139 non_ignored_count: usize,
5140 file_count: usize,
5141 non_ignored_file_count: usize,
5142}
5143
5144impl TraversalProgress<'_> {
5145 fn count(&self, include_files: bool, include_dirs: bool, include_ignored: bool) -> usize {
5146 match (include_files, include_dirs, include_ignored) {
5147 (true, true, true) => self.count,
5148 (true, true, false) => self.non_ignored_count,
5149 (true, false, true) => self.file_count,
5150 (true, false, false) => self.non_ignored_file_count,
5151 (false, true, true) => self.count - self.file_count,
5152 (false, true, false) => self.non_ignored_count - self.non_ignored_file_count,
5153 (false, false, _) => 0,
5154 }
5155 }
5156}
5157
5158impl<'a> sum_tree::Dimension<'a, EntrySummary> for TraversalProgress<'a> {
5159 fn zero(_cx: &()) -> Self {
5160 Default::default()
5161 }
5162
5163 fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
5164 self.max_path = summary.max_path.as_ref();
5165 self.count += summary.count;
5166 self.non_ignored_count += summary.non_ignored_count;
5167 self.file_count += summary.file_count;
5168 self.non_ignored_file_count += summary.non_ignored_file_count;
5169 }
5170}
5171
5172impl Default for TraversalProgress<'_> {
5173 fn default() -> Self {
5174 Self {
5175 max_path: Path::new(""),
5176 count: 0,
5177 non_ignored_count: 0,
5178 file_count: 0,
5179 non_ignored_file_count: 0,
5180 }
5181 }
5182}
5183
5184#[derive(Debug)]
5185pub struct Traversal<'a> {
5186 snapshot: &'a Snapshot,
5187 cursor: sum_tree::Cursor<'a, Entry, TraversalProgress<'a>>,
5188 include_ignored: bool,
5189 include_files: bool,
5190 include_dirs: bool,
5191}
5192
5193impl<'a> Traversal<'a> {
5194 fn new(
5195 snapshot: &'a Snapshot,
5196 include_files: bool,
5197 include_dirs: bool,
5198 include_ignored: bool,
5199 start_path: &Path,
5200 ) -> Self {
5201 let mut cursor = snapshot.entries_by_path.cursor(&());
5202 cursor.seek(&TraversalTarget::path(start_path), Bias::Left, &());
5203 let mut traversal = Self {
5204 snapshot,
5205 cursor,
5206 include_files,
5207 include_dirs,
5208 include_ignored,
5209 };
5210 if traversal.end_offset() == traversal.start_offset() {
5211 traversal.next();
5212 }
5213 traversal
5214 }
5215
5216 pub fn advance(&mut self) -> bool {
5217 self.advance_by(1)
5218 }
5219
5220 pub fn advance_by(&mut self, count: usize) -> bool {
5221 self.cursor.seek_forward(
5222 &TraversalTarget::Count {
5223 count: self.end_offset() + count,
5224 include_dirs: self.include_dirs,
5225 include_files: self.include_files,
5226 include_ignored: self.include_ignored,
5227 },
5228 Bias::Left,
5229 &(),
5230 )
5231 }
5232
5233 pub fn advance_to_sibling(&mut self) -> bool {
5234 while let Some(entry) = self.cursor.item() {
5235 self.cursor
5236 .seek_forward(&TraversalTarget::successor(&entry.path), Bias::Left, &());
5237 if let Some(entry) = self.cursor.item() {
5238 if (self.include_files || !entry.is_file())
5239 && (self.include_dirs || !entry.is_dir())
5240 && (self.include_ignored || !entry.is_ignored || entry.is_always_included)
5241 {
5242 return true;
5243 }
5244 }
5245 }
5246 false
5247 }
5248
5249 pub fn back_to_parent(&mut self) -> bool {
5250 let Some(parent_path) = self.cursor.item().and_then(|entry| entry.path.parent()) else {
5251 return false;
5252 };
5253 self.cursor
5254 .seek(&TraversalTarget::path(parent_path), Bias::Left, &())
5255 }
5256
5257 pub fn entry(&self) -> Option<&'a Entry> {
5258 self.cursor.item()
5259 }
5260
5261 pub fn snapshot(&self) -> &'a Snapshot {
5262 self.snapshot
5263 }
5264
5265 pub fn start_offset(&self) -> usize {
5266 self.cursor
5267 .start()
5268 .count(self.include_files, self.include_dirs, self.include_ignored)
5269 }
5270
5271 pub fn end_offset(&self) -> usize {
5272 self.cursor
5273 .end(&())
5274 .count(self.include_files, self.include_dirs, self.include_ignored)
5275 }
5276}
5277
5278impl<'a> Iterator for Traversal<'a> {
5279 type Item = &'a Entry;
5280
5281 fn next(&mut self) -> Option<Self::Item> {
5282 if let Some(item) = self.entry() {
5283 self.advance();
5284 Some(item)
5285 } else {
5286 None
5287 }
5288 }
5289}
5290
5291#[derive(Debug, Clone, Copy)]
5292pub enum PathTarget<'a> {
5293 Path(&'a Path),
5294 Successor(&'a Path),
5295}
5296
5297impl PathTarget<'_> {
5298 fn cmp_path(&self, other: &Path) -> Ordering {
5299 match self {
5300 PathTarget::Path(path) => path.cmp(&other),
5301 PathTarget::Successor(path) => {
5302 if other.starts_with(path) {
5303 Ordering::Greater
5304 } else {
5305 Ordering::Equal
5306 }
5307 }
5308 }
5309 }
5310}
5311
5312impl<'a, S: Summary> SeekTarget<'a, PathSummary<S>, PathProgress<'a>> for PathTarget<'_> {
5313 fn cmp(&self, cursor_location: &PathProgress<'a>, _: &S::Context) -> Ordering {
5314 self.cmp_path(&cursor_location.max_path)
5315 }
5316}
5317
5318impl<'a, S: Summary> SeekTarget<'a, PathSummary<S>, TraversalProgress<'a>> for PathTarget<'_> {
5319 fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: &S::Context) -> Ordering {
5320 self.cmp_path(&cursor_location.max_path)
5321 }
5322}
5323
5324#[derive(Debug)]
5325enum TraversalTarget<'a> {
5326 Path(PathTarget<'a>),
5327 Count {
5328 count: usize,
5329 include_files: bool,
5330 include_ignored: bool,
5331 include_dirs: bool,
5332 },
5333}
5334
5335impl<'a> TraversalTarget<'a> {
5336 fn path(path: &'a Path) -> Self {
5337 Self::Path(PathTarget::Path(path))
5338 }
5339
5340 fn successor(path: &'a Path) -> Self {
5341 Self::Path(PathTarget::Successor(path))
5342 }
5343
5344 fn cmp_progress(&self, progress: &TraversalProgress) -> Ordering {
5345 match self {
5346 TraversalTarget::Path(path) => path.cmp_path(&progress.max_path),
5347 TraversalTarget::Count {
5348 count,
5349 include_files,
5350 include_dirs,
5351 include_ignored,
5352 } => Ord::cmp(
5353 count,
5354 &progress.count(*include_files, *include_dirs, *include_ignored),
5355 ),
5356 }
5357 }
5358}
5359
5360impl<'a> SeekTarget<'a, EntrySummary, TraversalProgress<'a>> for TraversalTarget<'_> {
5361 fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: &()) -> Ordering {
5362 self.cmp_progress(cursor_location)
5363 }
5364}
5365
5366impl<'a> SeekTarget<'a, PathSummary<Unit>, TraversalProgress<'a>> for TraversalTarget<'_> {
5367 fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: &()) -> Ordering {
5368 self.cmp_progress(cursor_location)
5369 }
5370}
5371
5372pub struct ChildEntriesOptions {
5373 pub include_files: bool,
5374 pub include_dirs: bool,
5375 pub include_ignored: bool,
5376}
5377
5378pub struct ChildEntriesIter<'a> {
5379 parent_path: &'a Path,
5380 traversal: Traversal<'a>,
5381}
5382
5383impl<'a> Iterator for ChildEntriesIter<'a> {
5384 type Item = &'a Entry;
5385
5386 fn next(&mut self) -> Option<Self::Item> {
5387 if let Some(item) = self.traversal.entry() {
5388 if item.path.starts_with(self.parent_path) {
5389 self.traversal.advance_to_sibling();
5390 return Some(item);
5391 }
5392 }
5393 None
5394 }
5395}
5396
5397impl<'a> From<&'a Entry> for proto::Entry {
5398 fn from(entry: &'a Entry) -> Self {
5399 Self {
5400 id: entry.id.to_proto(),
5401 is_dir: entry.is_dir(),
5402 path: entry.path.as_ref().to_proto(),
5403 inode: entry.inode,
5404 mtime: entry.mtime.map(|time| time.into()),
5405 is_ignored: entry.is_ignored,
5406 is_external: entry.is_external,
5407 is_fifo: entry.is_fifo,
5408 size: Some(entry.size),
5409 canonical_path: entry
5410 .canonical_path
5411 .as_ref()
5412 .map(|path| path.as_ref().to_proto()),
5413 }
5414 }
5415}
5416
5417impl<'a> TryFrom<(&'a CharBag, &PathMatcher, proto::Entry)> for Entry {
5418 type Error = anyhow::Error;
5419
5420 fn try_from(
5421 (root_char_bag, always_included, entry): (&'a CharBag, &PathMatcher, proto::Entry),
5422 ) -> Result<Self> {
5423 let kind = if entry.is_dir {
5424 EntryKind::Dir
5425 } else {
5426 EntryKind::File
5427 };
5428
5429 let path = Arc::<Path>::from_proto(entry.path);
5430 let char_bag = char_bag_for_path(*root_char_bag, &path);
5431 let is_always_included = always_included.is_match(path.as_ref());
5432 Ok(Entry {
5433 id: ProjectEntryId::from_proto(entry.id),
5434 kind,
5435 path,
5436 inode: entry.inode,
5437 mtime: entry.mtime.map(|time| time.into()),
5438 size: entry.size.unwrap_or(0),
5439 canonical_path: entry
5440 .canonical_path
5441 .map(|path_string| Arc::from(PathBuf::from_proto(path_string))),
5442 is_ignored: entry.is_ignored,
5443 is_always_included,
5444 is_external: entry.is_external,
5445 is_private: false,
5446 char_bag,
5447 is_fifo: entry.is_fifo,
5448 })
5449 }
5450}
5451
5452#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
5453pub struct ProjectEntryId(usize);
5454
5455impl ProjectEntryId {
5456 pub const MAX: Self = Self(usize::MAX);
5457 pub const MIN: Self = Self(usize::MIN);
5458
5459 pub fn new(counter: &AtomicUsize) -> Self {
5460 Self(counter.fetch_add(1, SeqCst))
5461 }
5462
5463 pub fn from_proto(id: u64) -> Self {
5464 Self(id as usize)
5465 }
5466
5467 pub fn to_proto(&self) -> u64 {
5468 self.0 as u64
5469 }
5470
5471 pub fn to_usize(&self) -> usize {
5472 self.0
5473 }
5474}
5475
5476#[cfg(any(test, feature = "test-support"))]
5477impl CreatedEntry {
5478 pub fn to_included(self) -> Option<Entry> {
5479 match self {
5480 CreatedEntry::Included(entry) => Some(entry),
5481 CreatedEntry::Excluded { .. } => None,
5482 }
5483 }
5484}