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