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