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