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