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