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