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