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