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