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