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