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