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