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