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