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