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