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