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