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 mut containing_git_repository = None;
3777 for (index, ancestor) in root_abs_path.as_path().ancestors().enumerate() {
3778 if index != 0 {
3779 if Some(ancestor) == self.fs.home_dir().as_deref() {
3780 // Unless $HOME is itself the worktree root, don't consider it as a
3781 // containing git repository---expensive and likely unwanted.
3782 break;
3783 } else if let Ok(ignore) =
3784 build_gitignore(&ancestor.join(*GITIGNORE), self.fs.as_ref()).await
3785 {
3786 self.state
3787 .lock()
3788 .snapshot
3789 .ignores_by_parent_abs_path
3790 .insert(ancestor.into(), (ignore.into(), false));
3791 }
3792 }
3793
3794 let ancestor_dot_git = ancestor.join(*DOT_GIT);
3795 log::trace!("considering ancestor: {ancestor_dot_git:?}");
3796 // Check whether the directory or file called `.git` exists (in the
3797 // case of worktrees it's a file.)
3798 if self
3799 .fs
3800 .metadata(&ancestor_dot_git)
3801 .await
3802 .is_ok_and(|metadata| metadata.is_some())
3803 {
3804 if index != 0 {
3805 // We canonicalize, since the FS events use the canonicalized path.
3806 if let Some(ancestor_dot_git) =
3807 self.fs.canonicalize(&ancestor_dot_git).await.log_err()
3808 {
3809 let location_in_repo = root_abs_path
3810 .as_path()
3811 .strip_prefix(ancestor)
3812 .unwrap()
3813 .into();
3814 log::info!(
3815 "inserting parent git repo for this worktree: {location_in_repo:?}"
3816 );
3817 // We associate the external git repo with our root folder and
3818 // also mark where in the git repo the root folder is located.
3819 let local_repository = self.state.lock().insert_git_repository_for_path(
3820 WorkDirectory::AboveProject {
3821 absolute_path: ancestor.into(),
3822 location_in_repo,
3823 },
3824 ancestor_dot_git.clone().into(),
3825 self.fs.as_ref(),
3826 self.watcher.as_ref(),
3827 );
3828
3829 if local_repository.is_some() {
3830 containing_git_repository = Some(ancestor_dot_git)
3831 }
3832 };
3833 }
3834
3835 // Reached root of git repository.
3836 break;
3837 }
3838 }
3839
3840 log::info!("containing git repository: {containing_git_repository:?}");
3841
3842 let (scan_job_tx, scan_job_rx) = channel::unbounded();
3843 {
3844 let mut state = self.state.lock();
3845 state.snapshot.scan_id += 1;
3846 if let Some(mut root_entry) = state.snapshot.root_entry().cloned() {
3847 let ignore_stack = state
3848 .snapshot
3849 .ignore_stack_for_abs_path(root_abs_path.as_path(), true);
3850 if ignore_stack.is_abs_path_ignored(root_abs_path.as_path(), true) {
3851 root_entry.is_ignored = true;
3852 state.insert_entry(root_entry.clone(), self.fs.as_ref(), self.watcher.as_ref());
3853 }
3854 state.enqueue_scan_dir(root_abs_path.into(), &root_entry, &scan_job_tx);
3855 }
3856 };
3857
3858 // Perform an initial scan of the directory.
3859 drop(scan_job_tx);
3860 self.scan_dirs(true, scan_job_rx).await;
3861 {
3862 let mut state = self.state.lock();
3863 state.snapshot.completed_scan_id = state.snapshot.scan_id;
3864 }
3865
3866 self.send_status_update(false, SmallVec::new());
3867
3868 // Process any any FS events that occurred while performing the initial scan.
3869 // For these events, update events cannot be as precise, because we didn't
3870 // have the previous state loaded yet.
3871 self.phase = BackgroundScannerPhase::EventsReceivedDuringInitialScan;
3872 if let Poll::Ready(Some(mut paths)) = futures::poll!(fs_events_rx.next()) {
3873 while let Poll::Ready(Some(more_paths)) = futures::poll!(fs_events_rx.next()) {
3874 paths.extend(more_paths);
3875 }
3876 self.process_events(paths.into_iter().map(Into::into).collect())
3877 .await;
3878 }
3879 if let Some(abs_path) = containing_git_repository {
3880 self.process_events(vec![abs_path]).await;
3881 }
3882
3883 // Continue processing events until the worktree is dropped.
3884 self.phase = BackgroundScannerPhase::Events;
3885
3886 loop {
3887 select_biased! {
3888 // Process any path refresh requests from the worktree. Prioritize
3889 // these before handling changes reported by the filesystem.
3890 request = self.next_scan_request().fuse() => {
3891 let Ok(request) = request else { break };
3892 if !self.process_scan_request(request, false).await {
3893 return;
3894 }
3895 }
3896
3897 path_prefix_request = self.path_prefixes_to_scan_rx.recv().fuse() => {
3898 let Ok(request) = path_prefix_request else { break };
3899 log::trace!("adding path prefix {:?}", request.path);
3900
3901 let did_scan = self.forcibly_load_paths(&[request.path.clone()]).await;
3902 if did_scan {
3903 let abs_path =
3904 {
3905 let mut state = self.state.lock();
3906 state.path_prefixes_to_scan.insert(request.path.clone());
3907 state.snapshot.abs_path.as_path().join(&request.path)
3908 };
3909
3910 if let Some(abs_path) = self.fs.canonicalize(&abs_path).await.log_err() {
3911 self.process_events(vec![abs_path]).await;
3912 }
3913 }
3914 self.send_status_update(false, request.done);
3915 }
3916
3917 paths = fs_events_rx.next().fuse() => {
3918 let Some(mut paths) = paths else { break };
3919 while let Poll::Ready(Some(more_paths)) = futures::poll!(fs_events_rx.next()) {
3920 paths.extend(more_paths);
3921 }
3922 self.process_events(paths.into_iter().map(Into::into).collect()).await;
3923 }
3924 }
3925 }
3926 }
3927
3928 async fn process_scan_request(&self, mut request: ScanRequest, scanning: bool) -> bool {
3929 log::debug!("rescanning paths {:?}", request.relative_paths);
3930
3931 request.relative_paths.sort_unstable();
3932 self.forcibly_load_paths(&request.relative_paths).await;
3933
3934 let root_path = self.state.lock().snapshot.abs_path.clone();
3935 let root_canonical_path = match self.fs.canonicalize(root_path.as_path()).await {
3936 Ok(path) => SanitizedPath::from(path),
3937 Err(err) => {
3938 log::error!("failed to canonicalize root path: {}", err);
3939 return true;
3940 }
3941 };
3942 let abs_paths = request
3943 .relative_paths
3944 .iter()
3945 .map(|path| {
3946 if path.file_name().is_some() {
3947 root_canonical_path.as_path().join(path).to_path_buf()
3948 } else {
3949 root_canonical_path.as_path().to_path_buf()
3950 }
3951 })
3952 .collect::<Vec<_>>();
3953
3954 {
3955 let mut state = self.state.lock();
3956 let is_idle = state.snapshot.completed_scan_id == state.snapshot.scan_id;
3957 state.snapshot.scan_id += 1;
3958 if is_idle {
3959 state.snapshot.completed_scan_id = state.snapshot.scan_id;
3960 }
3961 }
3962
3963 self.reload_entries_for_paths(
3964 root_path,
3965 root_canonical_path,
3966 &request.relative_paths,
3967 abs_paths,
3968 None,
3969 )
3970 .await;
3971
3972 self.send_status_update(scanning, request.done)
3973 }
3974
3975 async fn process_events(&self, mut abs_paths: Vec<PathBuf>) {
3976 let root_path = self.state.lock().snapshot.abs_path.clone();
3977 let root_canonical_path = match self.fs.canonicalize(root_path.as_path()).await {
3978 Ok(path) => SanitizedPath::from(path),
3979 Err(err) => {
3980 let new_path = self
3981 .state
3982 .lock()
3983 .snapshot
3984 .root_file_handle
3985 .clone()
3986 .and_then(|handle| handle.current_path(&self.fs).log_err())
3987 .map(SanitizedPath::from)
3988 .filter(|new_path| *new_path != root_path);
3989
3990 if let Some(new_path) = new_path.as_ref() {
3991 log::info!(
3992 "root renamed from {} to {}",
3993 root_path.as_path().display(),
3994 new_path.as_path().display()
3995 )
3996 } else {
3997 log::warn!("root path could not be canonicalized: {}", err);
3998 }
3999 self.status_updates_tx
4000 .unbounded_send(ScanState::RootUpdated { new_path })
4001 .ok();
4002 return;
4003 }
4004 };
4005
4006 // Certain directories may have FS changes, but do not lead to git data changes that Zed cares about.
4007 // Ignore these, to avoid Zed unnecessarily rescanning git metadata.
4008 let skipped_files_in_dot_git = HashSet::from_iter([*COMMIT_MESSAGE, *INDEX_LOCK]);
4009 let skipped_dirs_in_dot_git = [*FSMONITOR_DAEMON, *LFS_DIR];
4010
4011 let mut relative_paths = Vec::with_capacity(abs_paths.len());
4012 let mut dot_git_abs_paths = Vec::new();
4013 abs_paths.sort_unstable();
4014 abs_paths.dedup_by(|a, b| a.starts_with(b));
4015 abs_paths.retain(|abs_path| {
4016 let abs_path = SanitizedPath::from(abs_path);
4017
4018 let snapshot = &self.state.lock().snapshot;
4019 {
4020 let mut is_git_related = false;
4021
4022 let dot_git_paths = abs_path.as_path().ancestors().find_map(|ancestor| {
4023 if smol::block_on(is_git_dir(ancestor, self.fs.as_ref())) {
4024 let path_in_git_dir = abs_path.as_path().strip_prefix(ancestor).expect("stripping off the ancestor");
4025 Some((ancestor.to_owned(), path_in_git_dir.to_owned()))
4026 } else {
4027 None
4028 }
4029 });
4030
4031 if let Some((dot_git_abs_path, path_in_git_dir)) = dot_git_paths {
4032 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)) {
4033 log::debug!("ignoring event {abs_path:?} as it's in the .git directory among skipped files or directories");
4034 return false;
4035 }
4036
4037 is_git_related = true;
4038 if !dot_git_abs_paths.contains(&dot_git_abs_path) {
4039 dot_git_abs_paths.push(dot_git_abs_path);
4040 }
4041 }
4042
4043 let relative_path: Arc<Path> =
4044 if let Ok(path) = abs_path.strip_prefix(&root_canonical_path) {
4045 path.into()
4046 } else {
4047 if is_git_related {
4048 log::debug!(
4049 "ignoring event {abs_path:?}, since it's in git dir outside of root path {root_canonical_path:?}",
4050 );
4051 } else {
4052 log::error!(
4053 "ignoring event {abs_path:?} outside of root path {root_canonical_path:?}",
4054 );
4055 }
4056 return false;
4057 };
4058
4059 if abs_path.0.file_name() == Some(*GITIGNORE) {
4060 for (_, repo) in snapshot.git_repositories.iter().filter(|(_, repo)| repo.directory_contains(&relative_path)) {
4061 if !dot_git_abs_paths.iter().any(|dot_git_abs_path| dot_git_abs_path == repo.dot_git_dir_abs_path.as_ref()) {
4062 dot_git_abs_paths.push(repo.dot_git_dir_abs_path.to_path_buf());
4063 }
4064 }
4065 }
4066
4067 let parent_dir_is_loaded = relative_path.parent().map_or(true, |parent| {
4068 snapshot
4069 .entry_for_path(parent)
4070 .map_or(false, |entry| entry.kind == EntryKind::Dir)
4071 });
4072 if !parent_dir_is_loaded {
4073 log::debug!("ignoring event {relative_path:?} within unloaded directory");
4074 return false;
4075 }
4076
4077 if self.settings.is_path_excluded(&relative_path) {
4078 if !is_git_related {
4079 log::debug!("ignoring FS event for excluded path {relative_path:?}");
4080 }
4081 return false;
4082 }
4083
4084 relative_paths.push(relative_path);
4085 true
4086 }
4087 });
4088
4089 if relative_paths.is_empty() && dot_git_abs_paths.is_empty() {
4090 return;
4091 }
4092
4093 self.state.lock().snapshot.scan_id += 1;
4094
4095 let (scan_job_tx, scan_job_rx) = channel::unbounded();
4096 log::debug!("received fs events {:?}", relative_paths);
4097 self.reload_entries_for_paths(
4098 root_path,
4099 root_canonical_path,
4100 &relative_paths,
4101 abs_paths,
4102 Some(scan_job_tx.clone()),
4103 )
4104 .await;
4105
4106 self.update_ignore_statuses(scan_job_tx).await;
4107 self.scan_dirs(false, scan_job_rx).await;
4108
4109 if !dot_git_abs_paths.is_empty() {
4110 self.update_git_repositories(dot_git_abs_paths);
4111 }
4112
4113 {
4114 let mut state = self.state.lock();
4115 state.snapshot.completed_scan_id = state.snapshot.scan_id;
4116 for (_, entry) in mem::take(&mut state.removed_entries) {
4117 state.scanned_dirs.remove(&entry.id);
4118 }
4119 }
4120 self.send_status_update(false, SmallVec::new());
4121 // send_status_update_inner(phase, state, status_update_tx, false, SmallVec::new());
4122 }
4123
4124 async fn forcibly_load_paths(&self, paths: &[Arc<Path>]) -> bool {
4125 let (scan_job_tx, scan_job_rx) = channel::unbounded();
4126 {
4127 let mut state = self.state.lock();
4128 let root_path = state.snapshot.abs_path.clone();
4129 for path in paths {
4130 for ancestor in path.ancestors() {
4131 if let Some(entry) = state.snapshot.entry_for_path(ancestor) {
4132 if entry.kind == EntryKind::UnloadedDir {
4133 let abs_path = root_path.as_path().join(ancestor);
4134 state.enqueue_scan_dir(abs_path.into(), entry, &scan_job_tx);
4135 state.paths_to_scan.insert(path.clone());
4136 break;
4137 }
4138 }
4139 }
4140 }
4141 drop(scan_job_tx);
4142 }
4143 while let Ok(job) = scan_job_rx.recv().await {
4144 self.scan_dir(&job).await.log_err();
4145 }
4146
4147 !mem::take(&mut self.state.lock().paths_to_scan).is_empty()
4148 }
4149
4150 async fn scan_dirs(
4151 &self,
4152 enable_progress_updates: bool,
4153 scan_jobs_rx: channel::Receiver<ScanJob>,
4154 ) {
4155 if self
4156 .status_updates_tx
4157 .unbounded_send(ScanState::Started)
4158 .is_err()
4159 {
4160 return;
4161 }
4162
4163 let progress_update_count = AtomicUsize::new(0);
4164 self.executor
4165 .scoped(|scope| {
4166 for _ in 0..self.executor.num_cpus() {
4167 scope.spawn(async {
4168 let mut last_progress_update_count = 0;
4169 let progress_update_timer = self.progress_timer(enable_progress_updates).fuse();
4170 futures::pin_mut!(progress_update_timer);
4171
4172 loop {
4173 select_biased! {
4174 // Process any path refresh requests before moving on to process
4175 // the scan queue, so that user operations are prioritized.
4176 request = self.next_scan_request().fuse() => {
4177 let Ok(request) = request else { break };
4178 if !self.process_scan_request(request, true).await {
4179 return;
4180 }
4181 }
4182
4183 // Send periodic progress updates to the worktree. Use an atomic counter
4184 // to ensure that only one of the workers sends a progress update after
4185 // the update interval elapses.
4186 _ = progress_update_timer => {
4187 match progress_update_count.compare_exchange(
4188 last_progress_update_count,
4189 last_progress_update_count + 1,
4190 SeqCst,
4191 SeqCst
4192 ) {
4193 Ok(_) => {
4194 last_progress_update_count += 1;
4195 self.send_status_update(true, SmallVec::new());
4196 }
4197 Err(count) => {
4198 last_progress_update_count = count;
4199 }
4200 }
4201 progress_update_timer.set(self.progress_timer(enable_progress_updates).fuse());
4202 }
4203
4204 // Recursively load directories from the file system.
4205 job = scan_jobs_rx.recv().fuse() => {
4206 let Ok(job) = job else { break };
4207 if let Err(err) = self.scan_dir(&job).await {
4208 if job.path.as_ref() != Path::new("") {
4209 log::error!("error scanning directory {:?}: {}", job.abs_path, err);
4210 }
4211 }
4212 }
4213 }
4214 }
4215 });
4216 }
4217 })
4218 .await;
4219 }
4220
4221 fn send_status_update(&self, scanning: bool, barrier: SmallVec<[barrier::Sender; 1]>) -> bool {
4222 let mut state = self.state.lock();
4223 if state.changed_paths.is_empty() && scanning {
4224 return true;
4225 }
4226
4227 let new_snapshot = state.snapshot.clone();
4228 let old_snapshot = mem::replace(&mut state.prev_snapshot, new_snapshot.snapshot.clone());
4229 let changes = build_diff(
4230 self.phase,
4231 &old_snapshot,
4232 &new_snapshot,
4233 &state.changed_paths,
4234 );
4235 state.changed_paths.clear();
4236
4237 self.status_updates_tx
4238 .unbounded_send(ScanState::Updated {
4239 snapshot: new_snapshot,
4240 changes,
4241 scanning,
4242 barrier,
4243 })
4244 .is_ok()
4245 }
4246
4247 async fn scan_dir(&self, job: &ScanJob) -> Result<()> {
4248 let root_abs_path;
4249 let root_char_bag;
4250 {
4251 let snapshot = &self.state.lock().snapshot;
4252 if self.settings.is_path_excluded(&job.path) {
4253 log::error!("skipping excluded directory {:?}", job.path);
4254 return Ok(());
4255 }
4256 log::trace!("scanning directory {:?}", job.path);
4257 root_abs_path = snapshot.abs_path().clone();
4258 root_char_bag = snapshot.root_char_bag;
4259 }
4260
4261 let next_entry_id = self.next_entry_id.clone();
4262 let mut ignore_stack = job.ignore_stack.clone();
4263 let mut new_ignore = None;
4264 let mut root_canonical_path = None;
4265 let mut new_entries: Vec<Entry> = Vec::new();
4266 let mut new_jobs: Vec<Option<ScanJob>> = Vec::new();
4267 let mut child_paths = self
4268 .fs
4269 .read_dir(&job.abs_path)
4270 .await?
4271 .filter_map(|entry| async {
4272 match entry {
4273 Ok(entry) => Some(entry),
4274 Err(error) => {
4275 log::error!("error processing entry {:?}", error);
4276 None
4277 }
4278 }
4279 })
4280 .collect::<Vec<_>>()
4281 .await;
4282
4283 // Ensure that .git and .gitignore are processed first.
4284 swap_to_front(&mut child_paths, *GITIGNORE);
4285 swap_to_front(&mut child_paths, *DOT_GIT);
4286
4287 for child_abs_path in child_paths {
4288 let child_abs_path: Arc<Path> = child_abs_path.into();
4289 let child_name = child_abs_path.file_name().unwrap();
4290 let child_path: Arc<Path> = job.path.join(child_name).into();
4291
4292 if child_name == *DOT_GIT {
4293 let mut state = self.state.lock();
4294 state.insert_git_repository(
4295 child_path.clone(),
4296 self.fs.as_ref(),
4297 self.watcher.as_ref(),
4298 );
4299 } else if child_name == *GITIGNORE {
4300 match build_gitignore(&child_abs_path, self.fs.as_ref()).await {
4301 Ok(ignore) => {
4302 let ignore = Arc::new(ignore);
4303 ignore_stack = ignore_stack.append(job.abs_path.clone(), ignore.clone());
4304 new_ignore = Some(ignore);
4305 }
4306 Err(error) => {
4307 log::error!(
4308 "error loading .gitignore file {:?} - {:?}",
4309 child_name,
4310 error
4311 );
4312 }
4313 }
4314 }
4315
4316 if self.settings.is_path_excluded(&child_path) {
4317 log::debug!("skipping excluded child entry {child_path:?}");
4318 self.state.lock().remove_path(&child_path);
4319 continue;
4320 }
4321
4322 let child_metadata = match self.fs.metadata(&child_abs_path).await {
4323 Ok(Some(metadata)) => metadata,
4324 Ok(None) => continue,
4325 Err(err) => {
4326 log::error!("error processing {child_abs_path:?}: {err:?}");
4327 continue;
4328 }
4329 };
4330
4331 let mut child_entry = Entry::new(
4332 child_path.clone(),
4333 &child_metadata,
4334 &next_entry_id,
4335 root_char_bag,
4336 None,
4337 );
4338
4339 if job.is_external {
4340 child_entry.is_external = true;
4341 } else if child_metadata.is_symlink {
4342 let canonical_path = match self.fs.canonicalize(&child_abs_path).await {
4343 Ok(path) => path,
4344 Err(err) => {
4345 log::error!(
4346 "error reading target of symlink {:?}: {:?}",
4347 child_abs_path,
4348 err
4349 );
4350 continue;
4351 }
4352 };
4353
4354 // lazily canonicalize the root path in order to determine if
4355 // symlinks point outside of the worktree.
4356 let root_canonical_path = match &root_canonical_path {
4357 Some(path) => path,
4358 None => match self.fs.canonicalize(&root_abs_path).await {
4359 Ok(path) => root_canonical_path.insert(path),
4360 Err(err) => {
4361 log::error!("error canonicalizing root {:?}: {:?}", root_abs_path, err);
4362 continue;
4363 }
4364 },
4365 };
4366
4367 if !canonical_path.starts_with(root_canonical_path) {
4368 child_entry.is_external = true;
4369 }
4370
4371 child_entry.canonical_path = Some(canonical_path.into());
4372 }
4373
4374 if child_entry.is_dir() {
4375 child_entry.is_ignored = ignore_stack.is_abs_path_ignored(&child_abs_path, true);
4376 child_entry.is_always_included = self.settings.is_path_always_included(&child_path);
4377
4378 // Avoid recursing until crash in the case of a recursive symlink
4379 if job.ancestor_inodes.contains(&child_entry.inode) {
4380 new_jobs.push(None);
4381 } else {
4382 let mut ancestor_inodes = job.ancestor_inodes.clone();
4383 ancestor_inodes.insert(child_entry.inode);
4384
4385 new_jobs.push(Some(ScanJob {
4386 abs_path: child_abs_path.clone(),
4387 path: child_path,
4388 is_external: child_entry.is_external,
4389 ignore_stack: if child_entry.is_ignored {
4390 IgnoreStack::all()
4391 } else {
4392 ignore_stack.clone()
4393 },
4394 ancestor_inodes,
4395 scan_queue: job.scan_queue.clone(),
4396 }));
4397 }
4398 } else {
4399 child_entry.is_ignored = ignore_stack.is_abs_path_ignored(&child_abs_path, false);
4400 child_entry.is_always_included = self.settings.is_path_always_included(&child_path);
4401 }
4402
4403 {
4404 let relative_path = job.path.join(child_name);
4405 if self.is_path_private(&relative_path) {
4406 log::debug!("detected private file: {relative_path:?}");
4407 child_entry.is_private = true;
4408 }
4409 }
4410
4411 new_entries.push(child_entry);
4412 }
4413
4414 let mut state = self.state.lock();
4415
4416 // Identify any subdirectories that should not be scanned.
4417 let mut job_ix = 0;
4418 for entry in &mut new_entries {
4419 state.reuse_entry_id(entry);
4420 if entry.is_dir() {
4421 if state.should_scan_directory(entry) {
4422 job_ix += 1;
4423 } else {
4424 log::debug!("defer scanning directory {:?}", entry.path);
4425 entry.kind = EntryKind::UnloadedDir;
4426 new_jobs.remove(job_ix);
4427 }
4428 }
4429 if entry.is_always_included {
4430 state
4431 .snapshot
4432 .always_included_entries
4433 .push(entry.path.clone());
4434 }
4435 }
4436
4437 state.populate_dir(&job.path, new_entries, new_ignore);
4438 self.watcher.add(job.abs_path.as_ref()).log_err();
4439
4440 for new_job in new_jobs.into_iter().flatten() {
4441 job.scan_queue
4442 .try_send(new_job)
4443 .expect("channel is unbounded");
4444 }
4445
4446 Ok(())
4447 }
4448
4449 /// All list arguments should be sorted before calling this function
4450 async fn reload_entries_for_paths(
4451 &self,
4452 root_abs_path: SanitizedPath,
4453 root_canonical_path: SanitizedPath,
4454 relative_paths: &[Arc<Path>],
4455 abs_paths: Vec<PathBuf>,
4456 scan_queue_tx: Option<Sender<ScanJob>>,
4457 ) {
4458 // grab metadata for all requested paths
4459 let metadata = futures::future::join_all(
4460 abs_paths
4461 .iter()
4462 .map(|abs_path| async move {
4463 let metadata = self.fs.metadata(abs_path).await?;
4464 if let Some(metadata) = metadata {
4465 let canonical_path = self.fs.canonicalize(abs_path).await?;
4466
4467 // If we're on a case-insensitive filesystem (default on macOS), we want
4468 // to only ignore metadata for non-symlink files if their absolute-path matches
4469 // the canonical-path.
4470 // Because if not, this might be a case-only-renaming (`mv test.txt TEST.TXT`)
4471 // and we want to ignore the metadata for the old path (`test.txt`) so it's
4472 // treated as removed.
4473 if !self.fs_case_sensitive && !metadata.is_symlink {
4474 let canonical_file_name = canonical_path.file_name();
4475 let file_name = abs_path.file_name();
4476 if canonical_file_name != file_name {
4477 return Ok(None);
4478 }
4479 }
4480
4481 anyhow::Ok(Some((metadata, SanitizedPath::from(canonical_path))))
4482 } else {
4483 Ok(None)
4484 }
4485 })
4486 .collect::<Vec<_>>(),
4487 )
4488 .await;
4489
4490 let mut state = self.state.lock();
4491 let doing_recursive_update = scan_queue_tx.is_some();
4492
4493 // Remove any entries for paths that no longer exist or are being recursively
4494 // refreshed. Do this before adding any new entries, so that renames can be
4495 // detected regardless of the order of the paths.
4496 for (path, metadata) in relative_paths.iter().zip(metadata.iter()) {
4497 if matches!(metadata, Ok(None)) || doing_recursive_update {
4498 log::trace!("remove path {:?}", path);
4499 state.remove_path(path);
4500 }
4501 }
4502
4503 for (path, metadata) in relative_paths.iter().zip(metadata.into_iter()) {
4504 let abs_path: Arc<Path> = root_abs_path.as_path().join(path).into();
4505 match metadata {
4506 Ok(Some((metadata, canonical_path))) => {
4507 let ignore_stack = state
4508 .snapshot
4509 .ignore_stack_for_abs_path(&abs_path, metadata.is_dir);
4510 let is_external = !canonical_path.starts_with(&root_canonical_path);
4511 let mut fs_entry = Entry::new(
4512 path.clone(),
4513 &metadata,
4514 self.next_entry_id.as_ref(),
4515 state.snapshot.root_char_bag,
4516 if metadata.is_symlink {
4517 Some(canonical_path.as_path().to_path_buf().into())
4518 } else {
4519 None
4520 },
4521 );
4522
4523 let is_dir = fs_entry.is_dir();
4524 fs_entry.is_ignored = ignore_stack.is_abs_path_ignored(&abs_path, is_dir);
4525 fs_entry.is_external = is_external;
4526 fs_entry.is_private = self.is_path_private(path);
4527 fs_entry.is_always_included = self.settings.is_path_always_included(path);
4528
4529 if let (Some(scan_queue_tx), true) = (&scan_queue_tx, is_dir) {
4530 if state.should_scan_directory(&fs_entry)
4531 || (fs_entry.path.as_os_str().is_empty()
4532 && abs_path.file_name() == Some(*DOT_GIT))
4533 {
4534 state.enqueue_scan_dir(abs_path, &fs_entry, scan_queue_tx);
4535 } else {
4536 fs_entry.kind = EntryKind::UnloadedDir;
4537 }
4538 }
4539
4540 state.insert_entry(fs_entry.clone(), self.fs.as_ref(), self.watcher.as_ref());
4541 }
4542 Ok(None) => {
4543 self.remove_repo_path(path, &mut state.snapshot);
4544 }
4545 Err(err) => {
4546 log::error!("error reading file {abs_path:?} on event: {err:#}");
4547 }
4548 }
4549 }
4550
4551 util::extend_sorted(
4552 &mut state.changed_paths,
4553 relative_paths.iter().cloned(),
4554 usize::MAX,
4555 Ord::cmp,
4556 );
4557 }
4558
4559 fn remove_repo_path(&self, path: &Arc<Path>, snapshot: &mut LocalSnapshot) -> Option<()> {
4560 if !path
4561 .components()
4562 .any(|component| component.as_os_str() == *DOT_GIT)
4563 {
4564 if let Some(local_repo) = snapshot.local_repo_for_work_directory_path(path) {
4565 let id = local_repo.work_directory_id;
4566 log::debug!("remove repo path: {:?}", path);
4567 snapshot.git_repositories.remove(&id);
4568 return Some(());
4569 }
4570 }
4571
4572 Some(())
4573 }
4574
4575 async fn update_ignore_statuses(&self, scan_job_tx: Sender<ScanJob>) {
4576 let mut ignores_to_update = Vec::new();
4577 let (ignore_queue_tx, ignore_queue_rx) = channel::unbounded();
4578 let prev_snapshot;
4579 {
4580 let snapshot = &mut self.state.lock().snapshot;
4581 let abs_path = snapshot.abs_path.clone();
4582 snapshot
4583 .ignores_by_parent_abs_path
4584 .retain(|parent_abs_path, (_, needs_update)| {
4585 if let Ok(parent_path) = parent_abs_path.strip_prefix(abs_path.as_path()) {
4586 if *needs_update {
4587 *needs_update = false;
4588 if snapshot.snapshot.entry_for_path(parent_path).is_some() {
4589 ignores_to_update.push(parent_abs_path.clone());
4590 }
4591 }
4592
4593 let ignore_path = parent_path.join(*GITIGNORE);
4594 if snapshot.snapshot.entry_for_path(ignore_path).is_none() {
4595 return false;
4596 }
4597 }
4598 true
4599 });
4600
4601 ignores_to_update.sort_unstable();
4602 let mut ignores_to_update = ignores_to_update.into_iter().peekable();
4603 while let Some(parent_abs_path) = ignores_to_update.next() {
4604 while ignores_to_update
4605 .peek()
4606 .map_or(false, |p| p.starts_with(&parent_abs_path))
4607 {
4608 ignores_to_update.next().unwrap();
4609 }
4610
4611 let ignore_stack = snapshot.ignore_stack_for_abs_path(&parent_abs_path, true);
4612 ignore_queue_tx
4613 .send_blocking(UpdateIgnoreStatusJob {
4614 abs_path: parent_abs_path,
4615 ignore_stack,
4616 ignore_queue: ignore_queue_tx.clone(),
4617 scan_queue: scan_job_tx.clone(),
4618 })
4619 .unwrap();
4620 }
4621
4622 prev_snapshot = snapshot.clone();
4623 }
4624 drop(ignore_queue_tx);
4625
4626 self.executor
4627 .scoped(|scope| {
4628 for _ in 0..self.executor.num_cpus() {
4629 scope.spawn(async {
4630 loop {
4631 select_biased! {
4632 // Process any path refresh requests before moving on to process
4633 // the queue of ignore statuses.
4634 request = self.next_scan_request().fuse() => {
4635 let Ok(request) = request else { break };
4636 if !self.process_scan_request(request, true).await {
4637 return;
4638 }
4639 }
4640
4641 // Recursively process directories whose ignores have changed.
4642 job = ignore_queue_rx.recv().fuse() => {
4643 let Ok(job) = job else { break };
4644 self.update_ignore_status(job, &prev_snapshot).await;
4645 }
4646 }
4647 }
4648 });
4649 }
4650 })
4651 .await;
4652 }
4653
4654 async fn update_ignore_status(&self, job: UpdateIgnoreStatusJob, snapshot: &LocalSnapshot) {
4655 log::trace!("update ignore status {:?}", job.abs_path);
4656
4657 let mut ignore_stack = job.ignore_stack;
4658 if let Some((ignore, _)) = snapshot.ignores_by_parent_abs_path.get(&job.abs_path) {
4659 ignore_stack = ignore_stack.append(job.abs_path.clone(), ignore.clone());
4660 }
4661
4662 let mut entries_by_id_edits = Vec::new();
4663 let mut entries_by_path_edits = Vec::new();
4664 let path = job
4665 .abs_path
4666 .strip_prefix(snapshot.abs_path.as_path())
4667 .unwrap();
4668
4669 for mut entry in snapshot.child_entries(path).cloned() {
4670 let was_ignored = entry.is_ignored;
4671 let abs_path: Arc<Path> = snapshot.abs_path().join(&entry.path).into();
4672 entry.is_ignored = ignore_stack.is_abs_path_ignored(&abs_path, entry.is_dir());
4673
4674 if entry.is_dir() {
4675 let child_ignore_stack = if entry.is_ignored {
4676 IgnoreStack::all()
4677 } else {
4678 ignore_stack.clone()
4679 };
4680
4681 // Scan any directories that were previously ignored and weren't previously scanned.
4682 if was_ignored && !entry.is_ignored && entry.kind.is_unloaded() {
4683 let state = self.state.lock();
4684 if state.should_scan_directory(&entry) {
4685 state.enqueue_scan_dir(abs_path.clone(), &entry, &job.scan_queue);
4686 }
4687 }
4688
4689 job.ignore_queue
4690 .send(UpdateIgnoreStatusJob {
4691 abs_path: abs_path.clone(),
4692 ignore_stack: child_ignore_stack,
4693 ignore_queue: job.ignore_queue.clone(),
4694 scan_queue: job.scan_queue.clone(),
4695 })
4696 .await
4697 .unwrap();
4698 }
4699
4700 if entry.is_ignored != was_ignored {
4701 let mut path_entry = snapshot.entries_by_id.get(&entry.id, &()).unwrap().clone();
4702 path_entry.scan_id = snapshot.scan_id;
4703 path_entry.is_ignored = entry.is_ignored;
4704 entries_by_id_edits.push(Edit::Insert(path_entry));
4705 entries_by_path_edits.push(Edit::Insert(entry));
4706 }
4707 }
4708
4709 let state = &mut self.state.lock();
4710 for edit in &entries_by_path_edits {
4711 if let Edit::Insert(entry) = edit {
4712 if let Err(ix) = state.changed_paths.binary_search(&entry.path) {
4713 state.changed_paths.insert(ix, entry.path.clone());
4714 }
4715 }
4716 }
4717
4718 state
4719 .snapshot
4720 .entries_by_path
4721 .edit(entries_by_path_edits, &());
4722 state.snapshot.entries_by_id.edit(entries_by_id_edits, &());
4723 }
4724
4725 fn update_git_repositories(&self, dot_git_paths: Vec<PathBuf>) {
4726 log::trace!("reloading repositories: {dot_git_paths:?}");
4727 let mut state = self.state.lock();
4728 let scan_id = state.snapshot.scan_id;
4729 for dot_git_dir in dot_git_paths {
4730 let existing_repository_entry =
4731 state
4732 .snapshot
4733 .git_repositories
4734 .iter()
4735 .find_map(|(_, repo)| {
4736 if repo.dot_git_dir_abs_path.as_ref() == &dot_git_dir
4737 || repo.dot_git_worktree_abs_path.as_deref() == Some(&dot_git_dir)
4738 {
4739 Some(repo.clone())
4740 } else {
4741 None
4742 }
4743 });
4744
4745 match existing_repository_entry {
4746 None => {
4747 let Ok(relative) = dot_git_dir.strip_prefix(state.snapshot.abs_path()) else {
4748 return;
4749 };
4750 state.insert_git_repository(
4751 relative.into(),
4752 self.fs.as_ref(),
4753 self.watcher.as_ref(),
4754 );
4755 }
4756 Some(local_repository) => {
4757 state.snapshot.git_repositories.update(
4758 &local_repository.work_directory_id,
4759 |entry| {
4760 entry.git_dir_scan_id = scan_id;
4761 },
4762 );
4763 }
4764 };
4765 }
4766
4767 // Remove any git repositories whose .git entry no longer exists.
4768 let snapshot = &mut state.snapshot;
4769 let mut ids_to_preserve = HashSet::default();
4770 for (&work_directory_id, entry) in snapshot.git_repositories.iter() {
4771 let exists_in_snapshot = snapshot
4772 .entry_for_id(work_directory_id)
4773 .map_or(false, |entry| {
4774 snapshot.entry_for_path(entry.path.join(*DOT_GIT)).is_some()
4775 });
4776
4777 if exists_in_snapshot
4778 || matches!(
4779 smol::block_on(self.fs.metadata(&entry.dot_git_dir_abs_path)),
4780 Ok(Some(_))
4781 )
4782 {
4783 ids_to_preserve.insert(work_directory_id);
4784 }
4785 }
4786
4787 snapshot
4788 .git_repositories
4789 .retain(|work_directory_id, _| ids_to_preserve.contains(work_directory_id));
4790 }
4791
4792 async fn progress_timer(&self, running: bool) {
4793 if !running {
4794 return futures::future::pending().await;
4795 }
4796
4797 #[cfg(any(test, feature = "test-support"))]
4798 if self.fs.is_fake() {
4799 return self.executor.simulate_random_delay().await;
4800 }
4801
4802 smol::Timer::after(FS_WATCH_LATENCY).await;
4803 }
4804
4805 fn is_path_private(&self, path: &Path) -> bool {
4806 !self.share_private_files && self.settings.is_path_private(path)
4807 }
4808
4809 async fn next_scan_request(&self) -> Result<ScanRequest> {
4810 let mut request = self.scan_requests_rx.recv().await?;
4811 while let Ok(next_request) = self.scan_requests_rx.try_recv() {
4812 request.relative_paths.extend(next_request.relative_paths);
4813 request.done.extend(next_request.done);
4814 }
4815 Ok(request)
4816 }
4817}
4818
4819fn build_diff(
4820 phase: BackgroundScannerPhase,
4821 old_snapshot: &Snapshot,
4822 new_snapshot: &Snapshot,
4823 event_paths: &[Arc<Path>],
4824) -> UpdatedEntriesSet {
4825 use BackgroundScannerPhase::*;
4826 use PathChange::{Added, AddedOrUpdated, Loaded, Removed, Updated};
4827
4828 // Identify which paths have changed. Use the known set of changed
4829 // parent paths to optimize the search.
4830 let mut changes = Vec::new();
4831 let mut old_paths = old_snapshot.entries_by_path.cursor::<PathKey>(&());
4832 let mut new_paths = new_snapshot.entries_by_path.cursor::<PathKey>(&());
4833 let mut last_newly_loaded_dir_path = None;
4834 old_paths.next(&());
4835 new_paths.next(&());
4836 for path in event_paths {
4837 let path = PathKey(path.clone());
4838 if old_paths.item().map_or(false, |e| e.path < path.0) {
4839 old_paths.seek_forward(&path, Bias::Left, &());
4840 }
4841 if new_paths.item().map_or(false, |e| e.path < path.0) {
4842 new_paths.seek_forward(&path, Bias::Left, &());
4843 }
4844 loop {
4845 match (old_paths.item(), new_paths.item()) {
4846 (Some(old_entry), Some(new_entry)) => {
4847 if old_entry.path > path.0
4848 && new_entry.path > path.0
4849 && !old_entry.path.starts_with(&path.0)
4850 && !new_entry.path.starts_with(&path.0)
4851 {
4852 break;
4853 }
4854
4855 match Ord::cmp(&old_entry.path, &new_entry.path) {
4856 Ordering::Less => {
4857 changes.push((old_entry.path.clone(), old_entry.id, Removed));
4858 old_paths.next(&());
4859 }
4860 Ordering::Equal => {
4861 if phase == EventsReceivedDuringInitialScan {
4862 if old_entry.id != new_entry.id {
4863 changes.push((old_entry.path.clone(), old_entry.id, Removed));
4864 }
4865 // If the worktree was not fully initialized when this event was generated,
4866 // we can't know whether this entry was added during the scan or whether
4867 // it was merely updated.
4868 changes.push((
4869 new_entry.path.clone(),
4870 new_entry.id,
4871 AddedOrUpdated,
4872 ));
4873 } else if old_entry.id != new_entry.id {
4874 changes.push((old_entry.path.clone(), old_entry.id, Removed));
4875 changes.push((new_entry.path.clone(), new_entry.id, Added));
4876 } else if old_entry != new_entry {
4877 if old_entry.kind.is_unloaded() {
4878 last_newly_loaded_dir_path = Some(&new_entry.path);
4879 changes.push((new_entry.path.clone(), new_entry.id, Loaded));
4880 } else {
4881 changes.push((new_entry.path.clone(), new_entry.id, Updated));
4882 }
4883 }
4884 old_paths.next(&());
4885 new_paths.next(&());
4886 }
4887 Ordering::Greater => {
4888 let is_newly_loaded = phase == InitialScan
4889 || last_newly_loaded_dir_path
4890 .as_ref()
4891 .map_or(false, |dir| new_entry.path.starts_with(dir));
4892 changes.push((
4893 new_entry.path.clone(),
4894 new_entry.id,
4895 if is_newly_loaded { Loaded } else { Added },
4896 ));
4897 new_paths.next(&());
4898 }
4899 }
4900 }
4901 (Some(old_entry), None) => {
4902 changes.push((old_entry.path.clone(), old_entry.id, Removed));
4903 old_paths.next(&());
4904 }
4905 (None, Some(new_entry)) => {
4906 let is_newly_loaded = phase == InitialScan
4907 || last_newly_loaded_dir_path
4908 .as_ref()
4909 .map_or(false, |dir| new_entry.path.starts_with(dir));
4910 changes.push((
4911 new_entry.path.clone(),
4912 new_entry.id,
4913 if is_newly_loaded { Loaded } else { Added },
4914 ));
4915 new_paths.next(&());
4916 }
4917 (None, None) => break,
4918 }
4919 }
4920 }
4921
4922 changes.into()
4923}
4924
4925fn swap_to_front(child_paths: &mut Vec<PathBuf>, file: &OsStr) {
4926 let position = child_paths
4927 .iter()
4928 .position(|path| path.file_name().unwrap() == file);
4929 if let Some(position) = position {
4930 let temp = child_paths.remove(position);
4931 child_paths.insert(0, temp);
4932 }
4933}
4934
4935fn char_bag_for_path(root_char_bag: CharBag, path: &Path) -> CharBag {
4936 let mut result = root_char_bag;
4937 result.extend(
4938 path.to_string_lossy()
4939 .chars()
4940 .map(|c| c.to_ascii_lowercase()),
4941 );
4942 result
4943}
4944
4945#[derive(Debug)]
4946struct ScanJob {
4947 abs_path: Arc<Path>,
4948 path: Arc<Path>,
4949 ignore_stack: Arc<IgnoreStack>,
4950 scan_queue: Sender<ScanJob>,
4951 ancestor_inodes: TreeSet<u64>,
4952 is_external: bool,
4953}
4954
4955struct UpdateIgnoreStatusJob {
4956 abs_path: Arc<Path>,
4957 ignore_stack: Arc<IgnoreStack>,
4958 ignore_queue: Sender<UpdateIgnoreStatusJob>,
4959 scan_queue: Sender<ScanJob>,
4960}
4961
4962pub trait WorktreeModelHandle {
4963 #[cfg(any(test, feature = "test-support"))]
4964 fn flush_fs_events<'a>(
4965 &self,
4966 cx: &'a mut gpui::TestAppContext,
4967 ) -> futures::future::LocalBoxFuture<'a, ()>;
4968
4969 #[cfg(any(test, feature = "test-support"))]
4970 fn flush_fs_events_in_root_git_repository<'a>(
4971 &self,
4972 cx: &'a mut gpui::TestAppContext,
4973 ) -> futures::future::LocalBoxFuture<'a, ()>;
4974}
4975
4976impl WorktreeModelHandle for Entity<Worktree> {
4977 // When the worktree's FS event stream sometimes delivers "redundant" events for FS changes that
4978 // occurred before the worktree was constructed. These events can cause the worktree to perform
4979 // extra directory scans, and emit extra scan-state notifications.
4980 //
4981 // This function mutates the worktree's directory and waits for those mutations to be picked up,
4982 // to ensure that all redundant FS events have already been processed.
4983 #[cfg(any(test, feature = "test-support"))]
4984 fn flush_fs_events<'a>(
4985 &self,
4986 cx: &'a mut gpui::TestAppContext,
4987 ) -> futures::future::LocalBoxFuture<'a, ()> {
4988 let file_name = "fs-event-sentinel";
4989
4990 let tree = self.clone();
4991 let (fs, root_path) = self.update(cx, |tree, _| {
4992 let tree = tree.as_local().unwrap();
4993 (tree.fs.clone(), tree.abs_path().clone())
4994 });
4995
4996 async move {
4997 fs.create_file(&root_path.join(file_name), Default::default())
4998 .await
4999 .unwrap();
5000
5001 let mut events = cx.events(&tree);
5002 while events.next().await.is_some() {
5003 if tree.update(cx, |tree, _| tree.entry_for_path(file_name).is_some()) {
5004 break;
5005 }
5006 }
5007
5008 fs.remove_file(&root_path.join(file_name), Default::default())
5009 .await
5010 .unwrap();
5011 while events.next().await.is_some() {
5012 if tree.update(cx, |tree, _| tree.entry_for_path(file_name).is_none()) {
5013 break;
5014 }
5015 }
5016
5017 cx.update(|cx| tree.read(cx).as_local().unwrap().scan_complete())
5018 .await;
5019 }
5020 .boxed_local()
5021 }
5022
5023 // This function is similar to flush_fs_events, except that it waits for events to be flushed in
5024 // the .git folder of the root repository.
5025 // The reason for its existence is that a repository's .git folder might live *outside* of the
5026 // worktree and thus its FS events might go through a different path.
5027 // In order to flush those, we need to create artificial events in the .git folder and wait
5028 // for the repository to be reloaded.
5029 #[cfg(any(test, feature = "test-support"))]
5030 fn flush_fs_events_in_root_git_repository<'a>(
5031 &self,
5032 cx: &'a mut gpui::TestAppContext,
5033 ) -> futures::future::LocalBoxFuture<'a, ()> {
5034 let file_name = "fs-event-sentinel";
5035
5036 let tree = self.clone();
5037 let (fs, root_path, mut git_dir_scan_id) = self.update(cx, |tree, _| {
5038 let tree = tree.as_local().unwrap();
5039 let local_repo_entry = tree
5040 .git_repositories
5041 .values()
5042 .min_by_key(|local_repo_entry| local_repo_entry.work_directory.clone())
5043 .unwrap();
5044 (
5045 tree.fs.clone(),
5046 local_repo_entry.dot_git_dir_abs_path.clone(),
5047 local_repo_entry.git_dir_scan_id,
5048 )
5049 });
5050
5051 let scan_id_increased = |tree: &mut Worktree, git_dir_scan_id: &mut usize| {
5052 let tree = tree.as_local().unwrap();
5053 // let repository = tree.repositories.first().unwrap();
5054 let local_repo_entry = tree
5055 .git_repositories
5056 .values()
5057 .min_by_key(|local_repo_entry| local_repo_entry.work_directory.clone())
5058 .unwrap();
5059
5060 if local_repo_entry.git_dir_scan_id > *git_dir_scan_id {
5061 *git_dir_scan_id = local_repo_entry.git_dir_scan_id;
5062 true
5063 } else {
5064 false
5065 }
5066 };
5067
5068 async move {
5069 fs.create_file(&root_path.join(file_name), Default::default())
5070 .await
5071 .unwrap();
5072
5073 let mut events = cx.events(&tree);
5074 while events.next().await.is_some() {
5075 if tree.update(cx, |tree, _| scan_id_increased(tree, &mut git_dir_scan_id)) {
5076 break;
5077 }
5078 }
5079
5080 fs.remove_file(&root_path.join(file_name), Default::default())
5081 .await
5082 .unwrap();
5083
5084 while events.next().await.is_some() {
5085 if tree.update(cx, |tree, _| scan_id_increased(tree, &mut git_dir_scan_id)) {
5086 break;
5087 }
5088 }
5089
5090 cx.update(|cx| tree.read(cx).as_local().unwrap().scan_complete())
5091 .await;
5092 }
5093 .boxed_local()
5094 }
5095}
5096
5097#[derive(Clone, Debug)]
5098struct TraversalProgress<'a> {
5099 max_path: &'a Path,
5100 count: usize,
5101 non_ignored_count: usize,
5102 file_count: usize,
5103 non_ignored_file_count: usize,
5104}
5105
5106impl TraversalProgress<'_> {
5107 fn count(&self, include_files: bool, include_dirs: bool, include_ignored: bool) -> usize {
5108 match (include_files, include_dirs, include_ignored) {
5109 (true, true, true) => self.count,
5110 (true, true, false) => self.non_ignored_count,
5111 (true, false, true) => self.file_count,
5112 (true, false, false) => self.non_ignored_file_count,
5113 (false, true, true) => self.count - self.file_count,
5114 (false, true, false) => self.non_ignored_count - self.non_ignored_file_count,
5115 (false, false, _) => 0,
5116 }
5117 }
5118}
5119
5120impl<'a> sum_tree::Dimension<'a, EntrySummary> for TraversalProgress<'a> {
5121 fn zero(_cx: &()) -> Self {
5122 Default::default()
5123 }
5124
5125 fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
5126 self.max_path = summary.max_path.as_ref();
5127 self.count += summary.count;
5128 self.non_ignored_count += summary.non_ignored_count;
5129 self.file_count += summary.file_count;
5130 self.non_ignored_file_count += summary.non_ignored_file_count;
5131 }
5132}
5133
5134impl Default for TraversalProgress<'_> {
5135 fn default() -> Self {
5136 Self {
5137 max_path: Path::new(""),
5138 count: 0,
5139 non_ignored_count: 0,
5140 file_count: 0,
5141 non_ignored_file_count: 0,
5142 }
5143 }
5144}
5145
5146#[derive(Debug)]
5147pub struct Traversal<'a> {
5148 snapshot: &'a Snapshot,
5149 cursor: sum_tree::Cursor<'a, Entry, TraversalProgress<'a>>,
5150 include_ignored: bool,
5151 include_files: bool,
5152 include_dirs: bool,
5153}
5154
5155impl<'a> Traversal<'a> {
5156 fn new(
5157 snapshot: &'a Snapshot,
5158 include_files: bool,
5159 include_dirs: bool,
5160 include_ignored: bool,
5161 start_path: &Path,
5162 ) -> Self {
5163 let mut cursor = snapshot.entries_by_path.cursor(&());
5164 cursor.seek(&TraversalTarget::path(start_path), Bias::Left, &());
5165 let mut traversal = Self {
5166 snapshot,
5167 cursor,
5168 include_files,
5169 include_dirs,
5170 include_ignored,
5171 };
5172 if traversal.end_offset() == traversal.start_offset() {
5173 traversal.next();
5174 }
5175 traversal
5176 }
5177
5178 pub fn advance(&mut self) -> bool {
5179 self.advance_by(1)
5180 }
5181
5182 pub fn advance_by(&mut self, count: usize) -> bool {
5183 self.cursor.seek_forward(
5184 &TraversalTarget::Count {
5185 count: self.end_offset() + count,
5186 include_dirs: self.include_dirs,
5187 include_files: self.include_files,
5188 include_ignored: self.include_ignored,
5189 },
5190 Bias::Left,
5191 &(),
5192 )
5193 }
5194
5195 pub fn advance_to_sibling(&mut self) -> bool {
5196 while let Some(entry) = self.cursor.item() {
5197 self.cursor
5198 .seek_forward(&TraversalTarget::successor(&entry.path), Bias::Left, &());
5199 if let Some(entry) = self.cursor.item() {
5200 if (self.include_files || !entry.is_file())
5201 && (self.include_dirs || !entry.is_dir())
5202 && (self.include_ignored || !entry.is_ignored || entry.is_always_included)
5203 {
5204 return true;
5205 }
5206 }
5207 }
5208 false
5209 }
5210
5211 pub fn back_to_parent(&mut self) -> bool {
5212 let Some(parent_path) = self.cursor.item().and_then(|entry| entry.path.parent()) else {
5213 return false;
5214 };
5215 self.cursor
5216 .seek(&TraversalTarget::path(parent_path), Bias::Left, &())
5217 }
5218
5219 pub fn entry(&self) -> Option<&'a Entry> {
5220 self.cursor.item()
5221 }
5222
5223 pub fn snapshot(&self) -> &'a Snapshot {
5224 self.snapshot
5225 }
5226
5227 pub fn start_offset(&self) -> usize {
5228 self.cursor
5229 .start()
5230 .count(self.include_files, self.include_dirs, self.include_ignored)
5231 }
5232
5233 pub fn end_offset(&self) -> usize {
5234 self.cursor
5235 .end(&())
5236 .count(self.include_files, self.include_dirs, self.include_ignored)
5237 }
5238}
5239
5240impl<'a> Iterator for Traversal<'a> {
5241 type Item = &'a Entry;
5242
5243 fn next(&mut self) -> Option<Self::Item> {
5244 if let Some(item) = self.entry() {
5245 self.advance();
5246 Some(item)
5247 } else {
5248 None
5249 }
5250 }
5251}
5252
5253#[derive(Debug, Clone, Copy)]
5254pub enum PathTarget<'a> {
5255 Path(&'a Path),
5256 Successor(&'a Path),
5257}
5258
5259impl PathTarget<'_> {
5260 fn cmp_path(&self, other: &Path) -> Ordering {
5261 match self {
5262 PathTarget::Path(path) => path.cmp(&other),
5263 PathTarget::Successor(path) => {
5264 if other.starts_with(path) {
5265 Ordering::Greater
5266 } else {
5267 Ordering::Equal
5268 }
5269 }
5270 }
5271 }
5272}
5273
5274impl<'a, S: Summary> SeekTarget<'a, PathSummary<S>, PathProgress<'a>> for PathTarget<'_> {
5275 fn cmp(&self, cursor_location: &PathProgress<'a>, _: &S::Context) -> Ordering {
5276 self.cmp_path(&cursor_location.max_path)
5277 }
5278}
5279
5280impl<'a, S: Summary> SeekTarget<'a, PathSummary<S>, TraversalProgress<'a>> for PathTarget<'_> {
5281 fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: &S::Context) -> Ordering {
5282 self.cmp_path(&cursor_location.max_path)
5283 }
5284}
5285
5286#[derive(Debug)]
5287enum TraversalTarget<'a> {
5288 Path(PathTarget<'a>),
5289 Count {
5290 count: usize,
5291 include_files: bool,
5292 include_ignored: bool,
5293 include_dirs: bool,
5294 },
5295}
5296
5297impl<'a> TraversalTarget<'a> {
5298 fn path(path: &'a Path) -> Self {
5299 Self::Path(PathTarget::Path(path))
5300 }
5301
5302 fn successor(path: &'a Path) -> Self {
5303 Self::Path(PathTarget::Successor(path))
5304 }
5305
5306 fn cmp_progress(&self, progress: &TraversalProgress) -> Ordering {
5307 match self {
5308 TraversalTarget::Path(path) => path.cmp_path(&progress.max_path),
5309 TraversalTarget::Count {
5310 count,
5311 include_files,
5312 include_dirs,
5313 include_ignored,
5314 } => Ord::cmp(
5315 count,
5316 &progress.count(*include_files, *include_dirs, *include_ignored),
5317 ),
5318 }
5319 }
5320}
5321
5322impl<'a> SeekTarget<'a, EntrySummary, TraversalProgress<'a>> for TraversalTarget<'_> {
5323 fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: &()) -> Ordering {
5324 self.cmp_progress(cursor_location)
5325 }
5326}
5327
5328impl<'a> SeekTarget<'a, PathSummary<Unit>, TraversalProgress<'a>> for TraversalTarget<'_> {
5329 fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: &()) -> Ordering {
5330 self.cmp_progress(cursor_location)
5331 }
5332}
5333
5334pub struct ChildEntriesOptions {
5335 pub include_files: bool,
5336 pub include_dirs: bool,
5337 pub include_ignored: bool,
5338}
5339
5340pub struct ChildEntriesIter<'a> {
5341 parent_path: &'a Path,
5342 traversal: Traversal<'a>,
5343}
5344
5345impl<'a> Iterator for ChildEntriesIter<'a> {
5346 type Item = &'a Entry;
5347
5348 fn next(&mut self) -> Option<Self::Item> {
5349 if let Some(item) = self.traversal.entry() {
5350 if item.path.starts_with(self.parent_path) {
5351 self.traversal.advance_to_sibling();
5352 return Some(item);
5353 }
5354 }
5355 None
5356 }
5357}
5358
5359impl<'a> From<&'a Entry> for proto::Entry {
5360 fn from(entry: &'a Entry) -> Self {
5361 Self {
5362 id: entry.id.to_proto(),
5363 is_dir: entry.is_dir(),
5364 path: entry.path.as_ref().to_proto(),
5365 inode: entry.inode,
5366 mtime: entry.mtime.map(|time| time.into()),
5367 is_ignored: entry.is_ignored,
5368 is_external: entry.is_external,
5369 is_fifo: entry.is_fifo,
5370 size: Some(entry.size),
5371 canonical_path: entry
5372 .canonical_path
5373 .as_ref()
5374 .map(|path| path.as_ref().to_proto()),
5375 }
5376 }
5377}
5378
5379impl<'a> TryFrom<(&'a CharBag, &PathMatcher, proto::Entry)> for Entry {
5380 type Error = anyhow::Error;
5381
5382 fn try_from(
5383 (root_char_bag, always_included, entry): (&'a CharBag, &PathMatcher, proto::Entry),
5384 ) -> Result<Self> {
5385 let kind = if entry.is_dir {
5386 EntryKind::Dir
5387 } else {
5388 EntryKind::File
5389 };
5390
5391 let path = Arc::<Path>::from_proto(entry.path);
5392 let char_bag = char_bag_for_path(*root_char_bag, &path);
5393 let is_always_included = always_included.is_match(path.as_ref());
5394 Ok(Entry {
5395 id: ProjectEntryId::from_proto(entry.id),
5396 kind,
5397 path,
5398 inode: entry.inode,
5399 mtime: entry.mtime.map(|time| time.into()),
5400 size: entry.size.unwrap_or(0),
5401 canonical_path: entry
5402 .canonical_path
5403 .map(|path_string| Arc::from(PathBuf::from_proto(path_string))),
5404 is_ignored: entry.is_ignored,
5405 is_always_included,
5406 is_external: entry.is_external,
5407 is_private: false,
5408 char_bag,
5409 is_fifo: entry.is_fifo,
5410 })
5411 }
5412}
5413
5414#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
5415pub struct ProjectEntryId(usize);
5416
5417impl ProjectEntryId {
5418 pub const MAX: Self = Self(usize::MAX);
5419 pub const MIN: Self = Self(usize::MIN);
5420
5421 pub fn new(counter: &AtomicUsize) -> Self {
5422 Self(counter.fetch_add(1, SeqCst))
5423 }
5424
5425 pub fn from_proto(id: u64) -> Self {
5426 Self(id as usize)
5427 }
5428
5429 pub fn to_proto(&self) -> u64 {
5430 self.0 as u64
5431 }
5432
5433 pub fn to_usize(&self) -> usize {
5434 self.0
5435 }
5436}
5437
5438#[cfg(any(test, feature = "test-support"))]
5439impl CreatedEntry {
5440 pub fn to_included(self) -> Option<Entry> {
5441 match self {
5442 CreatedEntry::Included(entry) => Some(entry),
5443 CreatedEntry::Excluded { .. } => None,
5444 }
5445 }
5446}