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