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