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_str(&self) -> &str {
2470 self.root_name.as_unix_str()
2471 }
2472
2473 pub fn scan_id(&self) -> usize {
2474 self.scan_id
2475 }
2476
2477 pub fn entry_for_path(&self, path: &RelPath) -> Option<&Entry> {
2478 self.traverse_from_path(true, true, true, path)
2479 .entry()
2480 .and_then(|entry| {
2481 if entry.path.as_ref() == path {
2482 Some(entry)
2483 } else {
2484 None
2485 }
2486 })
2487 }
2488
2489 /// Resolves a path to an executable using the following heuristics:
2490 ///
2491 /// 1. If the path starts with `~`, it is expanded to the user's home directory.
2492 /// 2. If the path is relative and contains more than one component,
2493 /// it is joined to the worktree root path.
2494 /// 3. If the path is relative and exists in the worktree
2495 /// (even if falls under an exclusion filter),
2496 /// it is joined to the worktree root path.
2497 /// 4. Otherwise the path is returned unmodified.
2498 ///
2499 /// Relative paths that do not exist in the worktree may
2500 /// still be found using the `PATH` environment variable.
2501 pub fn resolve_relative_path(&self, path: PathBuf) -> PathBuf {
2502 if let Some(path_str) = path.to_str() {
2503 if let Some(remaining_path) = path_str.strip_prefix("~/") {
2504 return home_dir().join(remaining_path);
2505 } else if path_str == "~" {
2506 return home_dir().to_path_buf();
2507 }
2508 }
2509
2510 if let Ok(rel_path) = RelPath::new(&path, self.path_style)
2511 && (path.components().count() > 1 || self.entry_for_path(&rel_path).is_some())
2512 {
2513 self.abs_path().join(path)
2514 } else {
2515 path
2516 }
2517 }
2518
2519 pub fn entry_for_id(&self, id: ProjectEntryId) -> Option<&Entry> {
2520 let entry = self.entries_by_id.get(&id, ())?;
2521 self.entry_for_path(&entry.path)
2522 }
2523
2524 pub fn path_style(&self) -> PathStyle {
2525 self.path_style
2526 }
2527}
2528
2529impl LocalSnapshot {
2530 fn local_repo_for_work_directory_path(&self, path: &RelPath) -> Option<&LocalRepositoryEntry> {
2531 self.git_repositories
2532 .iter()
2533 .map(|(_, entry)| entry)
2534 .find(|entry| entry.work_directory.path_key() == PathKey(path.into()))
2535 }
2536
2537 fn build_update(
2538 &self,
2539 project_id: u64,
2540 worktree_id: u64,
2541 entry_changes: UpdatedEntriesSet,
2542 ) -> proto::UpdateWorktree {
2543 let mut updated_entries = Vec::new();
2544 let mut removed_entries = Vec::new();
2545
2546 for (_, entry_id, path_change) in entry_changes.iter() {
2547 if let PathChange::Removed = path_change {
2548 removed_entries.push(entry_id.0 as u64);
2549 } else if let Some(entry) = self.entry_for_id(*entry_id) {
2550 updated_entries.push(proto::Entry::from(entry));
2551 }
2552 }
2553
2554 removed_entries.sort_unstable();
2555 updated_entries.sort_unstable_by_key(|e| e.id);
2556
2557 // TODO - optimize, knowing that removed_entries are sorted.
2558 removed_entries.retain(|id| updated_entries.binary_search_by_key(id, |e| e.id).is_err());
2559
2560 proto::UpdateWorktree {
2561 project_id,
2562 worktree_id,
2563 abs_path: self.abs_path().to_string_lossy().into_owned(),
2564 root_name: self.root_name().to_proto(),
2565 updated_entries,
2566 removed_entries,
2567 scan_id: self.scan_id as u64,
2568 is_last_update: self.completed_scan_id == self.scan_id,
2569 // Sent in separate messages.
2570 updated_repositories: Vec::new(),
2571 removed_repositories: Vec::new(),
2572 }
2573 }
2574
2575 async fn insert_entry(&mut self, mut entry: Entry, fs: &dyn Fs) -> Entry {
2576 log::trace!("insert entry {:?}", entry.path);
2577 if entry.is_file() && entry.path.file_name() == Some(&GITIGNORE) {
2578 let abs_path = self.absolutize(&entry.path);
2579 match build_gitignore(&abs_path, fs).await {
2580 Ok(ignore) => {
2581 self.ignores_by_parent_abs_path
2582 .insert(abs_path.parent().unwrap().into(), (Arc::new(ignore), true));
2583 }
2584 Err(error) => {
2585 log::error!(
2586 "error loading .gitignore file {:?} - {:?}",
2587 &entry.path,
2588 error
2589 );
2590 }
2591 }
2592 }
2593
2594 if entry.kind == EntryKind::PendingDir
2595 && let Some(existing_entry) = self.entries_by_path.get(&PathKey(entry.path.clone()), ())
2596 {
2597 entry.kind = existing_entry.kind;
2598 }
2599
2600 let scan_id = self.scan_id;
2601 let removed = self.entries_by_path.insert_or_replace(entry.clone(), ());
2602 if let Some(removed) = removed
2603 && removed.id != entry.id
2604 {
2605 self.entries_by_id.remove(&removed.id, ());
2606 }
2607 self.entries_by_id.insert_or_replace(
2608 PathEntry {
2609 id: entry.id,
2610 path: entry.path.clone(),
2611 is_ignored: entry.is_ignored,
2612 scan_id,
2613 },
2614 (),
2615 );
2616
2617 entry
2618 }
2619
2620 fn ancestor_inodes_for_path(&self, path: &RelPath) -> TreeSet<u64> {
2621 let mut inodes = TreeSet::default();
2622 for ancestor in path.ancestors().skip(1) {
2623 if let Some(entry) = self.entry_for_path(ancestor) {
2624 inodes.insert(entry.inode);
2625 }
2626 }
2627 inodes
2628 }
2629
2630 async fn ignore_stack_for_abs_path(
2631 &self,
2632 abs_path: &Path,
2633 is_dir: bool,
2634 fs: &dyn Fs,
2635 ) -> IgnoreStack {
2636 let mut new_ignores = Vec::new();
2637 let mut repo_root = None;
2638 for (index, ancestor) in abs_path.ancestors().enumerate() {
2639 if index > 0 {
2640 if let Some((ignore, _)) = self.ignores_by_parent_abs_path.get(ancestor) {
2641 new_ignores.push((ancestor, Some(ignore.clone())));
2642 } else {
2643 new_ignores.push((ancestor, None));
2644 }
2645 }
2646
2647 let metadata = fs.metadata(&ancestor.join(DOT_GIT)).await.ok().flatten();
2648 if metadata.is_some() {
2649 repo_root = Some(Arc::from(ancestor));
2650 break;
2651 }
2652 }
2653
2654 let mut ignore_stack = if let Some(global_gitignore) = self.global_gitignore.clone() {
2655 IgnoreStack::global(global_gitignore)
2656 } else {
2657 IgnoreStack::none()
2658 };
2659
2660 if let Some((repo_exclude, _)) = repo_root
2661 .as_ref()
2662 .and_then(|abs_path| self.repo_exclude_by_work_dir_abs_path.get(abs_path))
2663 {
2664 ignore_stack = ignore_stack.append(IgnoreKind::RepoExclude, repo_exclude.clone());
2665 }
2666 ignore_stack.repo_root = repo_root;
2667 for (parent_abs_path, ignore) in new_ignores.into_iter().rev() {
2668 if ignore_stack.is_abs_path_ignored(parent_abs_path, true) {
2669 ignore_stack = IgnoreStack::all();
2670 break;
2671 } else if let Some(ignore) = ignore {
2672 ignore_stack =
2673 ignore_stack.append(IgnoreKind::Gitignore(parent_abs_path.into()), ignore);
2674 }
2675 }
2676
2677 if ignore_stack.is_abs_path_ignored(abs_path, is_dir) {
2678 ignore_stack = IgnoreStack::all();
2679 }
2680
2681 ignore_stack
2682 }
2683
2684 #[cfg(feature = "test-support")]
2685 pub fn expanded_entries(&self) -> impl Iterator<Item = &Entry> {
2686 self.entries_by_path
2687 .cursor::<()>(())
2688 .filter(|entry| entry.kind == EntryKind::Dir && (entry.is_external || entry.is_ignored))
2689 }
2690
2691 #[cfg(feature = "test-support")]
2692 pub fn check_invariants(&self, git_state: bool) {
2693 use pretty_assertions::assert_eq;
2694
2695 assert_eq!(
2696 self.entries_by_path
2697 .cursor::<()>(())
2698 .map(|e| (&e.path, e.id))
2699 .collect::<Vec<_>>(),
2700 self.entries_by_id
2701 .cursor::<()>(())
2702 .map(|e| (&e.path, e.id))
2703 .collect::<collections::BTreeSet<_>>()
2704 .into_iter()
2705 .collect::<Vec<_>>(),
2706 "entries_by_path and entries_by_id are inconsistent"
2707 );
2708
2709 let mut files = self.files(true, 0);
2710 let mut visible_files = self.files(false, 0);
2711 for entry in self.entries_by_path.cursor::<()>(()) {
2712 if entry.is_file() {
2713 assert_eq!(files.next().unwrap().inode, entry.inode);
2714 if (!entry.is_ignored && !entry.is_external) || entry.is_always_included {
2715 assert_eq!(visible_files.next().unwrap().inode, entry.inode);
2716 }
2717 }
2718 }
2719
2720 assert!(files.next().is_none());
2721 assert!(visible_files.next().is_none());
2722
2723 let mut bfs_paths = Vec::new();
2724 let mut stack = self
2725 .root_entry()
2726 .map(|e| e.path.as_ref())
2727 .into_iter()
2728 .collect::<Vec<_>>();
2729 while let Some(path) = stack.pop() {
2730 bfs_paths.push(path);
2731 let ix = stack.len();
2732 for child_entry in self.child_entries(path) {
2733 stack.insert(ix, &child_entry.path);
2734 }
2735 }
2736
2737 let dfs_paths_via_iter = self
2738 .entries_by_path
2739 .cursor::<()>(())
2740 .map(|e| e.path.as_ref())
2741 .collect::<Vec<_>>();
2742 assert_eq!(bfs_paths, dfs_paths_via_iter);
2743
2744 let dfs_paths_via_traversal = self
2745 .entries(true, 0)
2746 .map(|e| e.path.as_ref())
2747 .collect::<Vec<_>>();
2748
2749 assert_eq!(dfs_paths_via_traversal, dfs_paths_via_iter);
2750
2751 if git_state {
2752 for ignore_parent_abs_path in self.ignores_by_parent_abs_path.keys() {
2753 let ignore_parent_path = &RelPath::new(
2754 ignore_parent_abs_path
2755 .strip_prefix(self.abs_path.as_path())
2756 .unwrap(),
2757 PathStyle::local(),
2758 )
2759 .unwrap();
2760 assert!(self.entry_for_path(ignore_parent_path).is_some());
2761 assert!(
2762 self.entry_for_path(
2763 &ignore_parent_path.join(RelPath::unix(GITIGNORE).unwrap())
2764 )
2765 .is_some()
2766 );
2767 }
2768 }
2769 }
2770
2771 #[cfg(feature = "test-support")]
2772 pub fn entries_without_ids(&self, include_ignored: bool) -> Vec<(&RelPath, u64, bool)> {
2773 let mut paths = Vec::new();
2774 for entry in self.entries_by_path.cursor::<()>(()) {
2775 if include_ignored || !entry.is_ignored {
2776 paths.push((entry.path.as_ref(), entry.inode, entry.is_ignored));
2777 }
2778 }
2779 paths.sort_by(|a, b| a.0.cmp(b.0));
2780 paths
2781 }
2782}
2783
2784impl BackgroundScannerState {
2785 fn should_scan_directory(&self, entry: &Entry) -> bool {
2786 (self.scanning_enabled && !entry.is_external && (!entry.is_ignored || entry.is_always_included))
2787 || entry.path.file_name() == Some(DOT_GIT)
2788 || entry.path.file_name() == Some(local_settings_folder_name())
2789 || entry.path.file_name() == Some(local_vscode_folder_name())
2790 || self.scanned_dirs.contains(&entry.id) // If we've ever scanned it, keep scanning
2791 || self
2792 .paths_to_scan
2793 .iter()
2794 .any(|p| p.starts_with(&entry.path))
2795 || self
2796 .path_prefixes_to_scan
2797 .iter()
2798 .any(|p| entry.path.starts_with(p))
2799 }
2800
2801 async fn enqueue_scan_dir(
2802 &self,
2803 abs_path: Arc<Path>,
2804 entry: &Entry,
2805 scan_job_tx: &Sender<ScanJob>,
2806 fs: &dyn Fs,
2807 ) {
2808 let path = entry.path.clone();
2809 let ignore_stack = self
2810 .snapshot
2811 .ignore_stack_for_abs_path(&abs_path, true, fs)
2812 .await;
2813 let mut ancestor_inodes = self.snapshot.ancestor_inodes_for_path(&path);
2814
2815 if !ancestor_inodes.contains(&entry.inode) {
2816 ancestor_inodes.insert(entry.inode);
2817 scan_job_tx
2818 .try_send(ScanJob {
2819 abs_path,
2820 path,
2821 ignore_stack,
2822 scan_queue: scan_job_tx.clone(),
2823 ancestor_inodes,
2824 is_external: entry.is_external,
2825 })
2826 .unwrap();
2827 }
2828 }
2829
2830 fn reuse_entry_id(&mut self, entry: &mut Entry) {
2831 if let Some(mtime) = entry.mtime {
2832 // If an entry with the same inode was removed from the worktree during this scan,
2833 // then it *might* represent the same file or directory. But the OS might also have
2834 // re-used the inode for a completely different file or directory.
2835 //
2836 // Conditionally reuse the old entry's id:
2837 // * if the mtime is the same, the file was probably been renamed.
2838 // * if the path is the same, the file may just have been updated
2839 if let Some(removed_entry) = self.removed_entries.remove(&entry.inode) {
2840 if removed_entry.mtime == Some(mtime) || removed_entry.path == entry.path {
2841 entry.id = removed_entry.id;
2842 }
2843 } else if let Some(existing_entry) = self.snapshot.entry_for_path(&entry.path) {
2844 entry.id = existing_entry.id;
2845 }
2846 }
2847 }
2848
2849 fn entry_id_for(
2850 &mut self,
2851 next_entry_id: &AtomicUsize,
2852 path: &RelPath,
2853 metadata: &fs::Metadata,
2854 ) -> ProjectEntryId {
2855 // If an entry with the same inode was removed from the worktree during this scan,
2856 // then it *might* represent the same file or directory. But the OS might also have
2857 // re-used the inode for a completely different file or directory.
2858 //
2859 // Conditionally reuse the old entry's id:
2860 // * if the mtime is the same, the file was probably been renamed.
2861 // * if the path is the same, the file may just have been updated
2862 if let Some(removed_entry) = self.removed_entries.remove(&metadata.inode) {
2863 if removed_entry.mtime == Some(metadata.mtime) || *removed_entry.path == *path {
2864 return removed_entry.id;
2865 }
2866 } else if let Some(existing_entry) = self.snapshot.entry_for_path(path) {
2867 return existing_entry.id;
2868 }
2869 ProjectEntryId::new(next_entry_id)
2870 }
2871
2872 async fn insert_entry(&mut self, entry: Entry, fs: &dyn Fs, watcher: &dyn Watcher) -> Entry {
2873 let entry = self.snapshot.insert_entry(entry, fs).await;
2874 if entry.path.file_name() == Some(&DOT_GIT) {
2875 self.insert_git_repository(entry.path.clone(), fs, watcher)
2876 .await;
2877 }
2878
2879 #[cfg(feature = "test-support")]
2880 self.snapshot.check_invariants(false);
2881
2882 entry
2883 }
2884
2885 fn populate_dir(
2886 &mut self,
2887 parent_path: Arc<RelPath>,
2888 entries: impl IntoIterator<Item = Entry>,
2889 ignore: Option<Arc<Gitignore>>,
2890 ) {
2891 let mut parent_entry = if let Some(parent_entry) = self
2892 .snapshot
2893 .entries_by_path
2894 .get(&PathKey(parent_path.clone()), ())
2895 {
2896 parent_entry.clone()
2897 } else {
2898 log::warn!(
2899 "populating a directory {:?} that has been removed",
2900 parent_path
2901 );
2902 return;
2903 };
2904
2905 match parent_entry.kind {
2906 EntryKind::PendingDir | EntryKind::UnloadedDir => parent_entry.kind = EntryKind::Dir,
2907 EntryKind::Dir => {}
2908 _ => return,
2909 }
2910
2911 if let Some(ignore) = ignore {
2912 let abs_parent_path = self
2913 .snapshot
2914 .abs_path
2915 .as_path()
2916 .join(parent_path.as_std_path())
2917 .into();
2918 self.snapshot
2919 .ignores_by_parent_abs_path
2920 .insert(abs_parent_path, (ignore, false));
2921 }
2922
2923 let parent_entry_id = parent_entry.id;
2924 self.scanned_dirs.insert(parent_entry_id);
2925 let mut entries_by_path_edits = vec![Edit::Insert(parent_entry)];
2926 let mut entries_by_id_edits = Vec::new();
2927
2928 for entry in entries {
2929 entries_by_id_edits.push(Edit::Insert(PathEntry {
2930 id: entry.id,
2931 path: entry.path.clone(),
2932 is_ignored: entry.is_ignored,
2933 scan_id: self.snapshot.scan_id,
2934 }));
2935 entries_by_path_edits.push(Edit::Insert(entry));
2936 }
2937
2938 self.snapshot
2939 .entries_by_path
2940 .edit(entries_by_path_edits, ());
2941 self.snapshot.entries_by_id.edit(entries_by_id_edits, ());
2942
2943 if let Err(ix) = self.changed_paths.binary_search(&parent_path) {
2944 self.changed_paths.insert(ix, parent_path.clone());
2945 }
2946
2947 #[cfg(feature = "test-support")]
2948 self.snapshot.check_invariants(false);
2949 }
2950
2951 fn remove_path(&mut self, path: &RelPath, watcher: &dyn Watcher) {
2952 log::trace!("background scanner removing path {path:?}");
2953 let mut new_entries;
2954 let removed_entries;
2955 {
2956 let mut cursor = self
2957 .snapshot
2958 .entries_by_path
2959 .cursor::<TraversalProgress>(());
2960 new_entries = cursor.slice(&TraversalTarget::path(path), Bias::Left);
2961 removed_entries = cursor.slice(&TraversalTarget::successor(path), Bias::Left);
2962 new_entries.append(cursor.suffix(), ());
2963 }
2964 self.snapshot.entries_by_path = new_entries;
2965
2966 let mut removed_ids = Vec::with_capacity(removed_entries.summary().count);
2967 let mut removed_dir_abs_paths = Vec::new();
2968 for entry in removed_entries.cursor::<()>(()) {
2969 if entry.is_dir() {
2970 removed_dir_abs_paths.push(self.snapshot.absolutize(&entry.path));
2971 }
2972
2973 match self.removed_entries.entry(entry.inode) {
2974 hash_map::Entry::Occupied(mut e) => {
2975 let prev_removed_entry = e.get_mut();
2976 if entry.id > prev_removed_entry.id {
2977 *prev_removed_entry = entry.clone();
2978 }
2979 }
2980 hash_map::Entry::Vacant(e) => {
2981 e.insert(entry.clone());
2982 }
2983 }
2984
2985 if entry.path.file_name() == Some(GITIGNORE) {
2986 let abs_parent_path = self.snapshot.absolutize(&entry.path.parent().unwrap());
2987 if let Some((_, needs_update)) = self
2988 .snapshot
2989 .ignores_by_parent_abs_path
2990 .get_mut(abs_parent_path.as_path())
2991 {
2992 *needs_update = true;
2993 }
2994 }
2995
2996 if let Err(ix) = removed_ids.binary_search(&entry.id) {
2997 removed_ids.insert(ix, entry.id);
2998 }
2999 }
3000
3001 self.snapshot
3002 .entries_by_id
3003 .edit(removed_ids.iter().map(|&id| Edit::Remove(id)).collect(), ());
3004 self.snapshot
3005 .git_repositories
3006 .retain(|id, _| removed_ids.binary_search(id).is_err());
3007
3008 for removed_dir_abs_path in removed_dir_abs_paths {
3009 watcher.remove(&removed_dir_abs_path).log_err();
3010 }
3011
3012 #[cfg(feature = "test-support")]
3013 self.snapshot.check_invariants(false);
3014 }
3015
3016 async fn insert_git_repository(
3017 &mut self,
3018 dot_git_path: Arc<RelPath>,
3019 fs: &dyn Fs,
3020 watcher: &dyn Watcher,
3021 ) {
3022 let work_dir_path: Arc<RelPath> = match dot_git_path.parent() {
3023 Some(parent_dir) => {
3024 // Guard against repositories inside the repository metadata
3025 if parent_dir
3026 .components()
3027 .any(|component| component == DOT_GIT)
3028 {
3029 log::debug!(
3030 "not building git repository for nested `.git` directory, `.git` path in the worktree: {dot_git_path:?}"
3031 );
3032 return;
3033 };
3034
3035 parent_dir.into()
3036 }
3037 None => {
3038 // `dot_git_path.parent().is_none()` means `.git` directory is the opened worktree itself,
3039 // no files inside that directory are tracked by git, so no need to build the repo around it
3040 log::debug!(
3041 "not building git repository for the worktree itself, `.git` path in the worktree: {dot_git_path:?}"
3042 );
3043 return;
3044 }
3045 };
3046
3047 let dot_git_abs_path = Arc::from(self.snapshot.absolutize(&dot_git_path).as_ref());
3048
3049 self.insert_git_repository_for_path(
3050 WorkDirectory::InProject {
3051 relative_path: work_dir_path,
3052 },
3053 dot_git_abs_path,
3054 fs,
3055 watcher,
3056 )
3057 .await
3058 .log_err();
3059 }
3060
3061 async fn insert_git_repository_for_path(
3062 &mut self,
3063 work_directory: WorkDirectory,
3064 dot_git_abs_path: Arc<Path>,
3065 fs: &dyn Fs,
3066 watcher: &dyn Watcher,
3067 ) -> Result<LocalRepositoryEntry> {
3068 let work_dir_entry = self
3069 .snapshot
3070 .entry_for_path(&work_directory.path_key().0)
3071 .with_context(|| {
3072 format!(
3073 "working directory `{}` not indexed",
3074 work_directory
3075 .path_key()
3076 .0
3077 .display(self.snapshot.path_style)
3078 )
3079 })?;
3080 let work_directory_abs_path = self.snapshot.work_directory_abs_path(&work_directory);
3081
3082 let (repository_dir_abs_path, common_dir_abs_path) =
3083 discover_git_paths(&dot_git_abs_path, fs).await;
3084 watcher
3085 .add(&common_dir_abs_path)
3086 .context("failed to add common directory to watcher")
3087 .log_err();
3088 watcher
3089 .add(&repository_dir_abs_path)
3090 .context("failed to add repository directory to watcher")
3091 .log_err();
3092
3093 let work_directory_id = work_dir_entry.id;
3094
3095 let local_repository = LocalRepositoryEntry {
3096 work_directory_id,
3097 work_directory,
3098 work_directory_abs_path: work_directory_abs_path.as_path().into(),
3099 git_dir_scan_id: 0,
3100 dot_git_abs_path,
3101 common_dir_abs_path,
3102 repository_dir_abs_path,
3103 };
3104
3105 self.snapshot
3106 .git_repositories
3107 .insert(work_directory_id, local_repository.clone());
3108
3109 log::trace!("inserting new local git repository");
3110 Ok(local_repository)
3111 }
3112}
3113
3114async fn is_git_dir(path: &Path, fs: &dyn Fs) -> bool {
3115 if let Some(file_name) = path.file_name()
3116 && file_name == DOT_GIT
3117 {
3118 return true;
3119 }
3120
3121 // If we're in a bare repository, we are not inside a `.git` folder. In a
3122 // bare repository, the root folder contains what would normally be in the
3123 // `.git` folder.
3124 let head_metadata = fs.metadata(&path.join("HEAD")).await;
3125 if !matches!(head_metadata, Ok(Some(_))) {
3126 return false;
3127 }
3128 let config_metadata = fs.metadata(&path.join("config")).await;
3129 matches!(config_metadata, Ok(Some(_)))
3130}
3131
3132async fn build_gitignore(abs_path: &Path, fs: &dyn Fs) -> Result<Gitignore> {
3133 let contents = fs
3134 .load(abs_path)
3135 .await
3136 .with_context(|| format!("failed to load gitignore file at {}", abs_path.display()))?;
3137 let parent = abs_path.parent().unwrap_or_else(|| Path::new("/"));
3138 let mut builder = GitignoreBuilder::new(parent);
3139 for line in contents.lines() {
3140 builder.add_line(Some(abs_path.into()), line)?;
3141 }
3142 Ok(builder.build()?)
3143}
3144
3145impl Deref for Worktree {
3146 type Target = Snapshot;
3147
3148 fn deref(&self) -> &Self::Target {
3149 match self {
3150 Worktree::Local(worktree) => &worktree.snapshot,
3151 Worktree::Remote(worktree) => &worktree.snapshot,
3152 }
3153 }
3154}
3155
3156impl Deref for LocalWorktree {
3157 type Target = LocalSnapshot;
3158
3159 fn deref(&self) -> &Self::Target {
3160 &self.snapshot
3161 }
3162}
3163
3164impl Deref for RemoteWorktree {
3165 type Target = Snapshot;
3166
3167 fn deref(&self) -> &Self::Target {
3168 &self.snapshot
3169 }
3170}
3171
3172impl fmt::Debug for LocalWorktree {
3173 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3174 self.snapshot.fmt(f)
3175 }
3176}
3177
3178impl fmt::Debug for Snapshot {
3179 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3180 struct EntriesById<'a>(&'a SumTree<PathEntry>);
3181 struct EntriesByPath<'a>(&'a SumTree<Entry>);
3182
3183 impl fmt::Debug for EntriesByPath<'_> {
3184 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3185 f.debug_map()
3186 .entries(self.0.iter().map(|entry| (&entry.path, entry.id)))
3187 .finish()
3188 }
3189 }
3190
3191 impl fmt::Debug for EntriesById<'_> {
3192 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3193 f.debug_list().entries(self.0.iter()).finish()
3194 }
3195 }
3196
3197 f.debug_struct("Snapshot")
3198 .field("id", &self.id)
3199 .field("root_name", &self.root_name)
3200 .field("entries_by_path", &EntriesByPath(&self.entries_by_path))
3201 .field("entries_by_id", &EntriesById(&self.entries_by_id))
3202 .finish()
3203 }
3204}
3205
3206#[derive(Debug, Clone, PartialEq)]
3207pub struct File {
3208 pub worktree: Entity<Worktree>,
3209 pub path: Arc<RelPath>,
3210 pub disk_state: DiskState,
3211 pub entry_id: Option<ProjectEntryId>,
3212 pub is_local: bool,
3213 pub is_private: bool,
3214}
3215
3216impl language::File for File {
3217 fn as_local(&self) -> Option<&dyn language::LocalFile> {
3218 if self.is_local { Some(self) } else { None }
3219 }
3220
3221 fn disk_state(&self) -> DiskState {
3222 self.disk_state
3223 }
3224
3225 fn path(&self) -> &Arc<RelPath> {
3226 &self.path
3227 }
3228
3229 fn full_path(&self, cx: &App) -> PathBuf {
3230 self.worktree.read(cx).full_path(&self.path)
3231 }
3232
3233 /// Returns the last component of this handle's absolute path. If this handle refers to the root
3234 /// of its worktree, then this method will return the name of the worktree itself.
3235 fn file_name<'a>(&'a self, cx: &'a App) -> &'a str {
3236 self.path
3237 .file_name()
3238 .unwrap_or_else(|| self.worktree.read(cx).root_name_str())
3239 }
3240
3241 fn worktree_id(&self, cx: &App) -> WorktreeId {
3242 self.worktree.read(cx).id()
3243 }
3244
3245 fn to_proto(&self, cx: &App) -> rpc::proto::File {
3246 rpc::proto::File {
3247 worktree_id: self.worktree.read(cx).id().to_proto(),
3248 entry_id: self.entry_id.map(|id| id.to_proto()),
3249 path: self.path.as_ref().to_proto(),
3250 mtime: self.disk_state.mtime().map(|time| time.into()),
3251 is_deleted: self.disk_state.is_deleted(),
3252 is_historic: matches!(self.disk_state, DiskState::Historic { .. }),
3253 }
3254 }
3255
3256 fn is_private(&self) -> bool {
3257 self.is_private
3258 }
3259
3260 fn path_style(&self, cx: &App) -> PathStyle {
3261 self.worktree.read(cx).path_style()
3262 }
3263
3264 fn can_open(&self) -> bool {
3265 true
3266 }
3267}
3268
3269impl language::LocalFile for File {
3270 fn abs_path(&self, cx: &App) -> PathBuf {
3271 self.worktree.read(cx).absolutize(&self.path)
3272 }
3273
3274 fn load(&self, cx: &App) -> Task<Result<String>> {
3275 let worktree = self.worktree.read(cx).as_local().unwrap();
3276 let abs_path = worktree.absolutize(&self.path);
3277 let fs = worktree.fs.clone();
3278 cx.background_spawn(async move { fs.load(&abs_path).await })
3279 }
3280
3281 fn load_bytes(&self, cx: &App) -> Task<Result<Vec<u8>>> {
3282 let worktree = self.worktree.read(cx).as_local().unwrap();
3283 let abs_path = worktree.absolutize(&self.path);
3284 let fs = worktree.fs.clone();
3285 cx.background_spawn(async move { fs.load_bytes(&abs_path).await })
3286 }
3287}
3288
3289impl File {
3290 pub fn for_entry(entry: Entry, worktree: Entity<Worktree>) -> Arc<Self> {
3291 Arc::new(Self {
3292 worktree,
3293 path: entry.path.clone(),
3294 disk_state: if let Some(mtime) = entry.mtime {
3295 DiskState::Present {
3296 mtime,
3297 size: entry.size,
3298 }
3299 } else {
3300 DiskState::New
3301 },
3302 entry_id: Some(entry.id),
3303 is_local: true,
3304 is_private: entry.is_private,
3305 })
3306 }
3307
3308 pub fn from_proto(
3309 proto: rpc::proto::File,
3310 worktree: Entity<Worktree>,
3311 cx: &App,
3312 ) -> Result<Self> {
3313 let worktree_id = worktree.read(cx).as_remote().context("not remote")?.id();
3314
3315 anyhow::ensure!(
3316 worktree_id.to_proto() == proto.worktree_id,
3317 "worktree id does not match file"
3318 );
3319
3320 let disk_state = if proto.is_historic {
3321 DiskState::Historic {
3322 was_deleted: proto.is_deleted,
3323 }
3324 } else if proto.is_deleted {
3325 DiskState::Deleted
3326 } else if let Some(mtime) = proto.mtime.map(&Into::into) {
3327 DiskState::Present { mtime, size: 0 }
3328 } else {
3329 DiskState::New
3330 };
3331
3332 Ok(Self {
3333 worktree,
3334 path: RelPath::from_proto(&proto.path).context("invalid path in file protobuf")?,
3335 disk_state,
3336 entry_id: proto.entry_id.map(ProjectEntryId::from_proto),
3337 is_local: false,
3338 is_private: false,
3339 })
3340 }
3341
3342 pub fn from_dyn(file: Option<&Arc<dyn language::File>>) -> Option<&Self> {
3343 file.and_then(|f| {
3344 let f: &dyn language::File = f.borrow();
3345 let f: &dyn Any = f;
3346 f.downcast_ref()
3347 })
3348 }
3349
3350 pub fn worktree_id(&self, cx: &App) -> WorktreeId {
3351 self.worktree.read(cx).id()
3352 }
3353
3354 pub fn project_entry_id(&self) -> Option<ProjectEntryId> {
3355 match self.disk_state {
3356 DiskState::Deleted => None,
3357 _ => self.entry_id,
3358 }
3359 }
3360}
3361
3362#[derive(Clone, Debug, PartialEq, Eq)]
3363pub struct Entry {
3364 pub id: ProjectEntryId,
3365 pub kind: EntryKind,
3366 pub path: Arc<RelPath>,
3367 pub inode: u64,
3368 pub mtime: Option<MTime>,
3369
3370 pub canonical_path: Option<Arc<Path>>,
3371 /// Whether this entry is ignored by Git.
3372 ///
3373 /// We only scan ignored entries once the directory is expanded and
3374 /// exclude them from searches.
3375 pub is_ignored: bool,
3376
3377 /// Whether this entry is hidden or inside hidden directory.
3378 ///
3379 /// We only scan hidden entries once the directory is expanded.
3380 pub is_hidden: bool,
3381
3382 /// Whether this entry is always included in searches.
3383 ///
3384 /// This is used for entries that are always included in searches, even
3385 /// if they are ignored by git. Overridden by file_scan_exclusions.
3386 pub is_always_included: bool,
3387
3388 /// Whether this entry's canonical path is outside of the worktree.
3389 /// This means the entry is only accessible from the worktree root via a
3390 /// symlink.
3391 ///
3392 /// We only scan entries outside of the worktree once the symlinked
3393 /// directory is expanded. External entries are treated like gitignored
3394 /// entries in that they are not included in searches.
3395 pub is_external: bool,
3396
3397 /// Whether this entry is considered to be a `.env` file.
3398 pub is_private: bool,
3399 /// The entry's size on disk, in bytes.
3400 pub size: u64,
3401 pub char_bag: CharBag,
3402 pub is_fifo: bool,
3403}
3404
3405#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3406pub enum EntryKind {
3407 UnloadedDir,
3408 PendingDir,
3409 Dir,
3410 File,
3411}
3412
3413#[derive(Clone, Copy, Debug, PartialEq)]
3414pub enum PathChange {
3415 /// A filesystem entry was was created.
3416 Added,
3417 /// A filesystem entry was removed.
3418 Removed,
3419 /// A filesystem entry was updated.
3420 Updated,
3421 /// A filesystem entry was either updated or added. We don't know
3422 /// whether or not it already existed, because the path had not
3423 /// been loaded before the event.
3424 AddedOrUpdated,
3425 /// A filesystem entry was found during the initial scan of the worktree.
3426 Loaded,
3427}
3428
3429#[derive(Clone, Debug, PartialEq, Eq)]
3430pub struct UpdatedGitRepository {
3431 /// ID of the repository's working directory.
3432 ///
3433 /// For a repo that's above the worktree root, this is the ID of the worktree root, and hence not unique.
3434 /// It's included here to aid the GitStore in detecting when a repository's working directory is renamed.
3435 pub work_directory_id: ProjectEntryId,
3436 pub old_work_directory_abs_path: Option<Arc<Path>>,
3437 pub new_work_directory_abs_path: Option<Arc<Path>>,
3438 /// For a normal git repository checkout, the absolute path to the .git directory.
3439 /// For a worktree, the absolute path to the worktree's subdirectory inside the .git directory.
3440 pub dot_git_abs_path: Option<Arc<Path>>,
3441 pub repository_dir_abs_path: Option<Arc<Path>>,
3442 pub common_dir_abs_path: Option<Arc<Path>>,
3443}
3444
3445pub type UpdatedEntriesSet = Arc<[(Arc<RelPath>, ProjectEntryId, PathChange)]>;
3446pub type UpdatedGitRepositoriesSet = Arc<[UpdatedGitRepository]>;
3447
3448#[derive(Clone, Debug)]
3449pub struct PathProgress<'a> {
3450 pub max_path: &'a RelPath,
3451}
3452
3453#[derive(Clone, Debug)]
3454pub struct PathSummary<S> {
3455 pub max_path: Arc<RelPath>,
3456 pub item_summary: S,
3457}
3458
3459impl<S: Summary> Summary for PathSummary<S> {
3460 type Context<'a> = S::Context<'a>;
3461
3462 fn zero(cx: Self::Context<'_>) -> Self {
3463 Self {
3464 max_path: RelPath::empty().into(),
3465 item_summary: S::zero(cx),
3466 }
3467 }
3468
3469 fn add_summary(&mut self, rhs: &Self, cx: Self::Context<'_>) {
3470 self.max_path = rhs.max_path.clone();
3471 self.item_summary.add_summary(&rhs.item_summary, cx);
3472 }
3473}
3474
3475impl<'a, S: Summary> sum_tree::Dimension<'a, PathSummary<S>> for PathProgress<'a> {
3476 fn zero(_: <PathSummary<S> as Summary>::Context<'_>) -> Self {
3477 Self {
3478 max_path: RelPath::empty(),
3479 }
3480 }
3481
3482 fn add_summary(
3483 &mut self,
3484 summary: &'a PathSummary<S>,
3485 _: <PathSummary<S> as Summary>::Context<'_>,
3486 ) {
3487 self.max_path = summary.max_path.as_ref()
3488 }
3489}
3490
3491impl<'a> sum_tree::Dimension<'a, PathSummary<GitSummary>> for GitSummary {
3492 fn zero(_cx: ()) -> Self {
3493 Default::default()
3494 }
3495
3496 fn add_summary(&mut self, summary: &'a PathSummary<GitSummary>, _: ()) {
3497 *self += summary.item_summary
3498 }
3499}
3500
3501impl<'a>
3502 sum_tree::SeekTarget<'a, PathSummary<GitSummary>, Dimensions<TraversalProgress<'a>, GitSummary>>
3503 for PathTarget<'_>
3504{
3505 fn cmp(
3506 &self,
3507 cursor_location: &Dimensions<TraversalProgress<'a>, GitSummary>,
3508 _: (),
3509 ) -> Ordering {
3510 self.cmp_path(cursor_location.0.max_path)
3511 }
3512}
3513
3514impl<'a, S: Summary> sum_tree::Dimension<'a, PathSummary<S>> for PathKey {
3515 fn zero(_: S::Context<'_>) -> Self {
3516 Default::default()
3517 }
3518
3519 fn add_summary(&mut self, summary: &'a PathSummary<S>, _: S::Context<'_>) {
3520 self.0 = summary.max_path.clone();
3521 }
3522}
3523
3524impl<'a, S: Summary> sum_tree::Dimension<'a, PathSummary<S>> for TraversalProgress<'a> {
3525 fn zero(_cx: S::Context<'_>) -> Self {
3526 Default::default()
3527 }
3528
3529 fn add_summary(&mut self, summary: &'a PathSummary<S>, _: S::Context<'_>) {
3530 self.max_path = summary.max_path.as_ref();
3531 }
3532}
3533
3534impl Entry {
3535 fn new(
3536 path: Arc<RelPath>,
3537 metadata: &fs::Metadata,
3538 id: ProjectEntryId,
3539 root_char_bag: CharBag,
3540 canonical_path: Option<Arc<Path>>,
3541 ) -> Self {
3542 let char_bag = char_bag_for_path(root_char_bag, &path);
3543 Self {
3544 id,
3545 kind: if metadata.is_dir {
3546 EntryKind::PendingDir
3547 } else {
3548 EntryKind::File
3549 },
3550 path,
3551 inode: metadata.inode,
3552 mtime: Some(metadata.mtime),
3553 size: metadata.len,
3554 canonical_path,
3555 is_ignored: false,
3556 is_hidden: false,
3557 is_always_included: false,
3558 is_external: false,
3559 is_private: false,
3560 char_bag,
3561 is_fifo: metadata.is_fifo,
3562 }
3563 }
3564
3565 pub fn is_created(&self) -> bool {
3566 self.mtime.is_some()
3567 }
3568
3569 pub fn is_dir(&self) -> bool {
3570 self.kind.is_dir()
3571 }
3572
3573 pub fn is_file(&self) -> bool {
3574 self.kind.is_file()
3575 }
3576}
3577
3578impl EntryKind {
3579 pub fn is_dir(&self) -> bool {
3580 matches!(
3581 self,
3582 EntryKind::Dir | EntryKind::PendingDir | EntryKind::UnloadedDir
3583 )
3584 }
3585
3586 pub fn is_unloaded(&self) -> bool {
3587 matches!(self, EntryKind::UnloadedDir)
3588 }
3589
3590 pub fn is_file(&self) -> bool {
3591 matches!(self, EntryKind::File)
3592 }
3593}
3594
3595impl sum_tree::Item for Entry {
3596 type Summary = EntrySummary;
3597
3598 fn summary(&self, _cx: ()) -> Self::Summary {
3599 let non_ignored_count = if (self.is_ignored || self.is_external) && !self.is_always_included
3600 {
3601 0
3602 } else {
3603 1
3604 };
3605 let file_count;
3606 let non_ignored_file_count;
3607 if self.is_file() {
3608 file_count = 1;
3609 non_ignored_file_count = non_ignored_count;
3610 } else {
3611 file_count = 0;
3612 non_ignored_file_count = 0;
3613 }
3614
3615 EntrySummary {
3616 max_path: self.path.clone(),
3617 count: 1,
3618 non_ignored_count,
3619 file_count,
3620 non_ignored_file_count,
3621 }
3622 }
3623}
3624
3625impl sum_tree::KeyedItem for Entry {
3626 type Key = PathKey;
3627
3628 fn key(&self) -> Self::Key {
3629 PathKey(self.path.clone())
3630 }
3631}
3632
3633#[derive(Clone, Debug)]
3634pub struct EntrySummary {
3635 max_path: Arc<RelPath>,
3636 count: usize,
3637 non_ignored_count: usize,
3638 file_count: usize,
3639 non_ignored_file_count: usize,
3640}
3641
3642impl Default for EntrySummary {
3643 fn default() -> Self {
3644 Self {
3645 max_path: Arc::from(RelPath::empty()),
3646 count: 0,
3647 non_ignored_count: 0,
3648 file_count: 0,
3649 non_ignored_file_count: 0,
3650 }
3651 }
3652}
3653
3654impl sum_tree::ContextLessSummary for EntrySummary {
3655 fn zero() -> Self {
3656 Default::default()
3657 }
3658
3659 fn add_summary(&mut self, rhs: &Self) {
3660 self.max_path = rhs.max_path.clone();
3661 self.count += rhs.count;
3662 self.non_ignored_count += rhs.non_ignored_count;
3663 self.file_count += rhs.file_count;
3664 self.non_ignored_file_count += rhs.non_ignored_file_count;
3665 }
3666}
3667
3668#[derive(Clone, Debug)]
3669struct PathEntry {
3670 id: ProjectEntryId,
3671 path: Arc<RelPath>,
3672 is_ignored: bool,
3673 scan_id: usize,
3674}
3675
3676impl sum_tree::Item for PathEntry {
3677 type Summary = PathEntrySummary;
3678
3679 fn summary(&self, _cx: ()) -> Self::Summary {
3680 PathEntrySummary { max_id: self.id }
3681 }
3682}
3683
3684impl sum_tree::KeyedItem for PathEntry {
3685 type Key = ProjectEntryId;
3686
3687 fn key(&self) -> Self::Key {
3688 self.id
3689 }
3690}
3691
3692#[derive(Clone, Debug, Default)]
3693struct PathEntrySummary {
3694 max_id: ProjectEntryId,
3695}
3696
3697impl sum_tree::ContextLessSummary for PathEntrySummary {
3698 fn zero() -> Self {
3699 Default::default()
3700 }
3701
3702 fn add_summary(&mut self, summary: &Self) {
3703 self.max_id = summary.max_id;
3704 }
3705}
3706
3707impl<'a> sum_tree::Dimension<'a, PathEntrySummary> for ProjectEntryId {
3708 fn zero(_cx: ()) -> Self {
3709 Default::default()
3710 }
3711
3712 fn add_summary(&mut self, summary: &'a PathEntrySummary, _: ()) {
3713 *self = summary.max_id;
3714 }
3715}
3716
3717#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
3718pub struct PathKey(pub Arc<RelPath>);
3719
3720impl Default for PathKey {
3721 fn default() -> Self {
3722 Self(RelPath::empty().into())
3723 }
3724}
3725
3726impl<'a> sum_tree::Dimension<'a, EntrySummary> for PathKey {
3727 fn zero(_cx: ()) -> Self {
3728 Default::default()
3729 }
3730
3731 fn add_summary(&mut self, summary: &'a EntrySummary, _: ()) {
3732 self.0 = summary.max_path.clone();
3733 }
3734}
3735
3736struct BackgroundScanner {
3737 state: async_lock::Mutex<BackgroundScannerState>,
3738 fs: Arc<dyn Fs>,
3739 fs_case_sensitive: bool,
3740 status_updates_tx: UnboundedSender<ScanState>,
3741 executor: BackgroundExecutor,
3742 scan_requests_rx: channel::Receiver<ScanRequest>,
3743 path_prefixes_to_scan_rx: channel::Receiver<PathPrefixScanRequest>,
3744 next_entry_id: Arc<AtomicUsize>,
3745 phase: BackgroundScannerPhase,
3746 watcher: Arc<dyn Watcher>,
3747 settings: WorktreeSettings,
3748 share_private_files: bool,
3749}
3750
3751#[derive(Copy, Clone, PartialEq)]
3752enum BackgroundScannerPhase {
3753 InitialScan,
3754 EventsReceivedDuringInitialScan,
3755 Events,
3756}
3757
3758impl BackgroundScanner {
3759 async fn run(&mut self, mut fs_events_rx: Pin<Box<dyn Send + Stream<Item = Vec<PathEvent>>>>) {
3760 let root_abs_path;
3761 let scanning_enabled;
3762 {
3763 let state = self.state.lock().await;
3764 root_abs_path = state.snapshot.abs_path.clone();
3765 scanning_enabled = state.scanning_enabled;
3766 }
3767
3768 // If the worktree root does not contain a git repository, then find
3769 // the git repository in an ancestor directory. Find any gitignore files
3770 // in ancestor directories.
3771 let repo = if scanning_enabled {
3772 let (ignores, exclude, repo) =
3773 discover_ancestor_git_repo(self.fs.clone(), &root_abs_path).await;
3774 self.state
3775 .lock()
3776 .await
3777 .snapshot
3778 .ignores_by_parent_abs_path
3779 .extend(ignores);
3780 if let Some(exclude) = exclude {
3781 self.state
3782 .lock()
3783 .await
3784 .snapshot
3785 .repo_exclude_by_work_dir_abs_path
3786 .insert(root_abs_path.as_path().into(), (exclude, false));
3787 }
3788
3789 repo
3790 } else {
3791 None
3792 };
3793
3794 let containing_git_repository = if let Some((ancestor_dot_git, work_directory)) = repo
3795 && scanning_enabled
3796 {
3797 maybe!(async {
3798 self.state
3799 .lock()
3800 .await
3801 .insert_git_repository_for_path(
3802 work_directory,
3803 ancestor_dot_git.clone().into(),
3804 self.fs.as_ref(),
3805 self.watcher.as_ref(),
3806 )
3807 .await
3808 .log_err()?;
3809 Some(ancestor_dot_git)
3810 })
3811 .await
3812 } else {
3813 None
3814 };
3815
3816 log::trace!("containing git repository: {containing_git_repository:?}");
3817
3818 let global_gitignore_file = paths::global_gitignore_path();
3819 let mut global_gitignore_events = if let Some(global_gitignore_path) =
3820 &global_gitignore_file
3821 && scanning_enabled
3822 {
3823 let is_file = self.fs.is_file(&global_gitignore_path).await;
3824 self.state.lock().await.snapshot.global_gitignore = if is_file {
3825 build_gitignore(global_gitignore_path, self.fs.as_ref())
3826 .await
3827 .ok()
3828 .map(Arc::new)
3829 } else {
3830 None
3831 };
3832 if is_file {
3833 self.fs
3834 .watch(global_gitignore_path, FS_WATCH_LATENCY)
3835 .await
3836 .0
3837 } else {
3838 Box::pin(futures::stream::pending())
3839 }
3840 } else {
3841 self.state.lock().await.snapshot.global_gitignore = None;
3842 Box::pin(futures::stream::pending())
3843 };
3844
3845 let (scan_job_tx, scan_job_rx) = channel::unbounded();
3846 {
3847 let mut state = self.state.lock().await;
3848 state.snapshot.scan_id += 1;
3849 if let Some(mut root_entry) = state.snapshot.root_entry().cloned() {
3850 let ignore_stack = state
3851 .snapshot
3852 .ignore_stack_for_abs_path(root_abs_path.as_path(), true, self.fs.as_ref())
3853 .await;
3854 if ignore_stack.is_abs_path_ignored(root_abs_path.as_path(), true) {
3855 root_entry.is_ignored = true;
3856 let mut root_entry = root_entry.clone();
3857 state.reuse_entry_id(&mut root_entry);
3858 state
3859 .insert_entry(root_entry, self.fs.as_ref(), self.watcher.as_ref())
3860 .await;
3861 }
3862 if root_entry.is_dir() && state.scanning_enabled {
3863 state
3864 .enqueue_scan_dir(
3865 root_abs_path.as_path().into(),
3866 &root_entry,
3867 &scan_job_tx,
3868 self.fs.as_ref(),
3869 )
3870 .await;
3871 }
3872 }
3873 };
3874
3875 // Perform an initial scan of the directory.
3876 drop(scan_job_tx);
3877 self.scan_dirs(true, scan_job_rx).await;
3878 {
3879 let mut state = self.state.lock().await;
3880 state.snapshot.completed_scan_id = state.snapshot.scan_id;
3881 }
3882
3883 self.send_status_update(false, SmallVec::new()).await;
3884
3885 // Process any any FS events that occurred while performing the initial scan.
3886 // For these events, update events cannot be as precise, because we didn't
3887 // have the previous state loaded yet.
3888 self.phase = BackgroundScannerPhase::EventsReceivedDuringInitialScan;
3889 if let Poll::Ready(Some(mut paths)) = futures::poll!(fs_events_rx.next()) {
3890 while let Poll::Ready(Some(more_paths)) = futures::poll!(fs_events_rx.next()) {
3891 paths.extend(more_paths);
3892 }
3893 self.process_events(
3894 paths
3895 .into_iter()
3896 .filter(|e| e.kind.is_some())
3897 .map(Into::into)
3898 .collect(),
3899 )
3900 .await;
3901 }
3902 if let Some(abs_path) = containing_git_repository {
3903 self.process_events(vec![abs_path]).await;
3904 }
3905
3906 // Continue processing events until the worktree is dropped.
3907 self.phase = BackgroundScannerPhase::Events;
3908
3909 loop {
3910 select_biased! {
3911 // Process any path refresh requests from the worktree. Prioritize
3912 // these before handling changes reported by the filesystem.
3913 request = self.next_scan_request().fuse() => {
3914 let Ok(request) = request else { break };
3915 if !self.process_scan_request(request, false).await {
3916 return;
3917 }
3918 }
3919
3920 path_prefix_request = self.path_prefixes_to_scan_rx.recv().fuse() => {
3921 let Ok(request) = path_prefix_request else { break };
3922 log::trace!("adding path prefix {:?}", request.path);
3923
3924 let did_scan = self.forcibly_load_paths(std::slice::from_ref(&request.path)).await;
3925 if did_scan {
3926 let abs_path =
3927 {
3928 let mut state = self.state.lock().await;
3929 state.path_prefixes_to_scan.insert(request.path.clone());
3930 state.snapshot.absolutize(&request.path)
3931 };
3932
3933 if let Some(abs_path) = self.fs.canonicalize(&abs_path).await.log_err() {
3934 self.process_events(vec![abs_path]).await;
3935 }
3936 }
3937 self.send_status_update(false, request.done).await;
3938 }
3939
3940 paths = fs_events_rx.next().fuse() => {
3941 let Some(mut paths) = paths else { break };
3942 while let Poll::Ready(Some(more_paths)) = futures::poll!(fs_events_rx.next()) {
3943 paths.extend(more_paths);
3944 }
3945 self.process_events(paths.into_iter().filter(|e| e.kind.is_some()).map(Into::into).collect()).await;
3946 }
3947
3948 _ = global_gitignore_events.next().fuse() => {
3949 if let Some(path) = &global_gitignore_file {
3950 self.update_global_gitignore(&path).await;
3951 }
3952 }
3953 }
3954 }
3955 }
3956
3957 async fn process_scan_request(&self, mut request: ScanRequest, scanning: bool) -> bool {
3958 log::debug!("rescanning paths {:?}", request.relative_paths);
3959
3960 request.relative_paths.sort_unstable();
3961 self.forcibly_load_paths(&request.relative_paths).await;
3962
3963 let root_path = self.state.lock().await.snapshot.abs_path.clone();
3964 let root_canonical_path = self.fs.canonicalize(root_path.as_path()).await;
3965 let root_canonical_path = match &root_canonical_path {
3966 Ok(path) => SanitizedPath::new(path),
3967 Err(err) => {
3968 log::error!("failed to canonicalize root path {root_path:?}: {err:#}");
3969 return true;
3970 }
3971 };
3972 let abs_paths = request
3973 .relative_paths
3974 .iter()
3975 .map(|path| {
3976 if path.file_name().is_some() {
3977 root_canonical_path.as_path().join(path.as_std_path())
3978 } else {
3979 root_canonical_path.as_path().to_path_buf()
3980 }
3981 })
3982 .collect::<Vec<_>>();
3983
3984 {
3985 let mut state = self.state.lock().await;
3986 let is_idle = state.snapshot.completed_scan_id == state.snapshot.scan_id;
3987 state.snapshot.scan_id += 1;
3988 if is_idle {
3989 state.snapshot.completed_scan_id = state.snapshot.scan_id;
3990 }
3991 }
3992
3993 self.reload_entries_for_paths(
3994 &root_path,
3995 &root_canonical_path,
3996 &request.relative_paths,
3997 abs_paths,
3998 None,
3999 )
4000 .await;
4001
4002 self.send_status_update(scanning, request.done).await
4003 }
4004
4005 async fn process_events(&self, mut abs_paths: Vec<PathBuf>) {
4006 log::trace!("process events: {abs_paths:?}");
4007 let root_path = self.state.lock().await.snapshot.abs_path.clone();
4008 let root_canonical_path = self.fs.canonicalize(root_path.as_path()).await;
4009 let root_canonical_path = match &root_canonical_path {
4010 Ok(path) => SanitizedPath::new(path),
4011 Err(err) => {
4012 let new_path = self
4013 .state
4014 .lock()
4015 .await
4016 .snapshot
4017 .root_file_handle
4018 .clone()
4019 .and_then(|handle| match handle.current_path(&self.fs) {
4020 Ok(new_path) => Some(new_path),
4021 Err(e) => {
4022 log::error!("Failed to refresh worktree root path: {e:#}");
4023 None
4024 }
4025 })
4026 .map(|path| SanitizedPath::new_arc(&path))
4027 .filter(|new_path| *new_path != root_path);
4028
4029 if let Some(new_path) = new_path {
4030 log::info!(
4031 "root renamed from {:?} to {:?}",
4032 root_path.as_path(),
4033 new_path.as_path(),
4034 );
4035 self.status_updates_tx
4036 .unbounded_send(ScanState::RootUpdated { new_path })
4037 .ok();
4038 } else {
4039 log::error!("root path could not be canonicalized: {err:#}");
4040 }
4041 return;
4042 }
4043 };
4044
4045 // Certain directories may have FS changes, but do not lead to git data changes that Zed cares about.
4046 // Ignore these, to avoid Zed unnecessarily rescanning git metadata.
4047 let skipped_files_in_dot_git = [COMMIT_MESSAGE, INDEX_LOCK];
4048 let skipped_dirs_in_dot_git = [FSMONITOR_DAEMON, LFS_DIR];
4049
4050 let mut relative_paths = Vec::with_capacity(abs_paths.len());
4051 let mut dot_git_abs_paths = Vec::new();
4052 let mut work_dirs_needing_exclude_update = Vec::new();
4053 abs_paths.sort_unstable();
4054 abs_paths.dedup_by(|a, b| a.starts_with(b));
4055 {
4056 let snapshot = &self.state.lock().await.snapshot;
4057
4058 let mut ranges_to_drop = SmallVec::<[Range<usize>; 4]>::new();
4059
4060 fn skip_ix(ranges: &mut SmallVec<[Range<usize>; 4]>, ix: usize) {
4061 if let Some(last_range) = ranges.last_mut()
4062 && last_range.end == ix
4063 {
4064 last_range.end += 1;
4065 } else {
4066 ranges.push(ix..ix + 1);
4067 }
4068 }
4069
4070 for (ix, abs_path) in abs_paths.iter().enumerate() {
4071 let abs_path = &SanitizedPath::new(&abs_path);
4072
4073 let mut is_git_related = false;
4074 let mut dot_git_paths = None;
4075
4076 for ancestor in abs_path.as_path().ancestors() {
4077 if is_git_dir(ancestor, self.fs.as_ref()).await {
4078 let path_in_git_dir = abs_path
4079 .as_path()
4080 .strip_prefix(ancestor)
4081 .expect("stripping off the ancestor");
4082 dot_git_paths = Some((ancestor.to_owned(), path_in_git_dir.to_owned()));
4083 break;
4084 }
4085 }
4086
4087 if let Some((dot_git_abs_path, path_in_git_dir)) = dot_git_paths {
4088 if skipped_files_in_dot_git
4089 .iter()
4090 .any(|skipped| OsStr::new(skipped) == path_in_git_dir.as_path().as_os_str())
4091 || skipped_dirs_in_dot_git.iter().any(|skipped_git_subdir| {
4092 path_in_git_dir.starts_with(skipped_git_subdir)
4093 })
4094 {
4095 log::debug!(
4096 "ignoring event {abs_path:?} as it's in the .git directory among skipped files or directories"
4097 );
4098 skip_ix(&mut ranges_to_drop, ix);
4099 continue;
4100 }
4101
4102 is_git_related = true;
4103 if !dot_git_abs_paths.contains(&dot_git_abs_path) {
4104 dot_git_abs_paths.push(dot_git_abs_path);
4105 }
4106 }
4107
4108 let relative_path = if let Ok(path) = abs_path.strip_prefix(&root_canonical_path)
4109 && let Ok(path) = RelPath::new(path, PathStyle::local())
4110 {
4111 path
4112 } else {
4113 if is_git_related {
4114 log::debug!(
4115 "ignoring event {abs_path:?}, since it's in git dir outside of root path {root_canonical_path:?}",
4116 );
4117 } else {
4118 log::error!(
4119 "ignoring event {abs_path:?} outside of root path {root_canonical_path:?}",
4120 );
4121 }
4122 skip_ix(&mut ranges_to_drop, ix);
4123 continue;
4124 };
4125
4126 let absolute_path = abs_path.to_path_buf();
4127 if absolute_path.ends_with(Path::new(DOT_GIT).join(REPO_EXCLUDE)) {
4128 if let Some(repository) = snapshot
4129 .git_repositories
4130 .values()
4131 .find(|repo| repo.common_dir_abs_path.join(REPO_EXCLUDE) == absolute_path)
4132 {
4133 work_dirs_needing_exclude_update
4134 .push(repository.work_directory_abs_path.clone());
4135 }
4136 }
4137
4138 if abs_path.file_name() == Some(OsStr::new(GITIGNORE)) {
4139 for (_, repo) in snapshot
4140 .git_repositories
4141 .iter()
4142 .filter(|(_, repo)| repo.directory_contains(&relative_path))
4143 {
4144 if !dot_git_abs_paths.iter().any(|dot_git_abs_path| {
4145 dot_git_abs_path == repo.common_dir_abs_path.as_ref()
4146 }) {
4147 dot_git_abs_paths.push(repo.common_dir_abs_path.to_path_buf());
4148 }
4149 }
4150 }
4151
4152 let parent_dir_is_loaded = relative_path.parent().is_none_or(|parent| {
4153 snapshot
4154 .entry_for_path(parent)
4155 .is_some_and(|entry| entry.kind == EntryKind::Dir)
4156 });
4157 if !parent_dir_is_loaded {
4158 log::debug!("ignoring event {relative_path:?} within unloaded directory");
4159 skip_ix(&mut ranges_to_drop, ix);
4160 continue;
4161 }
4162
4163 if self.settings.is_path_excluded(&relative_path) {
4164 if !is_git_related {
4165 log::debug!("ignoring FS event for excluded path {relative_path:?}");
4166 }
4167 skip_ix(&mut ranges_to_drop, ix);
4168 continue;
4169 }
4170
4171 relative_paths.push(relative_path.into_arc());
4172 }
4173
4174 for range_to_drop in ranges_to_drop.into_iter().rev() {
4175 abs_paths.drain(range_to_drop);
4176 }
4177 }
4178
4179 if relative_paths.is_empty() && dot_git_abs_paths.is_empty() {
4180 return;
4181 }
4182
4183 if !work_dirs_needing_exclude_update.is_empty() {
4184 let mut state = self.state.lock().await;
4185 for work_dir_abs_path in work_dirs_needing_exclude_update {
4186 if let Some((_, needs_update)) = state
4187 .snapshot
4188 .repo_exclude_by_work_dir_abs_path
4189 .get_mut(&work_dir_abs_path)
4190 {
4191 *needs_update = true;
4192 }
4193 }
4194 }
4195
4196 self.state.lock().await.snapshot.scan_id += 1;
4197
4198 let (scan_job_tx, scan_job_rx) = channel::unbounded();
4199 log::debug!("received fs events {:?}", relative_paths);
4200 self.reload_entries_for_paths(
4201 &root_path,
4202 &root_canonical_path,
4203 &relative_paths,
4204 abs_paths,
4205 Some(scan_job_tx.clone()),
4206 )
4207 .await;
4208
4209 let affected_repo_roots = if !dot_git_abs_paths.is_empty() {
4210 self.update_git_repositories(dot_git_abs_paths).await
4211 } else {
4212 Vec::new()
4213 };
4214
4215 {
4216 let mut ignores_to_update = self.ignores_needing_update().await;
4217 ignores_to_update.extend(affected_repo_roots);
4218 let ignores_to_update = self.order_ignores(ignores_to_update).await;
4219 let snapshot = self.state.lock().await.snapshot.clone();
4220 self.update_ignore_statuses_for_paths(scan_job_tx, snapshot, ignores_to_update)
4221 .await;
4222 self.scan_dirs(false, scan_job_rx).await;
4223 }
4224
4225 {
4226 let mut state = self.state.lock().await;
4227 state.snapshot.completed_scan_id = state.snapshot.scan_id;
4228 for (_, entry) in mem::take(&mut state.removed_entries) {
4229 state.scanned_dirs.remove(&entry.id);
4230 }
4231 }
4232 self.send_status_update(false, SmallVec::new()).await;
4233 }
4234
4235 async fn update_global_gitignore(&self, abs_path: &Path) {
4236 let ignore = build_gitignore(abs_path, self.fs.as_ref())
4237 .await
4238 .log_err()
4239 .map(Arc::new);
4240 let (prev_snapshot, ignore_stack, abs_path) = {
4241 let mut state = self.state.lock().await;
4242 state.snapshot.global_gitignore = ignore;
4243 let abs_path = state.snapshot.abs_path().clone();
4244 let ignore_stack = state
4245 .snapshot
4246 .ignore_stack_for_abs_path(&abs_path, true, self.fs.as_ref())
4247 .await;
4248 (state.snapshot.clone(), ignore_stack, abs_path)
4249 };
4250 let (scan_job_tx, scan_job_rx) = channel::unbounded();
4251 self.update_ignore_statuses_for_paths(
4252 scan_job_tx,
4253 prev_snapshot,
4254 vec![(abs_path, ignore_stack)],
4255 )
4256 .await;
4257 self.scan_dirs(false, scan_job_rx).await;
4258 self.send_status_update(false, SmallVec::new()).await;
4259 }
4260
4261 async fn forcibly_load_paths(&self, paths: &[Arc<RelPath>]) -> bool {
4262 let (scan_job_tx, scan_job_rx) = channel::unbounded();
4263 {
4264 let mut state = self.state.lock().await;
4265 let root_path = state.snapshot.abs_path.clone();
4266 for path in paths {
4267 for ancestor in path.ancestors() {
4268 if let Some(entry) = state.snapshot.entry_for_path(ancestor)
4269 && entry.kind == EntryKind::UnloadedDir
4270 {
4271 let abs_path = root_path.join(ancestor.as_std_path());
4272 state
4273 .enqueue_scan_dir(
4274 abs_path.into(),
4275 entry,
4276 &scan_job_tx,
4277 self.fs.as_ref(),
4278 )
4279 .await;
4280 state.paths_to_scan.insert(path.clone());
4281 break;
4282 }
4283 }
4284 }
4285 drop(scan_job_tx);
4286 }
4287 while let Ok(job) = scan_job_rx.recv().await {
4288 self.scan_dir(&job).await.log_err();
4289 }
4290
4291 !mem::take(&mut self.state.lock().await.paths_to_scan).is_empty()
4292 }
4293
4294 async fn scan_dirs(
4295 &self,
4296 enable_progress_updates: bool,
4297 scan_jobs_rx: channel::Receiver<ScanJob>,
4298 ) {
4299 if self
4300 .status_updates_tx
4301 .unbounded_send(ScanState::Started)
4302 .is_err()
4303 {
4304 return;
4305 }
4306
4307 let progress_update_count = AtomicUsize::new(0);
4308 self.executor
4309 .scoped_priority(Priority::Low, |scope| {
4310 for _ in 0..self.executor.num_cpus() {
4311 scope.spawn(async {
4312 let mut last_progress_update_count = 0;
4313 let progress_update_timer = self.progress_timer(enable_progress_updates).fuse();
4314 futures::pin_mut!(progress_update_timer);
4315
4316 loop {
4317 select_biased! {
4318 // Process any path refresh requests before moving on to process
4319 // the scan queue, so that user operations are prioritized.
4320 request = self.next_scan_request().fuse() => {
4321 let Ok(request) = request else { break };
4322 if !self.process_scan_request(request, true).await {
4323 return;
4324 }
4325 }
4326
4327 // Send periodic progress updates to the worktree. Use an atomic counter
4328 // to ensure that only one of the workers sends a progress update after
4329 // the update interval elapses.
4330 _ = progress_update_timer => {
4331 match progress_update_count.compare_exchange(
4332 last_progress_update_count,
4333 last_progress_update_count + 1,
4334 SeqCst,
4335 SeqCst
4336 ) {
4337 Ok(_) => {
4338 last_progress_update_count += 1;
4339 self.send_status_update(true, SmallVec::new()).await;
4340 }
4341 Err(count) => {
4342 last_progress_update_count = count;
4343 }
4344 }
4345 progress_update_timer.set(self.progress_timer(enable_progress_updates).fuse());
4346 }
4347
4348 // Recursively load directories from the file system.
4349 job = scan_jobs_rx.recv().fuse() => {
4350 let Ok(job) = job else { break };
4351 if let Err(err) = self.scan_dir(&job).await
4352 && job.path.is_empty() {
4353 log::error!("error scanning directory {:?}: {}", job.abs_path, err);
4354 }
4355 }
4356 }
4357 }
4358 });
4359 }
4360 })
4361 .await;
4362 }
4363
4364 async fn send_status_update(
4365 &self,
4366 scanning: bool,
4367 barrier: SmallVec<[barrier::Sender; 1]>,
4368 ) -> bool {
4369 let mut state = self.state.lock().await;
4370 if state.changed_paths.is_empty() && scanning {
4371 return true;
4372 }
4373
4374 let new_snapshot = state.snapshot.clone();
4375 let old_snapshot = mem::replace(&mut state.prev_snapshot, new_snapshot.snapshot.clone());
4376 let changes = build_diff(
4377 self.phase,
4378 &old_snapshot,
4379 &new_snapshot,
4380 &state.changed_paths,
4381 );
4382 state.changed_paths.clear();
4383
4384 self.status_updates_tx
4385 .unbounded_send(ScanState::Updated {
4386 snapshot: new_snapshot,
4387 changes,
4388 scanning,
4389 barrier,
4390 })
4391 .is_ok()
4392 }
4393
4394 async fn scan_dir(&self, job: &ScanJob) -> Result<()> {
4395 let root_abs_path;
4396 let root_char_bag;
4397 {
4398 let snapshot = &self.state.lock().await.snapshot;
4399 if self.settings.is_path_excluded(&job.path) {
4400 log::error!("skipping excluded directory {:?}", job.path);
4401 return Ok(());
4402 }
4403 log::trace!("scanning directory {:?}", job.path);
4404 root_abs_path = snapshot.abs_path().clone();
4405 root_char_bag = snapshot.root_char_bag;
4406 }
4407
4408 let next_entry_id = self.next_entry_id.clone();
4409 let mut ignore_stack = job.ignore_stack.clone();
4410 let mut new_ignore = None;
4411 let mut root_canonical_path = None;
4412 let mut new_entries: Vec<Entry> = Vec::new();
4413 let mut new_jobs: Vec<Option<ScanJob>> = Vec::new();
4414 let mut child_paths = self
4415 .fs
4416 .read_dir(&job.abs_path)
4417 .await?
4418 .filter_map(|entry| async {
4419 match entry {
4420 Ok(entry) => Some(entry),
4421 Err(error) => {
4422 log::error!("error processing entry {:?}", error);
4423 None
4424 }
4425 }
4426 })
4427 .collect::<Vec<_>>()
4428 .await;
4429
4430 // Ensure that .git and .gitignore are processed first.
4431 swap_to_front(&mut child_paths, GITIGNORE);
4432 swap_to_front(&mut child_paths, DOT_GIT);
4433
4434 if let Some(path) = child_paths.first()
4435 && path.ends_with(DOT_GIT)
4436 {
4437 ignore_stack.repo_root = Some(job.abs_path.clone());
4438 }
4439
4440 for child_abs_path in child_paths {
4441 let child_abs_path: Arc<Path> = child_abs_path.into();
4442 let child_name = child_abs_path.file_name().unwrap();
4443 let Some(child_path) = child_name
4444 .to_str()
4445 .and_then(|name| Some(job.path.join(RelPath::unix(name).ok()?)))
4446 else {
4447 continue;
4448 };
4449
4450 if child_name == DOT_GIT {
4451 let mut state = self.state.lock().await;
4452 state
4453 .insert_git_repository(
4454 child_path.clone(),
4455 self.fs.as_ref(),
4456 self.watcher.as_ref(),
4457 )
4458 .await;
4459 } else if child_name == GITIGNORE {
4460 match build_gitignore(&child_abs_path, self.fs.as_ref()).await {
4461 Ok(ignore) => {
4462 let ignore = Arc::new(ignore);
4463 ignore_stack = ignore_stack
4464 .append(IgnoreKind::Gitignore(job.abs_path.clone()), ignore.clone());
4465 new_ignore = Some(ignore);
4466 }
4467 Err(error) => {
4468 log::error!(
4469 "error loading .gitignore file {:?} - {:?}",
4470 child_name,
4471 error
4472 );
4473 }
4474 }
4475 }
4476
4477 if self.settings.is_path_excluded(&child_path) {
4478 log::debug!("skipping excluded child entry {child_path:?}");
4479 self.state
4480 .lock()
4481 .await
4482 .remove_path(&child_path, self.watcher.as_ref());
4483 continue;
4484 }
4485
4486 let child_metadata = match self.fs.metadata(&child_abs_path).await {
4487 Ok(Some(metadata)) => metadata,
4488 Ok(None) => continue,
4489 Err(err) => {
4490 log::error!("error processing {:?}: {err:#}", child_abs_path.display());
4491 continue;
4492 }
4493 };
4494
4495 let mut child_entry = Entry::new(
4496 child_path.clone(),
4497 &child_metadata,
4498 ProjectEntryId::new(&next_entry_id),
4499 root_char_bag,
4500 None,
4501 );
4502
4503 if job.is_external {
4504 child_entry.is_external = true;
4505 } else if child_metadata.is_symlink {
4506 let canonical_path = match self.fs.canonicalize(&child_abs_path).await {
4507 Ok(path) => path,
4508 Err(err) => {
4509 log::error!("error reading target of symlink {child_abs_path:?}: {err:#}",);
4510 continue;
4511 }
4512 };
4513
4514 // lazily canonicalize the root path in order to determine if
4515 // symlinks point outside of the worktree.
4516 let root_canonical_path = match &root_canonical_path {
4517 Some(path) => path,
4518 None => match self.fs.canonicalize(&root_abs_path).await {
4519 Ok(path) => root_canonical_path.insert(path),
4520 Err(err) => {
4521 log::error!("error canonicalizing root {:?}: {:?}", root_abs_path, err);
4522 continue;
4523 }
4524 },
4525 };
4526
4527 if !canonical_path.starts_with(root_canonical_path) {
4528 child_entry.is_external = true;
4529 }
4530
4531 child_entry.canonical_path = Some(canonical_path.into());
4532 }
4533
4534 if child_entry.is_dir() {
4535 child_entry.is_ignored = ignore_stack.is_abs_path_ignored(&child_abs_path, true);
4536 child_entry.is_always_included =
4537 self.settings.is_path_always_included(&child_path, true);
4538
4539 // Avoid recursing until crash in the case of a recursive symlink
4540 if job.ancestor_inodes.contains(&child_entry.inode) {
4541 new_jobs.push(None);
4542 } else {
4543 let mut ancestor_inodes = job.ancestor_inodes.clone();
4544 ancestor_inodes.insert(child_entry.inode);
4545
4546 new_jobs.push(Some(ScanJob {
4547 abs_path: child_abs_path.clone(),
4548 path: child_path,
4549 is_external: child_entry.is_external,
4550 ignore_stack: if child_entry.is_ignored {
4551 IgnoreStack::all()
4552 } else {
4553 ignore_stack.clone()
4554 },
4555 ancestor_inodes,
4556 scan_queue: job.scan_queue.clone(),
4557 }));
4558 }
4559 } else {
4560 child_entry.is_ignored = ignore_stack.is_abs_path_ignored(&child_abs_path, false);
4561 child_entry.is_always_included =
4562 self.settings.is_path_always_included(&child_path, false);
4563 }
4564
4565 {
4566 let relative_path = job
4567 .path
4568 .join(RelPath::unix(child_name.to_str().unwrap()).unwrap());
4569 if self.is_path_private(&relative_path) {
4570 log::debug!("detected private file: {relative_path:?}");
4571 child_entry.is_private = true;
4572 }
4573 if self.settings.is_path_hidden(&relative_path) {
4574 log::debug!("detected hidden file: {relative_path:?}");
4575 child_entry.is_hidden = true;
4576 }
4577 }
4578
4579 new_entries.push(child_entry);
4580 }
4581
4582 let mut state = self.state.lock().await;
4583
4584 // Identify any subdirectories that should not be scanned.
4585 let mut job_ix = 0;
4586 for entry in &mut new_entries {
4587 state.reuse_entry_id(entry);
4588 if entry.is_dir() {
4589 if state.should_scan_directory(entry) {
4590 job_ix += 1;
4591 } else {
4592 log::debug!("defer scanning directory {:?}", entry.path);
4593 entry.kind = EntryKind::UnloadedDir;
4594 new_jobs.remove(job_ix);
4595 }
4596 }
4597 if entry.is_always_included {
4598 state
4599 .snapshot
4600 .always_included_entries
4601 .push(entry.path.clone());
4602 }
4603 }
4604
4605 state.populate_dir(job.path.clone(), new_entries, new_ignore);
4606 self.watcher.add(job.abs_path.as_ref()).log_err();
4607
4608 for new_job in new_jobs.into_iter().flatten() {
4609 job.scan_queue
4610 .try_send(new_job)
4611 .expect("channel is unbounded");
4612 }
4613
4614 Ok(())
4615 }
4616
4617 /// All list arguments should be sorted before calling this function
4618 async fn reload_entries_for_paths(
4619 &self,
4620 root_abs_path: &SanitizedPath,
4621 root_canonical_path: &SanitizedPath,
4622 relative_paths: &[Arc<RelPath>],
4623 abs_paths: Vec<PathBuf>,
4624 scan_queue_tx: Option<Sender<ScanJob>>,
4625 ) {
4626 // grab metadata for all requested paths
4627 let metadata = futures::future::join_all(
4628 abs_paths
4629 .iter()
4630 .map(|abs_path| async move {
4631 let metadata = self.fs.metadata(abs_path).await?;
4632 if let Some(metadata) = metadata {
4633 let canonical_path = self.fs.canonicalize(abs_path).await?;
4634
4635 // If we're on a case-insensitive filesystem (default on macOS), we want
4636 // to only ignore metadata for non-symlink files if their absolute-path matches
4637 // the canonical-path.
4638 // Because if not, this might be a case-only-renaming (`mv test.txt TEST.TXT`)
4639 // and we want to ignore the metadata for the old path (`test.txt`) so it's
4640 // treated as removed.
4641 if !self.fs_case_sensitive && !metadata.is_symlink {
4642 let canonical_file_name = canonical_path.file_name();
4643 let file_name = abs_path.file_name();
4644 if canonical_file_name != file_name {
4645 return Ok(None);
4646 }
4647 }
4648
4649 anyhow::Ok(Some((metadata, SanitizedPath::new_arc(&canonical_path))))
4650 } else {
4651 Ok(None)
4652 }
4653 })
4654 .collect::<Vec<_>>(),
4655 )
4656 .await;
4657
4658 let mut new_ancestor_repo = if relative_paths.iter().any(|path| path.is_empty()) {
4659 Some(discover_ancestor_git_repo(self.fs.clone(), &root_abs_path).await)
4660 } else {
4661 None
4662 };
4663
4664 let mut state = self.state.lock().await;
4665 let doing_recursive_update = scan_queue_tx.is_some();
4666
4667 // Remove any entries for paths that no longer exist or are being recursively
4668 // refreshed. Do this before adding any new entries, so that renames can be
4669 // detected regardless of the order of the paths.
4670 for (path, metadata) in relative_paths.iter().zip(metadata.iter()) {
4671 if matches!(metadata, Ok(None)) || doing_recursive_update {
4672 state.remove_path(path, self.watcher.as_ref());
4673 }
4674 }
4675
4676 for (path, metadata) in relative_paths.iter().zip(metadata.into_iter()) {
4677 let abs_path: Arc<Path> = root_abs_path.join(path.as_std_path()).into();
4678 match metadata {
4679 Ok(Some((metadata, canonical_path))) => {
4680 let ignore_stack = state
4681 .snapshot
4682 .ignore_stack_for_abs_path(&abs_path, metadata.is_dir, self.fs.as_ref())
4683 .await;
4684 let is_external = !canonical_path.starts_with(&root_canonical_path);
4685 let entry_id = state.entry_id_for(self.next_entry_id.as_ref(), path, &metadata);
4686 let mut fs_entry = Entry::new(
4687 path.clone(),
4688 &metadata,
4689 entry_id,
4690 state.snapshot.root_char_bag,
4691 if metadata.is_symlink {
4692 Some(canonical_path.as_path().to_path_buf().into())
4693 } else {
4694 None
4695 },
4696 );
4697
4698 let is_dir = fs_entry.is_dir();
4699 fs_entry.is_ignored = ignore_stack.is_abs_path_ignored(&abs_path, is_dir);
4700 fs_entry.is_external = is_external;
4701 fs_entry.is_private = self.is_path_private(path);
4702 fs_entry.is_always_included =
4703 self.settings.is_path_always_included(path, is_dir);
4704 fs_entry.is_hidden = self.settings.is_path_hidden(path);
4705
4706 if let (Some(scan_queue_tx), true) = (&scan_queue_tx, is_dir) {
4707 if state.should_scan_directory(&fs_entry)
4708 || (fs_entry.path.is_empty()
4709 && abs_path.file_name() == Some(OsStr::new(DOT_GIT)))
4710 {
4711 state
4712 .enqueue_scan_dir(
4713 abs_path,
4714 &fs_entry,
4715 scan_queue_tx,
4716 self.fs.as_ref(),
4717 )
4718 .await;
4719 } else {
4720 fs_entry.kind = EntryKind::UnloadedDir;
4721 }
4722 }
4723
4724 state
4725 .insert_entry(fs_entry.clone(), self.fs.as_ref(), self.watcher.as_ref())
4726 .await;
4727
4728 if path.is_empty()
4729 && let Some((ignores, exclude, repo)) = new_ancestor_repo.take()
4730 {
4731 log::trace!("updating ancestor git repository");
4732 state.snapshot.ignores_by_parent_abs_path.extend(ignores);
4733 if let Some((ancestor_dot_git, work_directory)) = repo {
4734 if let Some(exclude) = exclude {
4735 let work_directory_abs_path = self
4736 .state
4737 .lock()
4738 .await
4739 .snapshot
4740 .work_directory_abs_path(&work_directory);
4741
4742 state
4743 .snapshot
4744 .repo_exclude_by_work_dir_abs_path
4745 .insert(work_directory_abs_path.into(), (exclude, false));
4746 }
4747 state
4748 .insert_git_repository_for_path(
4749 work_directory,
4750 ancestor_dot_git.into(),
4751 self.fs.as_ref(),
4752 self.watcher.as_ref(),
4753 )
4754 .await
4755 .log_err();
4756 }
4757 }
4758 }
4759 Ok(None) => {
4760 self.remove_repo_path(path.clone(), &mut state.snapshot);
4761 }
4762 Err(err) => {
4763 log::error!("error reading file {abs_path:?} on event: {err:#}");
4764 }
4765 }
4766 }
4767
4768 util::extend_sorted(
4769 &mut state.changed_paths,
4770 relative_paths.iter().cloned(),
4771 usize::MAX,
4772 Ord::cmp,
4773 );
4774 }
4775
4776 fn remove_repo_path(&self, path: Arc<RelPath>, snapshot: &mut LocalSnapshot) -> Option<()> {
4777 if !path.components().any(|component| component == DOT_GIT)
4778 && let Some(local_repo) = snapshot.local_repo_for_work_directory_path(&path)
4779 {
4780 let id = local_repo.work_directory_id;
4781 log::debug!("remove repo path: {:?}", path);
4782 snapshot.git_repositories.remove(&id);
4783 return Some(());
4784 }
4785
4786 Some(())
4787 }
4788
4789 async fn update_ignore_statuses_for_paths(
4790 &self,
4791 scan_job_tx: Sender<ScanJob>,
4792 prev_snapshot: LocalSnapshot,
4793 ignores_to_update: Vec<(Arc<Path>, IgnoreStack)>,
4794 ) {
4795 let (ignore_queue_tx, ignore_queue_rx) = channel::unbounded();
4796 {
4797 for (parent_abs_path, ignore_stack) in ignores_to_update {
4798 ignore_queue_tx
4799 .send_blocking(UpdateIgnoreStatusJob {
4800 abs_path: parent_abs_path,
4801 ignore_stack,
4802 ignore_queue: ignore_queue_tx.clone(),
4803 scan_queue: scan_job_tx.clone(),
4804 })
4805 .unwrap();
4806 }
4807 }
4808 drop(ignore_queue_tx);
4809
4810 self.executor
4811 .scoped(|scope| {
4812 for _ in 0..self.executor.num_cpus() {
4813 scope.spawn(async {
4814 loop {
4815 select_biased! {
4816 // Process any path refresh requests before moving on to process
4817 // the queue of ignore statuses.
4818 request = self.next_scan_request().fuse() => {
4819 let Ok(request) = request else { break };
4820 if !self.process_scan_request(request, true).await {
4821 return;
4822 }
4823 }
4824
4825 // Recursively process directories whose ignores have changed.
4826 job = ignore_queue_rx.recv().fuse() => {
4827 let Ok(job) = job else { break };
4828 self.update_ignore_status(job, &prev_snapshot).await;
4829 }
4830 }
4831 }
4832 });
4833 }
4834 })
4835 .await;
4836 }
4837
4838 async fn ignores_needing_update(&self) -> Vec<Arc<Path>> {
4839 let mut ignores_to_update = Vec::new();
4840 let mut excludes_to_load: Vec<(Arc<Path>, PathBuf)> = Vec::new();
4841
4842 // First pass: collect updates and drop stale entries without awaiting.
4843 {
4844 let snapshot = &mut self.state.lock().await.snapshot;
4845 let abs_path = snapshot.abs_path.clone();
4846 let mut repo_exclude_keys_to_remove: Vec<Arc<Path>> = Vec::new();
4847
4848 for (work_dir_abs_path, (_, needs_update)) in
4849 snapshot.repo_exclude_by_work_dir_abs_path.iter_mut()
4850 {
4851 let repository = snapshot
4852 .git_repositories
4853 .iter()
4854 .find(|(_, repo)| &repo.work_directory_abs_path == work_dir_abs_path);
4855
4856 if *needs_update {
4857 *needs_update = false;
4858 ignores_to_update.push(work_dir_abs_path.clone());
4859
4860 if let Some((_, repository)) = repository {
4861 let exclude_abs_path = repository.common_dir_abs_path.join(REPO_EXCLUDE);
4862 excludes_to_load.push((work_dir_abs_path.clone(), exclude_abs_path));
4863 }
4864 }
4865
4866 if repository.is_none() {
4867 repo_exclude_keys_to_remove.push(work_dir_abs_path.clone());
4868 }
4869 }
4870
4871 for key in repo_exclude_keys_to_remove {
4872 snapshot.repo_exclude_by_work_dir_abs_path.remove(&key);
4873 }
4874
4875 snapshot
4876 .ignores_by_parent_abs_path
4877 .retain(|parent_abs_path, (_, needs_update)| {
4878 if let Ok(parent_path) = parent_abs_path.strip_prefix(abs_path.as_path())
4879 && let Some(parent_path) =
4880 RelPath::new(&parent_path, PathStyle::local()).log_err()
4881 {
4882 if *needs_update {
4883 *needs_update = false;
4884 if snapshot.snapshot.entry_for_path(&parent_path).is_some() {
4885 ignores_to_update.push(parent_abs_path.clone());
4886 }
4887 }
4888
4889 let ignore_path = parent_path.join(RelPath::unix(GITIGNORE).unwrap());
4890 if snapshot.snapshot.entry_for_path(&ignore_path).is_none() {
4891 return false;
4892 }
4893 }
4894 true
4895 });
4896 }
4897
4898 // Load gitignores asynchronously (outside the lock)
4899 let mut loaded_excludes: Vec<(Arc<Path>, Arc<Gitignore>)> = Vec::new();
4900 for (work_dir_abs_path, exclude_abs_path) in excludes_to_load {
4901 if let Ok(current_exclude) = build_gitignore(&exclude_abs_path, self.fs.as_ref()).await
4902 {
4903 loaded_excludes.push((work_dir_abs_path, Arc::new(current_exclude)));
4904 }
4905 }
4906
4907 // Second pass: apply updates.
4908 if !loaded_excludes.is_empty() {
4909 let snapshot = &mut self.state.lock().await.snapshot;
4910
4911 for (work_dir_abs_path, exclude) in loaded_excludes {
4912 if let Some((existing_exclude, _)) = snapshot
4913 .repo_exclude_by_work_dir_abs_path
4914 .get_mut(&work_dir_abs_path)
4915 {
4916 *existing_exclude = exclude;
4917 }
4918 }
4919 }
4920
4921 ignores_to_update
4922 }
4923
4924 async fn order_ignores(&self, mut ignores: Vec<Arc<Path>>) -> Vec<(Arc<Path>, IgnoreStack)> {
4925 let fs = self.fs.clone();
4926 let snapshot = self.state.lock().await.snapshot.clone();
4927 ignores.sort_unstable();
4928 let mut ignores_to_update = ignores.into_iter().peekable();
4929
4930 let mut result = vec![];
4931 while let Some(parent_abs_path) = ignores_to_update.next() {
4932 while ignores_to_update
4933 .peek()
4934 .map_or(false, |p| p.starts_with(&parent_abs_path))
4935 {
4936 ignores_to_update.next().unwrap();
4937 }
4938 let ignore_stack = snapshot
4939 .ignore_stack_for_abs_path(&parent_abs_path, true, fs.as_ref())
4940 .await;
4941 result.push((parent_abs_path, ignore_stack));
4942 }
4943
4944 result
4945 }
4946
4947 async fn update_ignore_status(&self, job: UpdateIgnoreStatusJob, snapshot: &LocalSnapshot) {
4948 log::trace!("update ignore status {:?}", job.abs_path);
4949
4950 let mut ignore_stack = job.ignore_stack;
4951 if let Some((ignore, _)) = snapshot.ignores_by_parent_abs_path.get(&job.abs_path) {
4952 ignore_stack =
4953 ignore_stack.append(IgnoreKind::Gitignore(job.abs_path.clone()), ignore.clone());
4954 }
4955
4956 let mut entries_by_id_edits = Vec::new();
4957 let mut entries_by_path_edits = Vec::new();
4958 let Some(path) = job
4959 .abs_path
4960 .strip_prefix(snapshot.abs_path.as_path())
4961 .map_err(|_| {
4962 anyhow::anyhow!(
4963 "Failed to strip prefix '{}' from path '{}'",
4964 snapshot.abs_path.as_path().display(),
4965 job.abs_path.display()
4966 )
4967 })
4968 .log_err()
4969 else {
4970 return;
4971 };
4972
4973 let Some(path) = RelPath::new(&path, PathStyle::local()).log_err() else {
4974 return;
4975 };
4976
4977 if let Ok(Some(metadata)) = self.fs.metadata(&job.abs_path.join(DOT_GIT)).await
4978 && metadata.is_dir
4979 {
4980 ignore_stack.repo_root = Some(job.abs_path.clone());
4981 }
4982
4983 for mut entry in snapshot.child_entries(&path).cloned() {
4984 let was_ignored = entry.is_ignored;
4985 let abs_path: Arc<Path> = snapshot.absolutize(&entry.path).into();
4986 entry.is_ignored = ignore_stack.is_abs_path_ignored(&abs_path, entry.is_dir());
4987
4988 if entry.is_dir() {
4989 let child_ignore_stack = if entry.is_ignored {
4990 IgnoreStack::all()
4991 } else {
4992 ignore_stack.clone()
4993 };
4994
4995 // Scan any directories that were previously ignored and weren't previously scanned.
4996 if was_ignored && !entry.is_ignored && entry.kind.is_unloaded() {
4997 let state = self.state.lock().await;
4998 if state.should_scan_directory(&entry) {
4999 state
5000 .enqueue_scan_dir(
5001 abs_path.clone(),
5002 &entry,
5003 &job.scan_queue,
5004 self.fs.as_ref(),
5005 )
5006 .await;
5007 }
5008 }
5009
5010 job.ignore_queue
5011 .send(UpdateIgnoreStatusJob {
5012 abs_path: abs_path.clone(),
5013 ignore_stack: child_ignore_stack,
5014 ignore_queue: job.ignore_queue.clone(),
5015 scan_queue: job.scan_queue.clone(),
5016 })
5017 .await
5018 .unwrap();
5019 }
5020
5021 if entry.is_ignored != was_ignored {
5022 let mut path_entry = snapshot.entries_by_id.get(&entry.id, ()).unwrap().clone();
5023 path_entry.scan_id = snapshot.scan_id;
5024 path_entry.is_ignored = entry.is_ignored;
5025 entries_by_id_edits.push(Edit::Insert(path_entry));
5026 entries_by_path_edits.push(Edit::Insert(entry));
5027 }
5028 }
5029
5030 let state = &mut self.state.lock().await;
5031 for edit in &entries_by_path_edits {
5032 if let Edit::Insert(entry) = edit
5033 && let Err(ix) = state.changed_paths.binary_search(&entry.path)
5034 {
5035 state.changed_paths.insert(ix, entry.path.clone());
5036 }
5037 }
5038
5039 state
5040 .snapshot
5041 .entries_by_path
5042 .edit(entries_by_path_edits, ());
5043 state.snapshot.entries_by_id.edit(entries_by_id_edits, ());
5044 }
5045
5046 async fn update_git_repositories(&self, dot_git_paths: Vec<PathBuf>) -> Vec<Arc<Path>> {
5047 log::trace!("reloading repositories: {dot_git_paths:?}");
5048 let mut state = self.state.lock().await;
5049 let scan_id = state.snapshot.scan_id;
5050 let mut affected_repo_roots = Vec::new();
5051 for dot_git_dir in dot_git_paths {
5052 let existing_repository_entry =
5053 state
5054 .snapshot
5055 .git_repositories
5056 .iter()
5057 .find_map(|(_, repo)| {
5058 let dot_git_dir = SanitizedPath::new(&dot_git_dir);
5059 if SanitizedPath::new(repo.common_dir_abs_path.as_ref()) == dot_git_dir
5060 || SanitizedPath::new(repo.repository_dir_abs_path.as_ref())
5061 == dot_git_dir
5062 {
5063 Some(repo.clone())
5064 } else {
5065 None
5066 }
5067 });
5068
5069 match existing_repository_entry {
5070 None => {
5071 let Ok(relative) = dot_git_dir.strip_prefix(state.snapshot.abs_path()) else {
5072 debug_panic!(
5073 "update_git_repositories called with .git directory outside the worktree root"
5074 );
5075 return Vec::new();
5076 };
5077 affected_repo_roots.push(dot_git_dir.parent().unwrap().into());
5078 state
5079 .insert_git_repository(
5080 RelPath::new(relative, PathStyle::local())
5081 .unwrap()
5082 .into_arc(),
5083 self.fs.as_ref(),
5084 self.watcher.as_ref(),
5085 )
5086 .await;
5087 }
5088 Some(local_repository) => {
5089 state.snapshot.git_repositories.update(
5090 &local_repository.work_directory_id,
5091 |entry| {
5092 entry.git_dir_scan_id = scan_id;
5093 },
5094 );
5095 }
5096 };
5097 }
5098
5099 // Remove any git repositories whose .git entry no longer exists.
5100 let snapshot = &mut state.snapshot;
5101 let mut ids_to_preserve = HashSet::default();
5102 for (&work_directory_id, entry) in snapshot.git_repositories.iter() {
5103 let exists_in_snapshot =
5104 snapshot
5105 .entry_for_id(work_directory_id)
5106 .is_some_and(|entry| {
5107 snapshot
5108 .entry_for_path(&entry.path.join(RelPath::unix(DOT_GIT).unwrap()))
5109 .is_some()
5110 });
5111
5112 if exists_in_snapshot
5113 || matches!(
5114 self.fs.metadata(&entry.common_dir_abs_path).await,
5115 Ok(Some(_))
5116 )
5117 {
5118 ids_to_preserve.insert(work_directory_id);
5119 }
5120 }
5121
5122 snapshot
5123 .git_repositories
5124 .retain(|work_directory_id, entry| {
5125 let preserve = ids_to_preserve.contains(work_directory_id);
5126 if !preserve {
5127 affected_repo_roots.push(entry.dot_git_abs_path.parent().unwrap().into());
5128 snapshot
5129 .repo_exclude_by_work_dir_abs_path
5130 .remove(&entry.work_directory_abs_path);
5131 }
5132 preserve
5133 });
5134
5135 affected_repo_roots
5136 }
5137
5138 async fn progress_timer(&self, running: bool) {
5139 if !running {
5140 return futures::future::pending().await;
5141 }
5142
5143 #[cfg(feature = "test-support")]
5144 if self.fs.is_fake() {
5145 return self.executor.simulate_random_delay().await;
5146 }
5147
5148 self.executor.timer(FS_WATCH_LATENCY).await
5149 }
5150
5151 fn is_path_private(&self, path: &RelPath) -> bool {
5152 !self.share_private_files && self.settings.is_path_private(path)
5153 }
5154
5155 async fn next_scan_request(&self) -> Result<ScanRequest> {
5156 let mut request = self.scan_requests_rx.recv().await?;
5157 while let Ok(next_request) = self.scan_requests_rx.try_recv() {
5158 request.relative_paths.extend(next_request.relative_paths);
5159 request.done.extend(next_request.done);
5160 }
5161 Ok(request)
5162 }
5163}
5164
5165async fn discover_ancestor_git_repo(
5166 fs: Arc<dyn Fs>,
5167 root_abs_path: &SanitizedPath,
5168) -> (
5169 HashMap<Arc<Path>, (Arc<Gitignore>, bool)>,
5170 Option<Arc<Gitignore>>,
5171 Option<(PathBuf, WorkDirectory)>,
5172) {
5173 let mut exclude = None;
5174 let mut ignores = HashMap::default();
5175 for (index, ancestor) in root_abs_path.as_path().ancestors().enumerate() {
5176 if index != 0 {
5177 if ancestor == paths::home_dir() {
5178 // Unless $HOME is itself the worktree root, don't consider it as a
5179 // containing git repository---expensive and likely unwanted.
5180 break;
5181 } else if let Ok(ignore) = build_gitignore(&ancestor.join(GITIGNORE), fs.as_ref()).await
5182 {
5183 ignores.insert(ancestor.into(), (ignore.into(), false));
5184 }
5185 }
5186
5187 let ancestor_dot_git = ancestor.join(DOT_GIT);
5188 log::trace!("considering ancestor: {ancestor_dot_git:?}");
5189 // Check whether the directory or file called `.git` exists (in the
5190 // case of worktrees it's a file.)
5191 if fs
5192 .metadata(&ancestor_dot_git)
5193 .await
5194 .is_ok_and(|metadata| metadata.is_some())
5195 {
5196 if index != 0 {
5197 // We canonicalize, since the FS events use the canonicalized path.
5198 if let Some(ancestor_dot_git) = fs.canonicalize(&ancestor_dot_git).await.log_err() {
5199 let location_in_repo = root_abs_path
5200 .as_path()
5201 .strip_prefix(ancestor)
5202 .unwrap()
5203 .into();
5204 log::info!("inserting parent git repo for this worktree: {location_in_repo:?}");
5205 // We associate the external git repo with our root folder and
5206 // also mark where in the git repo the root folder is located.
5207 return (
5208 ignores,
5209 exclude,
5210 Some((
5211 ancestor_dot_git,
5212 WorkDirectory::AboveProject {
5213 absolute_path: ancestor.into(),
5214 location_in_repo,
5215 },
5216 )),
5217 );
5218 };
5219 }
5220
5221 let repo_exclude_abs_path = ancestor_dot_git.join(REPO_EXCLUDE);
5222 if let Ok(repo_exclude) = build_gitignore(&repo_exclude_abs_path, fs.as_ref()).await {
5223 exclude = Some(Arc::new(repo_exclude));
5224 }
5225
5226 // Reached root of git repository.
5227 break;
5228 }
5229 }
5230
5231 (ignores, exclude, None)
5232}
5233
5234fn build_diff(
5235 phase: BackgroundScannerPhase,
5236 old_snapshot: &Snapshot,
5237 new_snapshot: &Snapshot,
5238 event_paths: &[Arc<RelPath>],
5239) -> UpdatedEntriesSet {
5240 use BackgroundScannerPhase::*;
5241 use PathChange::{Added, AddedOrUpdated, Loaded, Removed, Updated};
5242
5243 // Identify which paths have changed. Use the known set of changed
5244 // parent paths to optimize the search.
5245 let mut changes = Vec::new();
5246 let mut old_paths = old_snapshot.entries_by_path.cursor::<PathKey>(());
5247 let mut new_paths = new_snapshot.entries_by_path.cursor::<PathKey>(());
5248 let mut last_newly_loaded_dir_path = None;
5249 old_paths.next();
5250 new_paths.next();
5251 for path in event_paths {
5252 let path = PathKey(path.clone());
5253 if old_paths.item().is_some_and(|e| e.path < path.0) {
5254 old_paths.seek_forward(&path, Bias::Left);
5255 }
5256 if new_paths.item().is_some_and(|e| e.path < path.0) {
5257 new_paths.seek_forward(&path, Bias::Left);
5258 }
5259 loop {
5260 match (old_paths.item(), new_paths.item()) {
5261 (Some(old_entry), Some(new_entry)) => {
5262 if old_entry.path > path.0
5263 && new_entry.path > path.0
5264 && !old_entry.path.starts_with(&path.0)
5265 && !new_entry.path.starts_with(&path.0)
5266 {
5267 break;
5268 }
5269
5270 match Ord::cmp(&old_entry.path, &new_entry.path) {
5271 Ordering::Less => {
5272 changes.push((old_entry.path.clone(), old_entry.id, Removed));
5273 old_paths.next();
5274 }
5275 Ordering::Equal => {
5276 if phase == EventsReceivedDuringInitialScan {
5277 if old_entry.id != new_entry.id {
5278 changes.push((old_entry.path.clone(), old_entry.id, Removed));
5279 }
5280 // If the worktree was not fully initialized when this event was generated,
5281 // we can't know whether this entry was added during the scan or whether
5282 // it was merely updated.
5283 changes.push((
5284 new_entry.path.clone(),
5285 new_entry.id,
5286 AddedOrUpdated,
5287 ));
5288 } else if old_entry.id != new_entry.id {
5289 changes.push((old_entry.path.clone(), old_entry.id, Removed));
5290 changes.push((new_entry.path.clone(), new_entry.id, Added));
5291 } else if old_entry != new_entry {
5292 if old_entry.kind.is_unloaded() {
5293 last_newly_loaded_dir_path = Some(&new_entry.path);
5294 changes.push((new_entry.path.clone(), new_entry.id, Loaded));
5295 } else {
5296 changes.push((new_entry.path.clone(), new_entry.id, Updated));
5297 }
5298 }
5299 old_paths.next();
5300 new_paths.next();
5301 }
5302 Ordering::Greater => {
5303 let is_newly_loaded = phase == InitialScan
5304 || last_newly_loaded_dir_path
5305 .as_ref()
5306 .is_some_and(|dir| new_entry.path.starts_with(dir));
5307 changes.push((
5308 new_entry.path.clone(),
5309 new_entry.id,
5310 if is_newly_loaded { Loaded } else { Added },
5311 ));
5312 new_paths.next();
5313 }
5314 }
5315 }
5316 (Some(old_entry), None) => {
5317 changes.push((old_entry.path.clone(), old_entry.id, Removed));
5318 old_paths.next();
5319 }
5320 (None, Some(new_entry)) => {
5321 let is_newly_loaded = phase == InitialScan
5322 || last_newly_loaded_dir_path
5323 .as_ref()
5324 .is_some_and(|dir| new_entry.path.starts_with(dir));
5325 changes.push((
5326 new_entry.path.clone(),
5327 new_entry.id,
5328 if is_newly_loaded { Loaded } else { Added },
5329 ));
5330 new_paths.next();
5331 }
5332 (None, None) => break,
5333 }
5334 }
5335 }
5336
5337 changes.into()
5338}
5339
5340fn swap_to_front(child_paths: &mut Vec<PathBuf>, file: &str) {
5341 let position = child_paths
5342 .iter()
5343 .position(|path| path.file_name().unwrap() == file);
5344 if let Some(position) = position {
5345 let temp = child_paths.remove(position);
5346 child_paths.insert(0, temp);
5347 }
5348}
5349
5350fn char_bag_for_path(root_char_bag: CharBag, path: &RelPath) -> CharBag {
5351 let mut result = root_char_bag;
5352 result.extend(path.as_unix_str().chars().map(|c| c.to_ascii_lowercase()));
5353 result
5354}
5355
5356#[derive(Debug)]
5357struct ScanJob {
5358 abs_path: Arc<Path>,
5359 path: Arc<RelPath>,
5360 ignore_stack: IgnoreStack,
5361 scan_queue: Sender<ScanJob>,
5362 ancestor_inodes: TreeSet<u64>,
5363 is_external: bool,
5364}
5365
5366struct UpdateIgnoreStatusJob {
5367 abs_path: Arc<Path>,
5368 ignore_stack: IgnoreStack,
5369 ignore_queue: Sender<UpdateIgnoreStatusJob>,
5370 scan_queue: Sender<ScanJob>,
5371}
5372
5373pub trait WorktreeModelHandle {
5374 #[cfg(feature = "test-support")]
5375 fn flush_fs_events<'a>(
5376 &self,
5377 cx: &'a mut gpui::TestAppContext,
5378 ) -> futures::future::LocalBoxFuture<'a, ()>;
5379
5380 #[cfg(feature = "test-support")]
5381 fn flush_fs_events_in_root_git_repository<'a>(
5382 &self,
5383 cx: &'a mut gpui::TestAppContext,
5384 ) -> futures::future::LocalBoxFuture<'a, ()>;
5385}
5386
5387impl WorktreeModelHandle for Entity<Worktree> {
5388 // When the worktree's FS event stream sometimes delivers "redundant" events for FS changes that
5389 // occurred before the worktree was constructed. These events can cause the worktree to perform
5390 // extra directory scans, and emit extra scan-state notifications.
5391 //
5392 // This function mutates the worktree's directory and waits for those mutations to be picked up,
5393 // to ensure that all redundant FS events have already been processed.
5394 #[cfg(feature = "test-support")]
5395 fn flush_fs_events<'a>(
5396 &self,
5397 cx: &'a mut gpui::TestAppContext,
5398 ) -> futures::future::LocalBoxFuture<'a, ()> {
5399 let file_name = "fs-event-sentinel";
5400
5401 let tree = self.clone();
5402 let (fs, root_path) = self.read_with(cx, |tree, _| {
5403 let tree = tree.as_local().unwrap();
5404 (tree.fs.clone(), tree.abs_path.clone())
5405 });
5406
5407 async move {
5408 // Subscribe to events BEFORE creating the file to avoid race condition
5409 // where events fire before subscription is set up
5410 let mut events = cx.events(&tree);
5411
5412 fs.create_file(&root_path.join(file_name), Default::default())
5413 .await
5414 .unwrap();
5415
5416 // Check if condition is already met before waiting for events
5417 let file_exists = || {
5418 tree.read_with(cx, |tree, _| {
5419 tree.entry_for_path(RelPath::unix(file_name).unwrap())
5420 .is_some()
5421 })
5422 };
5423
5424 // Use select to avoid blocking indefinitely if events are delayed
5425 while !file_exists() {
5426 futures::select_biased! {
5427 _ = events.next() => {}
5428 _ = futures::FutureExt::fuse(cx.background_executor.timer(std::time::Duration::from_millis(10))) => {}
5429 }
5430 }
5431
5432 fs.remove_file(&root_path.join(file_name), Default::default())
5433 .await
5434 .unwrap();
5435
5436 // Check if condition is already met before waiting for events
5437 let file_gone = || {
5438 tree.read_with(cx, |tree, _| {
5439 tree.entry_for_path(RelPath::unix(file_name).unwrap())
5440 .is_none()
5441 })
5442 };
5443
5444 // Use select to avoid blocking indefinitely if events are delayed
5445 while !file_gone() {
5446 futures::select_biased! {
5447 _ = events.next() => {}
5448 _ = futures::FutureExt::fuse(cx.background_executor.timer(std::time::Duration::from_millis(10))) => {}
5449 }
5450 }
5451
5452 cx.update(|cx| tree.read(cx).as_local().unwrap().scan_complete())
5453 .await;
5454 }
5455 .boxed_local()
5456 }
5457
5458 // This function is similar to flush_fs_events, except that it waits for events to be flushed in
5459 // the .git folder of the root repository.
5460 // The reason for its existence is that a repository's .git folder might live *outside* of the
5461 // worktree and thus its FS events might go through a different path.
5462 // In order to flush those, we need to create artificial events in the .git folder and wait
5463 // for the repository to be reloaded.
5464 #[cfg(feature = "test-support")]
5465 fn flush_fs_events_in_root_git_repository<'a>(
5466 &self,
5467 cx: &'a mut gpui::TestAppContext,
5468 ) -> futures::future::LocalBoxFuture<'a, ()> {
5469 let file_name = "fs-event-sentinel";
5470
5471 let tree = self.clone();
5472 let (fs, root_path, mut git_dir_scan_id) = self.read_with(cx, |tree, _| {
5473 let tree = tree.as_local().unwrap();
5474 let local_repo_entry = tree
5475 .git_repositories
5476 .values()
5477 .min_by_key(|local_repo_entry| local_repo_entry.work_directory.clone())
5478 .unwrap();
5479 (
5480 tree.fs.clone(),
5481 local_repo_entry.common_dir_abs_path.clone(),
5482 local_repo_entry.git_dir_scan_id,
5483 )
5484 });
5485
5486 let scan_id_increased = |tree: &mut Worktree, git_dir_scan_id: &mut usize| {
5487 let tree = tree.as_local().unwrap();
5488 // let repository = tree.repositories.first().unwrap();
5489 let local_repo_entry = tree
5490 .git_repositories
5491 .values()
5492 .min_by_key(|local_repo_entry| local_repo_entry.work_directory.clone())
5493 .unwrap();
5494
5495 if local_repo_entry.git_dir_scan_id > *git_dir_scan_id {
5496 *git_dir_scan_id = local_repo_entry.git_dir_scan_id;
5497 true
5498 } else {
5499 false
5500 }
5501 };
5502
5503 async move {
5504 // Subscribe to events BEFORE creating the file to avoid race condition
5505 // where events fire before subscription is set up
5506 let mut events = cx.events(&tree);
5507
5508 fs.create_file(&root_path.join(file_name), Default::default())
5509 .await
5510 .unwrap();
5511
5512 // Use select to avoid blocking indefinitely if events are delayed
5513 while !tree.update(cx, |tree, _| scan_id_increased(tree, &mut git_dir_scan_id)) {
5514 futures::select_biased! {
5515 _ = events.next() => {}
5516 _ = futures::FutureExt::fuse(cx.background_executor.timer(std::time::Duration::from_millis(10))) => {}
5517 }
5518 }
5519
5520 fs.remove_file(&root_path.join(file_name), Default::default())
5521 .await
5522 .unwrap();
5523
5524 // Use select to avoid blocking indefinitely if events are delayed
5525 while !tree.update(cx, |tree, _| scan_id_increased(tree, &mut git_dir_scan_id)) {
5526 futures::select_biased! {
5527 _ = events.next() => {}
5528 _ = futures::FutureExt::fuse(cx.background_executor.timer(std::time::Duration::from_millis(10))) => {}
5529 }
5530 }
5531
5532 cx.update(|cx| tree.read(cx).as_local().unwrap().scan_complete())
5533 .await;
5534 }
5535 .boxed_local()
5536 }
5537}
5538
5539#[derive(Clone, Debug)]
5540struct TraversalProgress<'a> {
5541 max_path: &'a RelPath,
5542 count: usize,
5543 non_ignored_count: usize,
5544 file_count: usize,
5545 non_ignored_file_count: usize,
5546}
5547
5548impl TraversalProgress<'_> {
5549 fn count(&self, include_files: bool, include_dirs: bool, include_ignored: bool) -> usize {
5550 match (include_files, include_dirs, include_ignored) {
5551 (true, true, true) => self.count,
5552 (true, true, false) => self.non_ignored_count,
5553 (true, false, true) => self.file_count,
5554 (true, false, false) => self.non_ignored_file_count,
5555 (false, true, true) => self.count - self.file_count,
5556 (false, true, false) => self.non_ignored_count - self.non_ignored_file_count,
5557 (false, false, _) => 0,
5558 }
5559 }
5560}
5561
5562impl<'a> sum_tree::Dimension<'a, EntrySummary> for TraversalProgress<'a> {
5563 fn zero(_cx: ()) -> Self {
5564 Default::default()
5565 }
5566
5567 fn add_summary(&mut self, summary: &'a EntrySummary, _: ()) {
5568 self.max_path = summary.max_path.as_ref();
5569 self.count += summary.count;
5570 self.non_ignored_count += summary.non_ignored_count;
5571 self.file_count += summary.file_count;
5572 self.non_ignored_file_count += summary.non_ignored_file_count;
5573 }
5574}
5575
5576impl Default for TraversalProgress<'_> {
5577 fn default() -> Self {
5578 Self {
5579 max_path: RelPath::empty(),
5580 count: 0,
5581 non_ignored_count: 0,
5582 file_count: 0,
5583 non_ignored_file_count: 0,
5584 }
5585 }
5586}
5587
5588#[derive(Debug)]
5589pub struct Traversal<'a> {
5590 snapshot: &'a Snapshot,
5591 cursor: sum_tree::Cursor<'a, 'static, Entry, TraversalProgress<'a>>,
5592 include_ignored: bool,
5593 include_files: bool,
5594 include_dirs: bool,
5595}
5596
5597impl<'a> Traversal<'a> {
5598 fn new(
5599 snapshot: &'a Snapshot,
5600 include_files: bool,
5601 include_dirs: bool,
5602 include_ignored: bool,
5603 start_path: &RelPath,
5604 ) -> Self {
5605 let mut cursor = snapshot.entries_by_path.cursor(());
5606 cursor.seek(&TraversalTarget::path(start_path), Bias::Left);
5607 let mut traversal = Self {
5608 snapshot,
5609 cursor,
5610 include_files,
5611 include_dirs,
5612 include_ignored,
5613 };
5614 if traversal.end_offset() == traversal.start_offset() {
5615 traversal.next();
5616 }
5617 traversal
5618 }
5619
5620 pub fn advance(&mut self) -> bool {
5621 self.advance_by(1)
5622 }
5623
5624 pub fn advance_by(&mut self, count: usize) -> bool {
5625 self.cursor.seek_forward(
5626 &TraversalTarget::Count {
5627 count: self.end_offset() + count,
5628 include_dirs: self.include_dirs,
5629 include_files: self.include_files,
5630 include_ignored: self.include_ignored,
5631 },
5632 Bias::Left,
5633 )
5634 }
5635
5636 pub fn advance_to_sibling(&mut self) -> bool {
5637 while let Some(entry) = self.cursor.item() {
5638 self.cursor
5639 .seek_forward(&TraversalTarget::successor(&entry.path), Bias::Left);
5640 if let Some(entry) = self.cursor.item()
5641 && (self.include_files || !entry.is_file())
5642 && (self.include_dirs || !entry.is_dir())
5643 && (self.include_ignored || !entry.is_ignored || entry.is_always_included)
5644 {
5645 return true;
5646 }
5647 }
5648 false
5649 }
5650
5651 pub fn back_to_parent(&mut self) -> bool {
5652 let Some(parent_path) = self.cursor.item().and_then(|entry| entry.path.parent()) else {
5653 return false;
5654 };
5655 self.cursor
5656 .seek(&TraversalTarget::path(parent_path), Bias::Left)
5657 }
5658
5659 pub fn entry(&self) -> Option<&'a Entry> {
5660 self.cursor.item()
5661 }
5662
5663 pub fn snapshot(&self) -> &'a Snapshot {
5664 self.snapshot
5665 }
5666
5667 pub fn start_offset(&self) -> usize {
5668 self.cursor
5669 .start()
5670 .count(self.include_files, self.include_dirs, self.include_ignored)
5671 }
5672
5673 pub fn end_offset(&self) -> usize {
5674 self.cursor
5675 .end()
5676 .count(self.include_files, self.include_dirs, self.include_ignored)
5677 }
5678}
5679
5680impl<'a> Iterator for Traversal<'a> {
5681 type Item = &'a Entry;
5682
5683 fn next(&mut self) -> Option<Self::Item> {
5684 if let Some(item) = self.entry() {
5685 self.advance();
5686 Some(item)
5687 } else {
5688 None
5689 }
5690 }
5691}
5692
5693#[derive(Debug, Clone, Copy)]
5694pub enum PathTarget<'a> {
5695 Path(&'a RelPath),
5696 Successor(&'a RelPath),
5697}
5698
5699impl PathTarget<'_> {
5700 fn cmp_path(&self, other: &RelPath) -> Ordering {
5701 match self {
5702 PathTarget::Path(path) => path.cmp(&other),
5703 PathTarget::Successor(path) => {
5704 if other.starts_with(path) {
5705 Ordering::Greater
5706 } else {
5707 Ordering::Equal
5708 }
5709 }
5710 }
5711 }
5712}
5713
5714impl<'a, S: Summary> SeekTarget<'a, PathSummary<S>, PathProgress<'a>> for PathTarget<'_> {
5715 fn cmp(&self, cursor_location: &PathProgress<'a>, _: S::Context<'_>) -> Ordering {
5716 self.cmp_path(cursor_location.max_path)
5717 }
5718}
5719
5720impl<'a, S: Summary> SeekTarget<'a, PathSummary<S>, TraversalProgress<'a>> for PathTarget<'_> {
5721 fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: S::Context<'_>) -> Ordering {
5722 self.cmp_path(cursor_location.max_path)
5723 }
5724}
5725
5726#[derive(Debug)]
5727enum TraversalTarget<'a> {
5728 Path(PathTarget<'a>),
5729 Count {
5730 count: usize,
5731 include_files: bool,
5732 include_ignored: bool,
5733 include_dirs: bool,
5734 },
5735}
5736
5737impl<'a> TraversalTarget<'a> {
5738 fn path(path: &'a RelPath) -> Self {
5739 Self::Path(PathTarget::Path(path))
5740 }
5741
5742 fn successor(path: &'a RelPath) -> Self {
5743 Self::Path(PathTarget::Successor(path))
5744 }
5745
5746 fn cmp_progress(&self, progress: &TraversalProgress) -> Ordering {
5747 match self {
5748 TraversalTarget::Path(path) => path.cmp_path(progress.max_path),
5749 TraversalTarget::Count {
5750 count,
5751 include_files,
5752 include_dirs,
5753 include_ignored,
5754 } => Ord::cmp(
5755 count,
5756 &progress.count(*include_files, *include_dirs, *include_ignored),
5757 ),
5758 }
5759 }
5760}
5761
5762impl<'a> SeekTarget<'a, EntrySummary, TraversalProgress<'a>> for TraversalTarget<'_> {
5763 fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: ()) -> Ordering {
5764 self.cmp_progress(cursor_location)
5765 }
5766}
5767
5768impl<'a> SeekTarget<'a, PathSummary<sum_tree::NoSummary>, TraversalProgress<'a>>
5769 for TraversalTarget<'_>
5770{
5771 fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: ()) -> Ordering {
5772 self.cmp_progress(cursor_location)
5773 }
5774}
5775
5776pub struct ChildEntriesOptions {
5777 pub include_files: bool,
5778 pub include_dirs: bool,
5779 pub include_ignored: bool,
5780}
5781
5782pub struct ChildEntriesIter<'a> {
5783 parent_path: &'a RelPath,
5784 traversal: Traversal<'a>,
5785}
5786
5787impl<'a> Iterator for ChildEntriesIter<'a> {
5788 type Item = &'a Entry;
5789
5790 fn next(&mut self) -> Option<Self::Item> {
5791 if let Some(item) = self.traversal.entry()
5792 && item.path.starts_with(self.parent_path)
5793 {
5794 self.traversal.advance_to_sibling();
5795 return Some(item);
5796 }
5797 None
5798 }
5799}
5800
5801impl<'a> From<&'a Entry> for proto::Entry {
5802 fn from(entry: &'a Entry) -> Self {
5803 Self {
5804 id: entry.id.to_proto(),
5805 is_dir: entry.is_dir(),
5806 path: entry.path.as_ref().to_proto(),
5807 inode: entry.inode,
5808 mtime: entry.mtime.map(|time| time.into()),
5809 is_ignored: entry.is_ignored,
5810 is_hidden: entry.is_hidden,
5811 is_external: entry.is_external,
5812 is_fifo: entry.is_fifo,
5813 size: Some(entry.size),
5814 canonical_path: entry
5815 .canonical_path
5816 .as_ref()
5817 .map(|path| path.to_string_lossy().into_owned()),
5818 }
5819 }
5820}
5821
5822impl TryFrom<(&CharBag, &PathMatcher, proto::Entry)> for Entry {
5823 type Error = anyhow::Error;
5824
5825 fn try_from(
5826 (root_char_bag, always_included, entry): (&CharBag, &PathMatcher, proto::Entry),
5827 ) -> Result<Self> {
5828 let kind = if entry.is_dir {
5829 EntryKind::Dir
5830 } else {
5831 EntryKind::File
5832 };
5833
5834 let path =
5835 RelPath::from_proto(&entry.path).context("invalid relative path in proto message")?;
5836 let char_bag = char_bag_for_path(*root_char_bag, &path);
5837 let is_always_included = always_included.is_match(&path);
5838 Ok(Entry {
5839 id: ProjectEntryId::from_proto(entry.id),
5840 kind,
5841 path,
5842 inode: entry.inode,
5843 mtime: entry.mtime.map(|time| time.into()),
5844 size: entry.size.unwrap_or(0),
5845 canonical_path: entry
5846 .canonical_path
5847 .map(|path_string| Arc::from(PathBuf::from(path_string))),
5848 is_ignored: entry.is_ignored,
5849 is_hidden: entry.is_hidden,
5850 is_always_included,
5851 is_external: entry.is_external,
5852 is_private: false,
5853 char_bag,
5854 is_fifo: entry.is_fifo,
5855 })
5856 }
5857}
5858
5859#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
5860pub struct ProjectEntryId(usize);
5861
5862impl ProjectEntryId {
5863 pub const MAX: Self = Self(usize::MAX);
5864 pub const MIN: Self = Self(usize::MIN);
5865
5866 pub fn new(counter: &AtomicUsize) -> Self {
5867 Self(counter.fetch_add(1, SeqCst))
5868 }
5869
5870 pub fn from_proto(id: u64) -> Self {
5871 Self(id as usize)
5872 }
5873
5874 pub fn to_proto(self) -> u64 {
5875 self.0 as u64
5876 }
5877
5878 pub fn from_usize(id: usize) -> Self {
5879 ProjectEntryId(id)
5880 }
5881
5882 pub fn to_usize(self) -> usize {
5883 self.0
5884 }
5885}
5886
5887#[cfg(feature = "test-support")]
5888impl CreatedEntry {
5889 pub fn into_included(self) -> Option<Entry> {
5890 match self {
5891 CreatedEntry::Included(entry) => Some(entry),
5892 CreatedEntry::Excluded { .. } => None,
5893 }
5894 }
5895}
5896
5897fn parse_gitfile(content: &str) -> anyhow::Result<&Path> {
5898 let path = content
5899 .strip_prefix("gitdir:")
5900 .with_context(|| format!("parsing gitfile content {content:?}"))?;
5901 Ok(Path::new(path.trim()))
5902}
5903
5904async fn discover_git_paths(dot_git_abs_path: &Arc<Path>, fs: &dyn Fs) -> (Arc<Path>, Arc<Path>) {
5905 let mut repository_dir_abs_path = dot_git_abs_path.clone();
5906 let mut common_dir_abs_path = dot_git_abs_path.clone();
5907
5908 if let Some(path) = fs
5909 .load(dot_git_abs_path)
5910 .await
5911 .ok()
5912 .as_ref()
5913 .and_then(|contents| parse_gitfile(contents).log_err())
5914 {
5915 let path = dot_git_abs_path
5916 .parent()
5917 .unwrap_or(Path::new(""))
5918 .join(path);
5919 if let Some(path) = fs.canonicalize(&path).await.log_err() {
5920 repository_dir_abs_path = Path::new(&path).into();
5921 common_dir_abs_path = repository_dir_abs_path.clone();
5922
5923 if let Some(commondir_contents) = fs.load(&path.join("commondir")).await.ok()
5924 && let Some(commondir_path) = fs
5925 .canonicalize(&path.join(commondir_contents.trim()))
5926 .await
5927 .log_err()
5928 {
5929 common_dir_abs_path = commondir_path.as_path().into();
5930 }
5931 }
5932 };
5933 (repository_dir_abs_path, common_dir_abs_path)
5934}
5935
5936struct NullWatcher;
5937
5938impl fs::Watcher for NullWatcher {
5939 fn add(&self, _path: &Path) -> Result<()> {
5940 Ok(())
5941 }
5942
5943 fn remove(&self, _path: &Path) -> Result<()> {
5944 Ok(())
5945 }
5946}
5947
5948const FILE_ANALYSIS_BYTES: usize = 1024;
5949
5950async fn decode_file_text(
5951 fs: &dyn Fs,
5952 abs_path: &Path,
5953) -> Result<(String, &'static Encoding, bool)> {
5954 let mut file = fs
5955 .open_sync(&abs_path)
5956 .await
5957 .with_context(|| format!("opening file {abs_path:?}"))?;
5958
5959 // First, read the beginning of the file to determine its kind and encoding.
5960 // We do not want to load an entire large blob into memory only to discard it.
5961 let mut file_first_bytes = Vec::with_capacity(FILE_ANALYSIS_BYTES);
5962 let mut buf = [0u8; FILE_ANALYSIS_BYTES];
5963 let mut reached_eof = false;
5964 loop {
5965 if file_first_bytes.len() >= FILE_ANALYSIS_BYTES {
5966 break;
5967 }
5968 let n = file
5969 .read(&mut buf)
5970 .with_context(|| format!("reading bytes of the file {abs_path:?}"))?;
5971 if n == 0 {
5972 reached_eof = true;
5973 break;
5974 }
5975 file_first_bytes.extend_from_slice(&buf[..n]);
5976 }
5977 let (bom_encoding, byte_content) = decode_byte_header(&file_first_bytes);
5978 anyhow::ensure!(
5979 byte_content != ByteContent::Binary,
5980 "Binary files are not supported"
5981 );
5982
5983 // If the file is eligible for opening, read the rest of the file.
5984 let mut content = file_first_bytes;
5985 if !reached_eof {
5986 let mut buf = [0u8; 8 * 1024];
5987 loop {
5988 let n = file
5989 .read(&mut buf)
5990 .with_context(|| format!("reading remaining bytes of the file {abs_path:?}"))?;
5991 if n == 0 {
5992 break;
5993 }
5994 content.extend_from_slice(&buf[..n]);
5995 }
5996 }
5997 decode_byte_full(content, bom_encoding, byte_content)
5998}
5999
6000fn decode_byte_header(prefix: &[u8]) -> (Option<&'static Encoding>, ByteContent) {
6001 if let Some((encoding, _bom_len)) = Encoding::for_bom(prefix) {
6002 return (Some(encoding), ByteContent::Unknown);
6003 }
6004 (None, analyze_byte_content(prefix))
6005}
6006
6007fn decode_byte_full(
6008 bytes: Vec<u8>,
6009 bom_encoding: Option<&'static Encoding>,
6010 byte_content: ByteContent,
6011) -> Result<(String, &'static Encoding, bool)> {
6012 if let Some(encoding) = bom_encoding {
6013 let (cow, _) = encoding.decode_with_bom_removal(&bytes);
6014 return Ok((cow.into_owned(), encoding, true));
6015 }
6016
6017 match byte_content {
6018 ByteContent::Utf16Le => {
6019 let encoding = encoding_rs::UTF_16LE;
6020 let (cow, _, _) = encoding.decode(&bytes);
6021 return Ok((cow.into_owned(), encoding, false));
6022 }
6023 ByteContent::Utf16Be => {
6024 let encoding = encoding_rs::UTF_16BE;
6025 let (cow, _, _) = encoding.decode(&bytes);
6026 return Ok((cow.into_owned(), encoding, false));
6027 }
6028 ByteContent::Binary => {
6029 anyhow::bail!("Binary files are not supported");
6030 }
6031 ByteContent::Unknown => {}
6032 }
6033
6034 fn detect_encoding(bytes: Vec<u8>) -> (String, &'static Encoding) {
6035 let mut detector = EncodingDetector::new();
6036 detector.feed(&bytes, true);
6037
6038 let encoding = detector.guess(None, true); // Use None for TLD hint to ensure neutral detection logic.
6039
6040 let (cow, _, _) = encoding.decode(&bytes);
6041 (cow.into_owned(), encoding)
6042 }
6043
6044 match String::from_utf8(bytes) {
6045 Ok(text) => {
6046 // ISO-2022-JP (and other ISO-2022 variants) consists entirely of 7-bit ASCII bytes,
6047 // so it is valid UTF-8. However, it contains escape sequences starting with '\x1b'.
6048 // If we find an escape character, we double-check the encoding to prevent
6049 // displaying raw escape sequences instead of the correct characters.
6050 if text.contains('\x1b') {
6051 let (s, enc) = detect_encoding(text.into_bytes());
6052 Ok((s, enc, false))
6053 } else {
6054 Ok((text, encoding_rs::UTF_8, false))
6055 }
6056 }
6057 Err(e) => {
6058 let (s, enc) = detect_encoding(e.into_bytes());
6059 Ok((s, enc, false))
6060 }
6061 }
6062}
6063
6064#[derive(PartialEq)]
6065enum ByteContent {
6066 Utf16Le,
6067 Utf16Be,
6068 Binary,
6069 Unknown,
6070}
6071
6072// Heuristic check using null byte distribution plus a generic text-likeness
6073// heuristic. This prefers UTF-16 when many bytes are NUL and otherwise
6074// distinguishes between text-like and binary-like content.
6075fn analyze_byte_content(bytes: &[u8]) -> ByteContent {
6076 if bytes.len() < 2 {
6077 return ByteContent::Unknown;
6078 }
6079
6080 if is_known_binary_header(bytes) {
6081 return ByteContent::Binary;
6082 }
6083
6084 let limit = bytes.len().min(FILE_ANALYSIS_BYTES);
6085 let mut even_null_count = 0usize;
6086 let mut odd_null_count = 0usize;
6087 let mut non_text_like_count = 0usize;
6088
6089 for (i, &byte) in bytes[..limit].iter().enumerate() {
6090 if byte == 0 {
6091 if i % 2 == 0 {
6092 even_null_count += 1;
6093 } else {
6094 odd_null_count += 1;
6095 }
6096 non_text_like_count += 1;
6097 continue;
6098 }
6099
6100 let is_text_like = match byte {
6101 b'\t' | b'\n' | b'\r' | 0x0C => true,
6102 0x20..=0x7E => true,
6103 // Treat bytes that are likely part of UTF-8 or single-byte encodings as text-like.
6104 0x80..=0xBF | 0xC2..=0xF4 => true,
6105 _ => false,
6106 };
6107
6108 if !is_text_like {
6109 non_text_like_count += 1;
6110 }
6111 }
6112
6113 let total_null_count = even_null_count + odd_null_count;
6114
6115 // If there are no NUL bytes at all, this is overwhelmingly likely to be text.
6116 if total_null_count == 0 {
6117 return ByteContent::Unknown;
6118 }
6119
6120 if total_null_count >= limit / 16 {
6121 if even_null_count > odd_null_count * 4 {
6122 return ByteContent::Utf16Be;
6123 }
6124 if odd_null_count > even_null_count * 4 {
6125 return ByteContent::Utf16Le;
6126 }
6127 return ByteContent::Binary;
6128 }
6129
6130 if non_text_like_count * 100 < limit * 8 {
6131 ByteContent::Unknown
6132 } else {
6133 ByteContent::Binary
6134 }
6135}
6136
6137fn is_known_binary_header(bytes: &[u8]) -> bool {
6138 bytes.starts_with(b"%PDF-") // PDF
6139 || bytes.starts_with(b"PK\x03\x04") // ZIP local header
6140 || bytes.starts_with(b"PK\x05\x06") // ZIP end of central directory
6141 || bytes.starts_with(b"PK\x07\x08") // ZIP spanning/splitting
6142 || bytes.starts_with(b"\x89PNG\r\n\x1a\n") // PNG
6143 || bytes.starts_with(b"\xFF\xD8\xFF") // JPEG
6144 || bytes.starts_with(b"GIF87a") // GIF87a
6145 || bytes.starts_with(b"GIF89a") // GIF89a
6146 || bytes.starts_with(b"IWAD") // Doom IWAD archive
6147 || bytes.starts_with(b"PWAD") // Doom PWAD archive
6148}