1mod ignore;
2mod worktree_settings;
3#[cfg(test)]
4mod worktree_tests;
5
6use ::ignore::gitignore::{Gitignore, GitignoreBuilder};
7use anyhow::{Context as _, Result, anyhow};
8use chardetng::EncodingDetector;
9use clock::ReplicaId;
10use collections::{HashMap, HashSet, VecDeque};
11use encoding_rs::Encoding;
12use fs::{Fs, MTime, PathEvent, RemoveOptions, Watcher, copy_recursive, read_dir_items};
13use futures::{
14 FutureExt as _, Stream, StreamExt,
15 channel::{
16 mpsc::{self, UnboundedSender},
17 oneshot,
18 },
19 select_biased, stream,
20 task::Poll,
21};
22use fuzzy::CharBag;
23use git::{
24 COMMIT_MESSAGE, DOT_GIT, FSMONITOR_DAEMON, GITIGNORE, INDEX_LOCK, LFS_DIR, REPO_EXCLUDE,
25 status::GitSummary,
26};
27use gpui::{
28 App, AppContext as _, AsyncApp, BackgroundExecutor, Context, Entity, EventEmitter, Priority,
29 Task,
30};
31use ignore::IgnoreStack;
32use language::DiskState;
33
34use parking_lot::Mutex;
35use paths::{local_settings_folder_name, local_vscode_folder_name};
36use postage::{
37 barrier,
38 prelude::{Sink as _, Stream as _},
39 watch,
40};
41use rpc::{
42 AnyProtoClient,
43 proto::{self, split_worktree_update},
44};
45pub use settings::WorktreeId;
46use settings::{Settings, SettingsLocation, SettingsStore};
47use smallvec::{SmallVec, smallvec};
48use smol::channel::{self, Sender};
49use std::{
50 any::Any,
51 borrow::Borrow as _,
52 cmp::Ordering,
53 collections::hash_map,
54 convert::TryFrom,
55 ffi::OsStr,
56 fmt,
57 future::Future,
58 mem::{self},
59 ops::{Deref, DerefMut, Range},
60 path::{Path, PathBuf},
61 pin::Pin,
62 sync::{
63 Arc,
64 atomic::{AtomicUsize, Ordering::SeqCst},
65 },
66 time::{Duration, Instant},
67};
68use sum_tree::{Bias, Dimensions, Edit, KeyedItem, SeekTarget, SumTree, Summary, TreeMap, TreeSet};
69use text::{LineEnding, Rope};
70use util::{
71 ResultExt, debug_panic, maybe,
72 paths::{PathMatcher, PathStyle, SanitizedPath, home_dir},
73 rel_path::RelPath,
74};
75pub use worktree_settings::WorktreeSettings;
76
77use crate::ignore::IgnoreKind;
78
79pub const FS_WATCH_LATENCY: Duration = Duration::from_millis(100);
80
81/// A set of local or remote files that are being opened as part of a project.
82/// Responsible for tracking related FS (for local)/collab (for remote) events and corresponding updates.
83/// Stores git repositories data and the diagnostics for the file(s).
84///
85/// Has an absolute path, and may be set to be visible in Zed UI or not.
86/// May correspond to a directory or a single file.
87/// Possible examples:
88/// * a drag and dropped file — may be added as an invisible, "ephemeral" entry to the current worktree
89/// * a directory opened in Zed — may be added as a visible entry to the current worktree
90///
91/// Uses [`Entry`] to track the state of each file/directory, can look up absolute paths for entries.
92pub enum Worktree {
93 Local(LocalWorktree),
94 Remote(RemoteWorktree),
95}
96
97/// An entry, created in the worktree.
98#[derive(Debug)]
99pub enum CreatedEntry {
100 /// Got created and indexed by the worktree, receiving a corresponding entry.
101 Included(Entry),
102 /// Got created, but not indexed due to falling under exclusion filters.
103 Excluded { abs_path: PathBuf },
104}
105
106#[derive(Debug)]
107pub struct LoadedFile {
108 pub file: Arc<File>,
109 pub text: String,
110 pub encoding: &'static Encoding,
111 pub has_bom: bool,
112}
113
114pub struct LoadedBinaryFile {
115 pub file: Arc<File>,
116 pub content: Vec<u8>,
117}
118
119impl fmt::Debug for LoadedBinaryFile {
120 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
121 f.debug_struct("LoadedBinaryFile")
122 .field("file", &self.file)
123 .field("content_bytes", &self.content.len())
124 .finish()
125 }
126}
127
128pub struct LocalWorktree {
129 snapshot: LocalSnapshot,
130 scan_requests_tx: channel::Sender<ScanRequest>,
131 path_prefixes_to_scan_tx: channel::Sender<PathPrefixScanRequest>,
132 is_scanning: (watch::Sender<bool>, watch::Receiver<bool>),
133 _background_scanner_tasks: Vec<Task<()>>,
134 update_observer: Option<UpdateObservationState>,
135 fs: Arc<dyn Fs>,
136 fs_case_sensitive: bool,
137 visible: bool,
138 next_entry_id: Arc<AtomicUsize>,
139 settings: WorktreeSettings,
140 share_private_files: bool,
141 scanning_enabled: bool,
142}
143
144pub struct PathPrefixScanRequest {
145 path: Arc<RelPath>,
146 done: SmallVec<[barrier::Sender; 1]>,
147}
148
149struct ScanRequest {
150 relative_paths: Vec<Arc<RelPath>>,
151 done: SmallVec<[barrier::Sender; 1]>,
152}
153
154pub struct RemoteWorktree {
155 snapshot: Snapshot,
156 background_snapshot: Arc<Mutex<(Snapshot, Vec<proto::UpdateWorktree>)>>,
157 project_id: u64,
158 client: AnyProtoClient,
159 file_scan_inclusions: PathMatcher,
160 updates_tx: Option<UnboundedSender<proto::UpdateWorktree>>,
161 update_observer: Option<mpsc::UnboundedSender<proto::UpdateWorktree>>,
162 snapshot_subscriptions: VecDeque<(usize, oneshot::Sender<()>)>,
163 replica_id: ReplicaId,
164 visible: bool,
165 disconnected: bool,
166}
167
168#[derive(Clone)]
169pub struct Snapshot {
170 id: WorktreeId,
171 /// The absolute path of the worktree root.
172 abs_path: Arc<SanitizedPath>,
173 path_style: PathStyle,
174 root_name: Arc<RelPath>,
175 root_char_bag: CharBag,
176 entries_by_path: SumTree<Entry>,
177 entries_by_id: SumTree<PathEntry>,
178 always_included_entries: Vec<Arc<RelPath>>,
179
180 /// A number that increases every time the worktree begins scanning
181 /// a set of paths from the filesystem. This scanning could be caused
182 /// by some operation performed on the worktree, such as reading or
183 /// writing a file, or by an event reported by the filesystem.
184 scan_id: usize,
185
186 /// The latest scan id that has completed, and whose preceding scans
187 /// have all completed. The current `scan_id` could be more than one
188 /// greater than the `completed_scan_id` if operations are performed
189 /// on the worktree while it is processing a file-system event.
190 completed_scan_id: usize,
191}
192
193/// This path corresponds to the 'content path' of a repository in relation
194/// to Zed's project root.
195/// In the majority of the cases, this is the folder that contains the .git folder.
196/// But if a sub-folder of a git repository is opened, this corresponds to the
197/// project root and the .git folder is located in a parent directory.
198#[derive(Clone, Debug, Ord, PartialOrd, Eq, PartialEq, Hash)]
199pub enum WorkDirectory {
200 InProject {
201 relative_path: Arc<RelPath>,
202 },
203 AboveProject {
204 absolute_path: Arc<Path>,
205 location_in_repo: Arc<Path>,
206 },
207}
208
209impl WorkDirectory {
210 fn path_key(&self) -> PathKey {
211 match self {
212 WorkDirectory::InProject { relative_path } => PathKey(relative_path.clone()),
213 WorkDirectory::AboveProject { .. } => PathKey(RelPath::empty().into()),
214 }
215 }
216
217 /// Returns true if the given path is a child of the work directory.
218 ///
219 /// Note that the path may not be a member of this repository, if there
220 /// is a repository in a directory between these two paths
221 /// external .git folder in a parent folder of the project root.
222 #[track_caller]
223 pub fn directory_contains(&self, path: &RelPath) -> bool {
224 match self {
225 WorkDirectory::InProject { relative_path } => path.starts_with(relative_path),
226 WorkDirectory::AboveProject { .. } => true,
227 }
228 }
229}
230
231impl Default for WorkDirectory {
232 fn default() -> Self {
233 Self::InProject {
234 relative_path: Arc::from(RelPath::empty()),
235 }
236 }
237}
238
239#[derive(Clone)]
240pub struct LocalSnapshot {
241 snapshot: Snapshot,
242 global_gitignore: Option<Arc<Gitignore>>,
243 /// Exclude files for all git repositories in the worktree, indexed by their absolute path.
244 /// The boolean indicates whether the gitignore needs to be updated.
245 repo_exclude_by_work_dir_abs_path: HashMap<Arc<Path>, (Arc<Gitignore>, bool)>,
246 /// All of the gitignore files in the worktree, indexed by their absolute path.
247 /// The boolean indicates whether the gitignore needs to be updated.
248 ignores_by_parent_abs_path: HashMap<Arc<Path>, (Arc<Gitignore>, bool)>,
249 /// All of the git repositories in the worktree, indexed by the project entry
250 /// id of their parent directory.
251 git_repositories: TreeMap<ProjectEntryId, LocalRepositoryEntry>,
252 /// The file handle of the worktree root
253 /// (so we can find it after it's been moved)
254 root_file_handle: Option<Arc<dyn fs::FileHandle>>,
255 executor: BackgroundExecutor,
256}
257
258struct BackgroundScannerState {
259 snapshot: LocalSnapshot,
260 scanned_dirs: HashSet<ProjectEntryId>,
261 path_prefixes_to_scan: HashSet<Arc<RelPath>>,
262 paths_to_scan: HashSet<Arc<RelPath>>,
263 /// The ids of all of the entries that were removed from the snapshot
264 /// as part of the current update. These entry ids may be re-used
265 /// if the same inode is discovered at a new path, or if the given
266 /// path is re-created after being deleted.
267 removed_entries: HashMap<u64, Entry>,
268 changed_paths: Vec<Arc<RelPath>>,
269 prev_snapshot: Snapshot,
270 scanning_enabled: bool,
271}
272
273#[derive(Debug, Clone)]
274struct LocalRepositoryEntry {
275 work_directory_id: ProjectEntryId,
276 work_directory: WorkDirectory,
277 work_directory_abs_path: Arc<Path>,
278 git_dir_scan_id: usize,
279 /// Absolute path to the original .git entry that caused us to create this repository.
280 ///
281 /// This is normally a directory, but may be a "gitfile" that points to a directory elsewhere
282 /// (whose path we then store in `repository_dir_abs_path`).
283 dot_git_abs_path: Arc<Path>,
284 /// Absolute path to the "commondir" for this repository.
285 ///
286 /// This is always a directory. For a normal repository, this is the same as dot_git_abs_path,
287 /// but in the case of a submodule or a worktree it is the path to the "parent" .git directory
288 /// from which the submodule/worktree was derived.
289 common_dir_abs_path: Arc<Path>,
290 /// Absolute path to the directory holding the repository's state.
291 ///
292 /// For a normal repository, this is a directory and coincides with `dot_git_abs_path` and
293 /// `common_dir_abs_path`. For a submodule or worktree, this is some subdirectory of the
294 /// commondir like `/project/.git/modules/foo`.
295 repository_dir_abs_path: Arc<Path>,
296}
297
298impl sum_tree::Item for LocalRepositoryEntry {
299 type Summary = PathSummary<sum_tree::NoSummary>;
300
301 fn summary(&self, _: <Self::Summary as Summary>::Context<'_>) -> Self::Summary {
302 PathSummary {
303 max_path: self.work_directory.path_key().0,
304 item_summary: sum_tree::NoSummary,
305 }
306 }
307}
308
309impl KeyedItem for LocalRepositoryEntry {
310 type Key = PathKey;
311
312 fn key(&self) -> Self::Key {
313 self.work_directory.path_key()
314 }
315}
316
317impl Deref for LocalRepositoryEntry {
318 type Target = WorkDirectory;
319
320 fn deref(&self) -> &Self::Target {
321 &self.work_directory
322 }
323}
324
325impl Deref for LocalSnapshot {
326 type Target = Snapshot;
327
328 fn deref(&self) -> &Self::Target {
329 &self.snapshot
330 }
331}
332
333impl DerefMut for LocalSnapshot {
334 fn deref_mut(&mut self) -> &mut Self::Target {
335 &mut self.snapshot
336 }
337}
338
339enum ScanState {
340 Started,
341 Updated {
342 snapshot: LocalSnapshot,
343 changes: UpdatedEntriesSet,
344 barrier: SmallVec<[barrier::Sender; 1]>,
345 scanning: bool,
346 },
347 RootUpdated {
348 new_path: Arc<SanitizedPath>,
349 },
350}
351
352struct UpdateObservationState {
353 snapshots_tx: mpsc::UnboundedSender<(LocalSnapshot, UpdatedEntriesSet)>,
354 resume_updates: watch::Sender<()>,
355 _maintain_remote_snapshot: Task<Option<()>>,
356}
357
358#[derive(Debug, Clone)]
359pub enum Event {
360 UpdatedEntries(UpdatedEntriesSet),
361 UpdatedGitRepositories(UpdatedGitRepositoriesSet),
362 DeletedEntry(ProjectEntryId),
363}
364
365impl EventEmitter<Event> for Worktree {}
366
367impl Worktree {
368 pub async fn local(
369 path: impl Into<Arc<Path>>,
370 visible: bool,
371 fs: Arc<dyn Fs>,
372 next_entry_id: Arc<AtomicUsize>,
373 scanning_enabled: bool,
374 cx: &mut AsyncApp,
375 ) -> Result<Entity<Self>> {
376 let abs_path = path.into();
377 let metadata = fs
378 .metadata(&abs_path)
379 .await
380 .context("failed to stat worktree path")?;
381
382 let fs_case_sensitive = fs.is_case_sensitive().await.unwrap_or_else(|e| {
383 log::error!(
384 "Failed to determine whether filesystem is case sensitive (falling back to true) due to error: {e:#}"
385 );
386 true
387 });
388
389 let root_file_handle = if metadata.as_ref().is_some() {
390 fs.open_handle(&abs_path)
391 .await
392 .with_context(|| {
393 format!(
394 "failed to open local worktree root at {}",
395 abs_path.display()
396 )
397 })
398 .log_err()
399 } else {
400 None
401 };
402
403 Ok(cx.new(move |cx: &mut Context<Worktree>| {
404 let mut snapshot = LocalSnapshot {
405 ignores_by_parent_abs_path: Default::default(),
406 global_gitignore: Default::default(),
407 repo_exclude_by_work_dir_abs_path: Default::default(),
408 git_repositories: Default::default(),
409 snapshot: Snapshot::new(
410 cx.entity_id().as_u64(),
411 abs_path
412 .file_name()
413 .and_then(|f| f.to_str())
414 .map_or(RelPath::empty().into(), |f| {
415 RelPath::unix(f).unwrap().into()
416 }),
417 abs_path.clone(),
418 PathStyle::local(),
419 ),
420 root_file_handle,
421 executor: cx.background_executor().clone(),
422 };
423
424 let worktree_id = snapshot.id();
425 let settings_location = Some(SettingsLocation {
426 worktree_id,
427 path: RelPath::empty(),
428 });
429
430 let settings = WorktreeSettings::get(settings_location, cx).clone();
431 cx.observe_global::<SettingsStore>(move |this, cx| {
432 if let Self::Local(this) = this {
433 let settings = WorktreeSettings::get(settings_location, cx).clone();
434 if this.settings != settings {
435 this.settings = settings;
436 this.restart_background_scanners(cx);
437 }
438 }
439 })
440 .detach();
441
442 let share_private_files = false;
443 if let Some(metadata) = metadata {
444 let mut entry = Entry::new(
445 RelPath::empty().into(),
446 &metadata,
447 ProjectEntryId::new(&next_entry_id),
448 snapshot.root_char_bag,
449 None,
450 );
451 if metadata.is_dir {
452 if !scanning_enabled {
453 entry.kind = EntryKind::UnloadedDir;
454 }
455 } else {
456 if let Some(file_name) = abs_path.file_name()
457 && let Some(file_name) = file_name.to_str()
458 && let Ok(path) = RelPath::unix(file_name)
459 {
460 entry.is_private = !share_private_files && settings.is_path_private(path);
461 entry.is_hidden = settings.is_path_hidden(path);
462 }
463 }
464 snapshot.insert_entry(entry, fs.as_ref());
465 }
466
467 let (scan_requests_tx, scan_requests_rx) = channel::unbounded();
468 let (path_prefixes_to_scan_tx, path_prefixes_to_scan_rx) = channel::unbounded();
469 let mut worktree = LocalWorktree {
470 share_private_files,
471 next_entry_id,
472 snapshot,
473 is_scanning: watch::channel_with(true),
474 update_observer: None,
475 scan_requests_tx,
476 path_prefixes_to_scan_tx,
477 _background_scanner_tasks: Vec::new(),
478 fs,
479 fs_case_sensitive,
480 visible,
481 settings,
482 scanning_enabled,
483 };
484 worktree.start_background_scanner(scan_requests_rx, path_prefixes_to_scan_rx, cx);
485 Worktree::Local(worktree)
486 }))
487 }
488
489 pub fn remote(
490 project_id: u64,
491 replica_id: ReplicaId,
492 worktree: proto::WorktreeMetadata,
493 client: AnyProtoClient,
494 path_style: PathStyle,
495 cx: &mut App,
496 ) -> Entity<Self> {
497 cx.new(|cx: &mut Context<Self>| {
498 let snapshot = Snapshot::new(
499 worktree.id,
500 RelPath::from_proto(&worktree.root_name)
501 .unwrap_or_else(|_| RelPath::empty().into()),
502 Path::new(&worktree.abs_path).into(),
503 path_style,
504 );
505
506 let background_snapshot = Arc::new(Mutex::new((
507 snapshot.clone(),
508 Vec::<proto::UpdateWorktree>::new(),
509 )));
510 let (background_updates_tx, mut background_updates_rx) =
511 mpsc::unbounded::<proto::UpdateWorktree>();
512 let (mut snapshot_updated_tx, mut snapshot_updated_rx) = watch::channel();
513
514 let worktree_id = snapshot.id();
515 let settings_location = Some(SettingsLocation {
516 worktree_id,
517 path: RelPath::empty(),
518 });
519
520 let settings = WorktreeSettings::get(settings_location, cx).clone();
521 let worktree = RemoteWorktree {
522 client,
523 project_id,
524 replica_id,
525 snapshot,
526 file_scan_inclusions: settings.parent_dir_scan_inclusions.clone(),
527 background_snapshot: background_snapshot.clone(),
528 updates_tx: Some(background_updates_tx),
529 update_observer: None,
530 snapshot_subscriptions: Default::default(),
531 visible: worktree.visible,
532 disconnected: false,
533 };
534
535 // Apply updates to a separate snapshot in a background task, then
536 // send them to a foreground task which updates the model.
537 cx.background_spawn(async move {
538 while let Some(update) = background_updates_rx.next().await {
539 {
540 let mut lock = background_snapshot.lock();
541 lock.0.apply_remote_update(
542 update.clone(),
543 &settings.parent_dir_scan_inclusions,
544 );
545 lock.1.push(update);
546 }
547 snapshot_updated_tx.send(()).await.ok();
548 }
549 })
550 .detach();
551
552 // On the foreground task, update to the latest snapshot and notify
553 // any update observer of all updates that led to that snapshot.
554 cx.spawn(async move |this, cx| {
555 while (snapshot_updated_rx.recv().await).is_some() {
556 this.update(cx, |this, cx| {
557 let mut entries_changed = false;
558 let this = this.as_remote_mut().unwrap();
559 {
560 let mut lock = this.background_snapshot.lock();
561 this.snapshot = lock.0.clone();
562 for update in lock.1.drain(..) {
563 entries_changed |= !update.updated_entries.is_empty()
564 || !update.removed_entries.is_empty();
565 if let Some(tx) = &this.update_observer {
566 tx.unbounded_send(update).ok();
567 }
568 }
569 };
570
571 if entries_changed {
572 cx.emit(Event::UpdatedEntries(Arc::default()));
573 }
574 cx.notify();
575 while let Some((scan_id, _)) = this.snapshot_subscriptions.front() {
576 if this.observed_snapshot(*scan_id) {
577 let (_, tx) = this.snapshot_subscriptions.pop_front().unwrap();
578 let _ = tx.send(());
579 } else {
580 break;
581 }
582 }
583 })?;
584 }
585 anyhow::Ok(())
586 })
587 .detach();
588
589 Worktree::Remote(worktree)
590 })
591 }
592
593 pub fn as_local(&self) -> Option<&LocalWorktree> {
594 if let Worktree::Local(worktree) = self {
595 Some(worktree)
596 } else {
597 None
598 }
599 }
600
601 pub fn as_remote(&self) -> Option<&RemoteWorktree> {
602 if let Worktree::Remote(worktree) = self {
603 Some(worktree)
604 } else {
605 None
606 }
607 }
608
609 pub fn as_local_mut(&mut self) -> Option<&mut LocalWorktree> {
610 if let Worktree::Local(worktree) = self {
611 Some(worktree)
612 } else {
613 None
614 }
615 }
616
617 pub fn as_remote_mut(&mut self) -> Option<&mut RemoteWorktree> {
618 if let Worktree::Remote(worktree) = self {
619 Some(worktree)
620 } else {
621 None
622 }
623 }
624
625 pub fn is_local(&self) -> bool {
626 matches!(self, Worktree::Local(_))
627 }
628
629 pub fn is_remote(&self) -> bool {
630 !self.is_local()
631 }
632
633 pub fn settings_location(&self, _: &Context<Self>) -> SettingsLocation<'static> {
634 SettingsLocation {
635 worktree_id: self.id(),
636 path: RelPath::empty(),
637 }
638 }
639
640 pub fn snapshot(&self) -> Snapshot {
641 match self {
642 Worktree::Local(worktree) => worktree.snapshot.snapshot.clone(),
643 Worktree::Remote(worktree) => worktree.snapshot.clone(),
644 }
645 }
646
647 pub fn scan_id(&self) -> usize {
648 match self {
649 Worktree::Local(worktree) => worktree.snapshot.scan_id,
650 Worktree::Remote(worktree) => worktree.snapshot.scan_id,
651 }
652 }
653
654 pub fn metadata_proto(&self) -> proto::WorktreeMetadata {
655 proto::WorktreeMetadata {
656 id: self.id().to_proto(),
657 root_name: self.root_name().to_proto(),
658 visible: self.is_visible(),
659 abs_path: self.abs_path().to_string_lossy().into_owned(),
660 }
661 }
662
663 pub fn completed_scan_id(&self) -> usize {
664 match self {
665 Worktree::Local(worktree) => worktree.snapshot.completed_scan_id,
666 Worktree::Remote(worktree) => worktree.snapshot.completed_scan_id,
667 }
668 }
669
670 pub fn is_visible(&self) -> bool {
671 match self {
672 Worktree::Local(worktree) => worktree.visible,
673 Worktree::Remote(worktree) => worktree.visible,
674 }
675 }
676
677 pub fn replica_id(&self) -> ReplicaId {
678 match self {
679 Worktree::Local(_) => ReplicaId::LOCAL,
680 Worktree::Remote(worktree) => worktree.replica_id,
681 }
682 }
683
684 pub fn abs_path(&self) -> Arc<Path> {
685 match self {
686 Worktree::Local(worktree) => SanitizedPath::cast_arc(worktree.abs_path.clone()),
687 Worktree::Remote(worktree) => SanitizedPath::cast_arc(worktree.abs_path.clone()),
688 }
689 }
690
691 pub fn root_file(&self, cx: &Context<Self>) -> Option<Arc<File>> {
692 let entry = self.root_entry()?;
693 Some(File::for_entry(entry.clone(), cx.entity()))
694 }
695
696 pub fn observe_updates<F, Fut>(&mut self, project_id: u64, cx: &Context<Worktree>, callback: F)
697 where
698 F: 'static + Send + Fn(proto::UpdateWorktree) -> Fut,
699 Fut: 'static + Send + Future<Output = bool>,
700 {
701 match self {
702 Worktree::Local(this) => this.observe_updates(project_id, cx, callback),
703 Worktree::Remote(this) => this.observe_updates(project_id, cx, callback),
704 }
705 }
706
707 pub fn stop_observing_updates(&mut self) {
708 match self {
709 Worktree::Local(this) => {
710 this.update_observer.take();
711 }
712 Worktree::Remote(this) => {
713 this.update_observer.take();
714 }
715 }
716 }
717
718 #[cfg(any(test, feature = "test-support"))]
719 pub fn has_update_observer(&self) -> bool {
720 match self {
721 Worktree::Local(this) => this.update_observer.is_some(),
722 Worktree::Remote(this) => this.update_observer.is_some(),
723 }
724 }
725
726 pub fn load_file(&self, path: &RelPath, cx: &Context<Worktree>) -> Task<Result<LoadedFile>> {
727 match self {
728 Worktree::Local(this) => this.load_file(path, cx),
729 Worktree::Remote(_) => {
730 Task::ready(Err(anyhow!("remote worktrees can't yet load files")))
731 }
732 }
733 }
734
735 pub fn load_binary_file(
736 &self,
737 path: &RelPath,
738 cx: &Context<Worktree>,
739 ) -> Task<Result<LoadedBinaryFile>> {
740 match self {
741 Worktree::Local(this) => this.load_binary_file(path, cx),
742 Worktree::Remote(_) => {
743 Task::ready(Err(anyhow!("remote worktrees can't yet load binary files")))
744 }
745 }
746 }
747
748 pub fn write_file(
749 &self,
750 path: Arc<RelPath>,
751 text: Rope,
752 line_ending: LineEnding,
753 encoding: &'static Encoding,
754 has_bom: bool,
755 cx: &Context<Worktree>,
756 ) -> Task<Result<Arc<File>>> {
757 match self {
758 Worktree::Local(this) => {
759 this.write_file(path, text, line_ending, encoding, has_bom, cx)
760 }
761 Worktree::Remote(_) => {
762 Task::ready(Err(anyhow!("remote worktree can't yet write files")))
763 }
764 }
765 }
766
767 pub fn create_entry(
768 &mut self,
769 path: Arc<RelPath>,
770 is_directory: bool,
771 content: Option<Vec<u8>>,
772 cx: &Context<Worktree>,
773 ) -> Task<Result<CreatedEntry>> {
774 let worktree_id = self.id();
775 match self {
776 Worktree::Local(this) => this.create_entry(path, is_directory, content, cx),
777 Worktree::Remote(this) => {
778 let project_id = this.project_id;
779 let request = this.client.request(proto::CreateProjectEntry {
780 worktree_id: worktree_id.to_proto(),
781 project_id,
782 path: path.as_ref().to_proto(),
783 content,
784 is_directory,
785 });
786 cx.spawn(async move |this, cx| {
787 let response = request.await?;
788 match response.entry {
789 Some(entry) => this
790 .update(cx, |worktree, cx| {
791 worktree.as_remote_mut().unwrap().insert_entry(
792 entry,
793 response.worktree_scan_id as usize,
794 cx,
795 )
796 })?
797 .await
798 .map(CreatedEntry::Included),
799 None => {
800 let abs_path =
801 this.read_with(cx, |worktree, _| worktree.absolutize(&path))?;
802 Ok(CreatedEntry::Excluded { abs_path })
803 }
804 }
805 })
806 }
807 }
808 }
809
810 pub fn delete_entry(
811 &mut self,
812 entry_id: ProjectEntryId,
813 trash: bool,
814 cx: &mut Context<Worktree>,
815 ) -> Option<Task<Result<()>>> {
816 let task = match self {
817 Worktree::Local(this) => this.delete_entry(entry_id, trash, cx),
818 Worktree::Remote(this) => this.delete_entry(entry_id, trash, cx),
819 }?;
820
821 let entry = match &*self {
822 Worktree::Local(this) => this.entry_for_id(entry_id),
823 Worktree::Remote(this) => this.entry_for_id(entry_id),
824 }?;
825
826 let mut ids = vec![entry_id];
827 let path = &*entry.path;
828
829 self.get_children_ids_recursive(path, &mut ids);
830
831 for id in ids {
832 cx.emit(Event::DeletedEntry(id));
833 }
834 Some(task)
835 }
836
837 fn get_children_ids_recursive(&self, path: &RelPath, ids: &mut Vec<ProjectEntryId>) {
838 let children_iter = self.child_entries(path);
839 for child in children_iter {
840 ids.push(child.id);
841 self.get_children_ids_recursive(&child.path, ids);
842 }
843 }
844
845 // pub fn rename_entry(
846 // &mut self,
847 // entry_id: ProjectEntryId,
848 // new_path: Arc<RelPath>,
849 // cx: &Context<Self>,
850 // ) -> Task<Result<CreatedEntry>> {
851 // match self {
852 // Worktree::Local(this) => this.rename_entry(entry_id, new_path, cx),
853 // Worktree::Remote(this) => this.rename_entry(entry_id, new_path, cx),
854 // }
855 // }
856
857 pub fn copy_external_entries(
858 &mut self,
859 target_directory: Arc<RelPath>,
860 paths: Vec<Arc<Path>>,
861 fs: Arc<dyn Fs>,
862 cx: &Context<Worktree>,
863 ) -> Task<Result<Vec<ProjectEntryId>>> {
864 match self {
865 Worktree::Local(this) => this.copy_external_entries(target_directory, paths, cx),
866 Worktree::Remote(this) => this.copy_external_entries(target_directory, paths, fs, cx),
867 }
868 }
869
870 pub fn expand_entry(
871 &mut self,
872 entry_id: ProjectEntryId,
873 cx: &Context<Worktree>,
874 ) -> Option<Task<Result<()>>> {
875 match self {
876 Worktree::Local(this) => this.expand_entry(entry_id, cx),
877 Worktree::Remote(this) => {
878 let response = this.client.request(proto::ExpandProjectEntry {
879 project_id: this.project_id,
880 entry_id: entry_id.to_proto(),
881 });
882 Some(cx.spawn(async move |this, cx| {
883 let response = response.await?;
884 this.update(cx, |this, _| {
885 this.as_remote_mut()
886 .unwrap()
887 .wait_for_snapshot(response.worktree_scan_id as usize)
888 })?
889 .await?;
890 Ok(())
891 }))
892 }
893 }
894 }
895
896 pub fn expand_all_for_entry(
897 &mut self,
898 entry_id: ProjectEntryId,
899 cx: &Context<Worktree>,
900 ) -> Option<Task<Result<()>>> {
901 match self {
902 Worktree::Local(this) => this.expand_all_for_entry(entry_id, cx),
903 Worktree::Remote(this) => {
904 let response = this.client.request(proto::ExpandAllForProjectEntry {
905 project_id: this.project_id,
906 entry_id: entry_id.to_proto(),
907 });
908 Some(cx.spawn(async move |this, cx| {
909 let response = response.await?;
910 this.update(cx, |this, _| {
911 this.as_remote_mut()
912 .unwrap()
913 .wait_for_snapshot(response.worktree_scan_id as usize)
914 })?
915 .await?;
916 Ok(())
917 }))
918 }
919 }
920 }
921
922 pub async fn handle_create_entry(
923 this: Entity<Self>,
924 request: proto::CreateProjectEntry,
925 mut cx: AsyncApp,
926 ) -> Result<proto::ProjectEntryResponse> {
927 let (scan_id, entry) = this.update(&mut cx, |this, cx| {
928 anyhow::Ok((
929 this.scan_id(),
930 this.create_entry(
931 RelPath::from_proto(&request.path).with_context(|| {
932 format!("received invalid relative path {:?}", request.path)
933 })?,
934 request.is_directory,
935 request.content,
936 cx,
937 ),
938 ))
939 })?;
940 Ok(proto::ProjectEntryResponse {
941 entry: match &entry.await? {
942 CreatedEntry::Included(entry) => Some(entry.into()),
943 CreatedEntry::Excluded { .. } => None,
944 },
945 worktree_scan_id: scan_id as u64,
946 })
947 }
948
949 pub async fn handle_delete_entry(
950 this: Entity<Self>,
951 request: proto::DeleteProjectEntry,
952 mut cx: AsyncApp,
953 ) -> Result<proto::ProjectEntryResponse> {
954 let (scan_id, task) = this.update(&mut cx, |this, cx| {
955 (
956 this.scan_id(),
957 this.delete_entry(
958 ProjectEntryId::from_proto(request.entry_id),
959 request.use_trash,
960 cx,
961 ),
962 )
963 });
964 task.ok_or_else(|| anyhow::anyhow!("invalid entry"))?
965 .await?;
966 Ok(proto::ProjectEntryResponse {
967 entry: None,
968 worktree_scan_id: scan_id as u64,
969 })
970 }
971
972 pub async fn handle_expand_entry(
973 this: Entity<Self>,
974 request: proto::ExpandProjectEntry,
975 mut cx: AsyncApp,
976 ) -> Result<proto::ExpandProjectEntryResponse> {
977 let task = this.update(&mut cx, |this, cx| {
978 this.expand_entry(ProjectEntryId::from_proto(request.entry_id), cx)
979 });
980 task.ok_or_else(|| anyhow::anyhow!("no such entry"))?
981 .await?;
982 let scan_id = this.read_with(&cx, |this, _| this.scan_id());
983 Ok(proto::ExpandProjectEntryResponse {
984 worktree_scan_id: scan_id as u64,
985 })
986 }
987
988 pub async fn handle_expand_all_for_entry(
989 this: Entity<Self>,
990 request: proto::ExpandAllForProjectEntry,
991 mut cx: AsyncApp,
992 ) -> Result<proto::ExpandAllForProjectEntryResponse> {
993 let task = this.update(&mut cx, |this, cx| {
994 this.expand_all_for_entry(ProjectEntryId::from_proto(request.entry_id), cx)
995 });
996 task.ok_or_else(|| anyhow::anyhow!("no such entry"))?
997 .await?;
998 let scan_id = this.read_with(&cx, |this, _| this.scan_id());
999 Ok(proto::ExpandAllForProjectEntryResponse {
1000 worktree_scan_id: scan_id as u64,
1001 })
1002 }
1003
1004 pub fn is_single_file(&self) -> bool {
1005 self.root_dir().is_none()
1006 }
1007
1008 /// For visible worktrees, returns the path with the worktree name as the first component.
1009 /// Otherwise, returns an absolute path.
1010 pub fn full_path(&self, worktree_relative_path: &RelPath) -> PathBuf {
1011 if self.is_visible() {
1012 self.root_name()
1013 .join(worktree_relative_path)
1014 .display(self.path_style)
1015 .to_string()
1016 .into()
1017 } else {
1018 let full_path = self.abs_path();
1019 let mut full_path_string = if self.is_local()
1020 && let Ok(stripped) = full_path.strip_prefix(home_dir())
1021 {
1022 self.path_style
1023 .join("~", &*stripped.to_string_lossy())
1024 .unwrap()
1025 } else {
1026 full_path.to_string_lossy().into_owned()
1027 };
1028
1029 if worktree_relative_path.components().next().is_some() {
1030 full_path_string.push_str(self.path_style.primary_separator());
1031 full_path_string.push_str(&worktree_relative_path.display(self.path_style));
1032 }
1033
1034 full_path_string.into()
1035 }
1036 }
1037}
1038
1039impl LocalWorktree {
1040 pub fn fs(&self) -> &Arc<dyn Fs> {
1041 &self.fs
1042 }
1043
1044 pub fn is_path_private(&self, path: &RelPath) -> bool {
1045 !self.share_private_files && self.settings.is_path_private(path)
1046 }
1047
1048 pub fn fs_is_case_sensitive(&self) -> bool {
1049 self.fs_case_sensitive
1050 }
1051
1052 fn restart_background_scanners(&mut self, cx: &Context<Worktree>) {
1053 let (scan_requests_tx, scan_requests_rx) = channel::unbounded();
1054 let (path_prefixes_to_scan_tx, path_prefixes_to_scan_rx) = channel::unbounded();
1055 self.scan_requests_tx = scan_requests_tx;
1056 self.path_prefixes_to_scan_tx = path_prefixes_to_scan_tx;
1057
1058 self.start_background_scanner(scan_requests_rx, path_prefixes_to_scan_rx, cx);
1059 let always_included_entries = mem::take(&mut self.snapshot.always_included_entries);
1060 log::debug!(
1061 "refreshing entries for the following always included paths: {:?}",
1062 always_included_entries
1063 );
1064
1065 // Cleans up old always included entries to ensure they get updated properly. Otherwise,
1066 // nested always included entries may not get updated and will result in out-of-date info.
1067 self.refresh_entries_for_paths(always_included_entries);
1068 }
1069
1070 fn start_background_scanner(
1071 &mut self,
1072 scan_requests_rx: channel::Receiver<ScanRequest>,
1073 path_prefixes_to_scan_rx: channel::Receiver<PathPrefixScanRequest>,
1074 cx: &Context<Worktree>,
1075 ) {
1076 let snapshot = self.snapshot();
1077 let share_private_files = self.share_private_files;
1078 let next_entry_id = self.next_entry_id.clone();
1079 let fs = self.fs.clone();
1080 let scanning_enabled = self.scanning_enabled;
1081 let settings = self.settings.clone();
1082 let (scan_states_tx, mut scan_states_rx) = mpsc::unbounded();
1083 let background_scanner = cx.background_spawn({
1084 let abs_path = snapshot.abs_path.as_path().to_path_buf();
1085 let background = cx.background_executor().clone();
1086 async move {
1087 let (events, watcher) = if scanning_enabled {
1088 fs.watch(&abs_path, FS_WATCH_LATENCY).await
1089 } else {
1090 (Box::pin(stream::pending()) as _, Arc::new(NullWatcher) as _)
1091 };
1092 let fs_case_sensitive = fs.is_case_sensitive().await.unwrap_or_else(|e| {
1093 log::error!("Failed to determine whether filesystem is case sensitive: {e:#}");
1094 true
1095 });
1096
1097 let mut scanner = BackgroundScanner {
1098 fs,
1099 fs_case_sensitive,
1100 status_updates_tx: scan_states_tx,
1101 executor: background,
1102 scan_requests_rx,
1103 path_prefixes_to_scan_rx,
1104 next_entry_id,
1105 state: async_lock::Mutex::new(BackgroundScannerState {
1106 prev_snapshot: snapshot.snapshot.clone(),
1107 snapshot,
1108 scanned_dirs: Default::default(),
1109 scanning_enabled,
1110 path_prefixes_to_scan: Default::default(),
1111 paths_to_scan: Default::default(),
1112 removed_entries: Default::default(),
1113 changed_paths: Default::default(),
1114 }),
1115 phase: BackgroundScannerPhase::InitialScan,
1116 share_private_files,
1117 settings,
1118 watcher,
1119 };
1120
1121 scanner
1122 .run(Box::pin(events.map(|events| events.into_iter().collect())))
1123 .await;
1124 }
1125 });
1126 let scan_state_updater = cx.spawn(async move |this, cx| {
1127 while let Some((state, this)) = scan_states_rx.next().await.zip(this.upgrade()) {
1128 this.update(cx, |this, cx| {
1129 let this = this.as_local_mut().unwrap();
1130 match state {
1131 ScanState::Started => {
1132 *this.is_scanning.0.borrow_mut() = true;
1133 }
1134 ScanState::Updated {
1135 snapshot,
1136 changes,
1137 barrier,
1138 scanning,
1139 } => {
1140 *this.is_scanning.0.borrow_mut() = scanning;
1141 this.set_snapshot(snapshot, changes, cx);
1142 drop(barrier);
1143 }
1144 ScanState::RootUpdated { new_path } => {
1145 this.update_abs_path_and_refresh(new_path, cx);
1146 }
1147 }
1148 });
1149 }
1150 });
1151 self._background_scanner_tasks = vec![background_scanner, scan_state_updater];
1152 *self.is_scanning.0.borrow_mut() = true;
1153 }
1154
1155 fn set_snapshot(
1156 &mut self,
1157 mut new_snapshot: LocalSnapshot,
1158 entry_changes: UpdatedEntriesSet,
1159 cx: &mut Context<Worktree>,
1160 ) {
1161 let repo_changes = self.changed_repos(&self.snapshot, &mut new_snapshot);
1162 self.snapshot = new_snapshot;
1163
1164 if let Some(share) = self.update_observer.as_mut() {
1165 share
1166 .snapshots_tx
1167 .unbounded_send((self.snapshot.clone(), entry_changes.clone()))
1168 .ok();
1169 }
1170
1171 if !entry_changes.is_empty() {
1172 cx.emit(Event::UpdatedEntries(entry_changes));
1173 }
1174 if !repo_changes.is_empty() {
1175 cx.emit(Event::UpdatedGitRepositories(repo_changes));
1176 }
1177 }
1178
1179 fn changed_repos(
1180 &self,
1181 old_snapshot: &LocalSnapshot,
1182 new_snapshot: &mut LocalSnapshot,
1183 ) -> UpdatedGitRepositoriesSet {
1184 let mut changes = Vec::new();
1185 let mut old_repos = old_snapshot.git_repositories.iter().peekable();
1186 let new_repos = new_snapshot.git_repositories.clone();
1187 let mut new_repos = new_repos.iter().peekable();
1188
1189 loop {
1190 match (new_repos.peek().map(clone), old_repos.peek().map(clone)) {
1191 (Some((new_entry_id, new_repo)), Some((old_entry_id, old_repo))) => {
1192 match Ord::cmp(&new_entry_id, &old_entry_id) {
1193 Ordering::Less => {
1194 changes.push(UpdatedGitRepository {
1195 work_directory_id: new_entry_id,
1196 old_work_directory_abs_path: None,
1197 new_work_directory_abs_path: Some(
1198 new_repo.work_directory_abs_path.clone(),
1199 ),
1200 dot_git_abs_path: Some(new_repo.dot_git_abs_path.clone()),
1201 repository_dir_abs_path: Some(
1202 new_repo.repository_dir_abs_path.clone(),
1203 ),
1204 common_dir_abs_path: Some(new_repo.common_dir_abs_path.clone()),
1205 });
1206 new_repos.next();
1207 }
1208 Ordering::Equal => {
1209 if new_repo.git_dir_scan_id != old_repo.git_dir_scan_id
1210 || new_repo.work_directory_abs_path
1211 != old_repo.work_directory_abs_path
1212 {
1213 changes.push(UpdatedGitRepository {
1214 work_directory_id: new_entry_id,
1215 old_work_directory_abs_path: Some(
1216 old_repo.work_directory_abs_path.clone(),
1217 ),
1218 new_work_directory_abs_path: Some(
1219 new_repo.work_directory_abs_path.clone(),
1220 ),
1221 dot_git_abs_path: Some(new_repo.dot_git_abs_path.clone()),
1222 repository_dir_abs_path: Some(
1223 new_repo.repository_dir_abs_path.clone(),
1224 ),
1225 common_dir_abs_path: Some(new_repo.common_dir_abs_path.clone()),
1226 });
1227 }
1228 new_repos.next();
1229 old_repos.next();
1230 }
1231 Ordering::Greater => {
1232 changes.push(UpdatedGitRepository {
1233 work_directory_id: old_entry_id,
1234 old_work_directory_abs_path: Some(
1235 old_repo.work_directory_abs_path.clone(),
1236 ),
1237 new_work_directory_abs_path: None,
1238 dot_git_abs_path: None,
1239 repository_dir_abs_path: None,
1240 common_dir_abs_path: None,
1241 });
1242 old_repos.next();
1243 }
1244 }
1245 }
1246 (Some((entry_id, repo)), None) => {
1247 changes.push(UpdatedGitRepository {
1248 work_directory_id: entry_id,
1249 old_work_directory_abs_path: None,
1250 new_work_directory_abs_path: Some(repo.work_directory_abs_path.clone()),
1251 dot_git_abs_path: Some(repo.dot_git_abs_path.clone()),
1252 repository_dir_abs_path: Some(repo.repository_dir_abs_path.clone()),
1253 common_dir_abs_path: Some(repo.common_dir_abs_path.clone()),
1254 });
1255 new_repos.next();
1256 }
1257 (None, Some((entry_id, repo))) => {
1258 changes.push(UpdatedGitRepository {
1259 work_directory_id: entry_id,
1260 old_work_directory_abs_path: Some(repo.work_directory_abs_path.clone()),
1261 new_work_directory_abs_path: None,
1262 dot_git_abs_path: Some(repo.dot_git_abs_path.clone()),
1263 repository_dir_abs_path: Some(repo.repository_dir_abs_path.clone()),
1264 common_dir_abs_path: Some(repo.common_dir_abs_path.clone()),
1265 });
1266 old_repos.next();
1267 }
1268 (None, None) => break,
1269 }
1270 }
1271
1272 fn clone<T: Clone, U: Clone>(value: &(&T, &U)) -> (T, U) {
1273 (value.0.clone(), value.1.clone())
1274 }
1275
1276 changes.into()
1277 }
1278
1279 pub fn scan_complete(&self) -> impl Future<Output = ()> + use<> {
1280 let mut is_scanning_rx = self.is_scanning.1.clone();
1281 async move {
1282 let mut is_scanning = *is_scanning_rx.borrow();
1283 while is_scanning {
1284 if let Some(value) = is_scanning_rx.recv().await {
1285 is_scanning = value;
1286 } else {
1287 break;
1288 }
1289 }
1290 }
1291 }
1292
1293 pub fn snapshot(&self) -> LocalSnapshot {
1294 self.snapshot.clone()
1295 }
1296
1297 pub fn settings(&self) -> WorktreeSettings {
1298 self.settings.clone()
1299 }
1300
1301 fn load_binary_file(
1302 &self,
1303 path: &RelPath,
1304 cx: &Context<Worktree>,
1305 ) -> Task<Result<LoadedBinaryFile>> {
1306 let path = Arc::from(path);
1307 let abs_path = self.absolutize(&path);
1308 let fs = self.fs.clone();
1309 let entry = self.refresh_entry(path.clone(), None, cx);
1310 let is_private = self.is_path_private(&path);
1311
1312 let worktree = cx.weak_entity();
1313 cx.background_spawn(async move {
1314 let content = fs.load_bytes(&abs_path).await?;
1315
1316 let worktree = worktree.upgrade().context("worktree was dropped")?;
1317 let file = match entry.await? {
1318 Some(entry) => File::for_entry(entry, worktree),
1319 None => {
1320 let metadata = fs
1321 .metadata(&abs_path)
1322 .await
1323 .with_context(|| {
1324 format!("Loading metadata for excluded file {abs_path:?}")
1325 })?
1326 .with_context(|| {
1327 format!("Excluded file {abs_path:?} got removed during loading")
1328 })?;
1329 Arc::new(File {
1330 entry_id: None,
1331 worktree,
1332 path,
1333 disk_state: DiskState::Present {
1334 mtime: metadata.mtime,
1335 },
1336 is_local: true,
1337 is_private,
1338 })
1339 }
1340 };
1341
1342 Ok(LoadedBinaryFile { file, content })
1343 })
1344 }
1345
1346 fn load_file(&self, path: &RelPath, cx: &Context<Worktree>) -> Task<Result<LoadedFile>> {
1347 let path = Arc::from(path);
1348 let abs_path = self.absolutize(&path);
1349 let fs = self.fs.clone();
1350 let entry = self.refresh_entry(path.clone(), None, cx);
1351 let is_private = self.is_path_private(path.as_ref());
1352
1353 let this = cx.weak_entity();
1354 cx.background_spawn(async move {
1355 // WARN: Temporary workaround for #27283.
1356 // We are not efficient with our memory usage per file, and use in excess of 64GB for a 10GB file
1357 // Therefore, as a temporary workaround to prevent system freezes, we just bail before opening a file
1358 // if it is too large
1359 // 5GB seems to be more reasonable, peaking at ~16GB, while 6GB jumps up to >24GB which seems like a
1360 // reasonable limit
1361 {
1362 const FILE_SIZE_MAX: u64 = 6 * 1024 * 1024 * 1024; // 6GB
1363 if let Ok(Some(metadata)) = fs.metadata(&abs_path).await
1364 && metadata.len >= FILE_SIZE_MAX
1365 {
1366 anyhow::bail!("File is too large to load");
1367 }
1368 }
1369 let (text, encoding, has_bom) = decode_file_text(fs.as_ref(), &abs_path).await?;
1370
1371 let worktree = this.upgrade().context("worktree was dropped")?;
1372 let file = match entry.await? {
1373 Some(entry) => File::for_entry(entry, worktree),
1374 None => {
1375 let metadata = fs
1376 .metadata(&abs_path)
1377 .await
1378 .with_context(|| {
1379 format!("Loading metadata for excluded file {abs_path:?}")
1380 })?
1381 .with_context(|| {
1382 format!("Excluded file {abs_path:?} got removed during loading")
1383 })?;
1384 Arc::new(File {
1385 entry_id: None,
1386 worktree,
1387 path,
1388 disk_state: DiskState::Present {
1389 mtime: metadata.mtime,
1390 },
1391 is_local: true,
1392 is_private,
1393 })
1394 }
1395 };
1396
1397 Ok(LoadedFile {
1398 file,
1399 text,
1400 encoding,
1401 has_bom,
1402 })
1403 })
1404 }
1405
1406 /// Find the lowest path in the worktree's datastructures that is an ancestor
1407 fn lowest_ancestor(&self, path: &RelPath) -> Arc<RelPath> {
1408 let mut lowest_ancestor = None;
1409 for path in path.ancestors() {
1410 if self.entry_for_path(path).is_some() {
1411 lowest_ancestor = Some(path.into());
1412 break;
1413 }
1414 }
1415
1416 lowest_ancestor.unwrap_or_else(|| RelPath::empty().into())
1417 }
1418
1419 fn create_entry(
1420 &self,
1421 path: Arc<RelPath>,
1422 is_dir: bool,
1423 content: Option<Vec<u8>>,
1424 cx: &Context<Worktree>,
1425 ) -> Task<Result<CreatedEntry>> {
1426 let abs_path = self.absolutize(&path);
1427 let path_excluded = self.settings.is_path_excluded(&path);
1428 let fs = self.fs.clone();
1429 let task_abs_path = abs_path.clone();
1430 let write = cx.background_spawn(async move {
1431 if is_dir {
1432 fs.create_dir(&task_abs_path)
1433 .await
1434 .with_context(|| format!("creating directory {task_abs_path:?}"))
1435 } else {
1436 fs.write(&task_abs_path, content.as_deref().unwrap_or(&[]))
1437 .await
1438 .with_context(|| format!("creating file {task_abs_path:?}"))
1439 }
1440 });
1441
1442 let lowest_ancestor = self.lowest_ancestor(&path);
1443 cx.spawn(async move |this, cx| {
1444 write.await?;
1445 if path_excluded {
1446 return Ok(CreatedEntry::Excluded { abs_path });
1447 }
1448
1449 let (result, refreshes) = this.update(cx, |this, cx| {
1450 let mut refreshes = Vec::new();
1451 let refresh_paths = path.strip_prefix(&lowest_ancestor).unwrap();
1452 for refresh_path in refresh_paths.ancestors() {
1453 if refresh_path == RelPath::empty() {
1454 continue;
1455 }
1456 let refresh_full_path = lowest_ancestor.join(refresh_path);
1457
1458 refreshes.push(this.as_local_mut().unwrap().refresh_entry(
1459 refresh_full_path,
1460 None,
1461 cx,
1462 ));
1463 }
1464 (
1465 this.as_local_mut().unwrap().refresh_entry(path, None, cx),
1466 refreshes,
1467 )
1468 })?;
1469 for refresh in refreshes {
1470 refresh.await.log_err();
1471 }
1472
1473 Ok(result
1474 .await?
1475 .map(CreatedEntry::Included)
1476 .unwrap_or_else(|| CreatedEntry::Excluded { abs_path }))
1477 })
1478 }
1479
1480 fn write_file(
1481 &self,
1482 path: Arc<RelPath>,
1483 text: Rope,
1484 line_ending: LineEnding,
1485 encoding: &'static Encoding,
1486 has_bom: bool,
1487 cx: &Context<Worktree>,
1488 ) -> Task<Result<Arc<File>>> {
1489 let fs = self.fs.clone();
1490 let is_private = self.is_path_private(&path);
1491 let abs_path = self.absolutize(&path);
1492
1493 let write = cx.background_spawn({
1494 let fs = fs.clone();
1495 let abs_path = abs_path.clone();
1496 async move {
1497 // For UTF-8, use the optimized `fs.save` which writes Rope chunks directly to disk
1498 // without allocating a contiguous string.
1499 if encoding == encoding_rs::UTF_8 && !has_bom {
1500 return fs.save(&abs_path, &text, line_ending).await;
1501 }
1502
1503 // For legacy encodings (e.g. Shift-JIS), we fall back to converting the entire Rope
1504 // to a String/Bytes in memory before writing.
1505 //
1506 // Note: This is inefficient for very large files compared to the streaming approach above,
1507 // but supporting streaming writes for arbitrary encodings would require a significant
1508 // refactor of the `fs` crate to expose a Writer interface.
1509 let text_string = text.to_string();
1510 let normalized_text = match line_ending {
1511 LineEnding::Unix => text_string,
1512 LineEnding::Windows => text_string.replace('\n', "\r\n"),
1513 };
1514
1515 // Create the byte vector manually for UTF-16 encodings because encoding_rs encodes to UTF-8 by default (per WHATWG standards),
1516 // which is not what we want for saving files.
1517 let bytes = if encoding == encoding_rs::UTF_16BE {
1518 let mut data = Vec::with_capacity(normalized_text.len() * 2 + 2);
1519 if has_bom {
1520 data.extend_from_slice(&[0xFE, 0xFF]); // BOM
1521 }
1522 let utf16be_bytes =
1523 normalized_text.encode_utf16().flat_map(|u| u.to_be_bytes());
1524 data.extend(utf16be_bytes);
1525 data.into()
1526 } else if encoding == encoding_rs::UTF_16LE {
1527 let mut data = Vec::with_capacity(normalized_text.len() * 2 + 2);
1528 if has_bom {
1529 data.extend_from_slice(&[0xFF, 0xFE]); // BOM
1530 }
1531 let utf16le_bytes =
1532 normalized_text.encode_utf16().flat_map(|u| u.to_le_bytes());
1533 data.extend(utf16le_bytes);
1534 data.into()
1535 } else {
1536 // For other encodings (Shift-JIS, UTF-8 with BOM, etc.), delegate to encoding_rs.
1537 let bom_bytes = if has_bom {
1538 if encoding == encoding_rs::UTF_8 {
1539 vec![0xEF, 0xBB, 0xBF]
1540 } else {
1541 vec![]
1542 }
1543 } else {
1544 vec![]
1545 };
1546 let (cow, _, _) = encoding.encode(&normalized_text);
1547 if !bom_bytes.is_empty() {
1548 let mut bytes = bom_bytes;
1549 bytes.extend_from_slice(&cow);
1550 bytes.into()
1551 } else {
1552 cow
1553 }
1554 };
1555
1556 fs.write(&abs_path, &bytes).await
1557 }
1558 });
1559
1560 cx.spawn(async move |this, cx| {
1561 write.await?;
1562 let entry = this
1563 .update(cx, |this, cx| {
1564 this.as_local_mut()
1565 .unwrap()
1566 .refresh_entry(path.clone(), None, cx)
1567 })?
1568 .await?;
1569 let worktree = this.upgrade().context("worktree dropped")?;
1570 if let Some(entry) = entry {
1571 Ok(File::for_entry(entry, worktree))
1572 } else {
1573 let metadata = fs
1574 .metadata(&abs_path)
1575 .await
1576 .with_context(|| {
1577 format!("Fetching metadata after saving the excluded buffer {abs_path:?}")
1578 })?
1579 .with_context(|| {
1580 format!("Excluded buffer {path:?} got removed during saving")
1581 })?;
1582 Ok(Arc::new(File {
1583 worktree,
1584 path,
1585 disk_state: DiskState::Present {
1586 mtime: metadata.mtime,
1587 },
1588 entry_id: None,
1589 is_local: true,
1590 is_private,
1591 }))
1592 }
1593 })
1594 }
1595
1596 fn delete_entry(
1597 &self,
1598 entry_id: ProjectEntryId,
1599 trash: bool,
1600 cx: &Context<Worktree>,
1601 ) -> Option<Task<Result<()>>> {
1602 let entry = self.entry_for_id(entry_id)?.clone();
1603 let abs_path = self.absolutize(&entry.path);
1604 let fs = self.fs.clone();
1605
1606 let delete = cx.background_spawn(async move {
1607 if entry.is_file() {
1608 if trash {
1609 fs.trash_file(&abs_path, Default::default()).await?;
1610 } else {
1611 fs.remove_file(&abs_path, Default::default()).await?;
1612 }
1613 } else if trash {
1614 fs.trash_dir(
1615 &abs_path,
1616 RemoveOptions {
1617 recursive: true,
1618 ignore_if_not_exists: false,
1619 },
1620 )
1621 .await?;
1622 } else {
1623 fs.remove_dir(
1624 &abs_path,
1625 RemoveOptions {
1626 recursive: true,
1627 ignore_if_not_exists: false,
1628 },
1629 )
1630 .await?;
1631 }
1632 anyhow::Ok(entry.path)
1633 });
1634
1635 Some(cx.spawn(async move |this, cx| {
1636 let path = delete.await?;
1637 this.update(cx, |this, _| {
1638 this.as_local_mut()
1639 .unwrap()
1640 .refresh_entries_for_paths(vec![path])
1641 })?
1642 .recv()
1643 .await;
1644 Ok(())
1645 }))
1646 }
1647
1648 pub fn copy_external_entries(
1649 &self,
1650 target_directory: Arc<RelPath>,
1651 paths: Vec<Arc<Path>>,
1652 cx: &Context<Worktree>,
1653 ) -> Task<Result<Vec<ProjectEntryId>>> {
1654 let target_directory = self.absolutize(&target_directory);
1655 let worktree_path = self.abs_path().clone();
1656 let fs = self.fs.clone();
1657 let paths = paths
1658 .into_iter()
1659 .filter_map(|source| {
1660 let file_name = source.file_name()?;
1661 let mut target = target_directory.clone();
1662 target.push(file_name);
1663
1664 // Do not allow copying the same file to itself.
1665 if source.as_ref() != target.as_path() {
1666 Some((source, target))
1667 } else {
1668 None
1669 }
1670 })
1671 .collect::<Vec<_>>();
1672
1673 let paths_to_refresh = paths
1674 .iter()
1675 .filter_map(|(_, target)| {
1676 RelPath::new(
1677 target.strip_prefix(&worktree_path).ok()?,
1678 PathStyle::local(),
1679 )
1680 .ok()
1681 .map(|path| path.into_arc())
1682 })
1683 .collect::<Vec<_>>();
1684
1685 cx.spawn(async move |this, cx| {
1686 cx.background_spawn(async move {
1687 for (source, target) in paths {
1688 copy_recursive(
1689 fs.as_ref(),
1690 &source,
1691 &target,
1692 fs::CopyOptions {
1693 overwrite: true,
1694 ..Default::default()
1695 },
1696 )
1697 .await
1698 .with_context(|| {
1699 format!("Failed to copy file from {source:?} to {target:?}")
1700 })?;
1701 }
1702 anyhow::Ok(())
1703 })
1704 .await
1705 .log_err();
1706 let mut refresh = cx.read_entity(
1707 &this.upgrade().with_context(|| "Dropped worktree")?,
1708 |this, _| {
1709 anyhow::Ok::<postage::barrier::Receiver>(
1710 this.as_local()
1711 .with_context(|| "Worktree is not local")?
1712 .refresh_entries_for_paths(paths_to_refresh.clone()),
1713 )
1714 },
1715 )?;
1716
1717 cx.background_spawn(async move {
1718 refresh.next().await;
1719 anyhow::Ok(())
1720 })
1721 .await
1722 .log_err();
1723
1724 let this = this.upgrade().with_context(|| "Dropped worktree")?;
1725 Ok(cx.read_entity(&this, |this, _| {
1726 paths_to_refresh
1727 .iter()
1728 .filter_map(|path| Some(this.entry_for_path(path)?.id))
1729 .collect()
1730 }))
1731 })
1732 }
1733
1734 fn expand_entry(
1735 &self,
1736 entry_id: ProjectEntryId,
1737 cx: &Context<Worktree>,
1738 ) -> Option<Task<Result<()>>> {
1739 let path = self.entry_for_id(entry_id)?.path.clone();
1740 let mut refresh = self.refresh_entries_for_paths(vec![path]);
1741 Some(cx.background_spawn(async move {
1742 refresh.next().await;
1743 Ok(())
1744 }))
1745 }
1746
1747 fn expand_all_for_entry(
1748 &self,
1749 entry_id: ProjectEntryId,
1750 cx: &Context<Worktree>,
1751 ) -> Option<Task<Result<()>>> {
1752 let path = self.entry_for_id(entry_id).unwrap().path.clone();
1753 let mut rx = self.add_path_prefix_to_scan(path);
1754 Some(cx.background_spawn(async move {
1755 rx.next().await;
1756 Ok(())
1757 }))
1758 }
1759
1760 pub fn refresh_entries_for_paths(&self, paths: Vec<Arc<RelPath>>) -> barrier::Receiver {
1761 let (tx, rx) = barrier::channel();
1762 self.scan_requests_tx
1763 .try_send(ScanRequest {
1764 relative_paths: paths,
1765 done: smallvec![tx],
1766 })
1767 .ok();
1768 rx
1769 }
1770
1771 #[cfg(feature = "test-support")]
1772 pub fn manually_refresh_entries_for_paths(
1773 &self,
1774 paths: Vec<Arc<RelPath>>,
1775 ) -> barrier::Receiver {
1776 self.refresh_entries_for_paths(paths)
1777 }
1778
1779 pub fn add_path_prefix_to_scan(&self, path_prefix: Arc<RelPath>) -> barrier::Receiver {
1780 let (tx, rx) = barrier::channel();
1781 self.path_prefixes_to_scan_tx
1782 .try_send(PathPrefixScanRequest {
1783 path: path_prefix,
1784 done: smallvec![tx],
1785 })
1786 .ok();
1787 rx
1788 }
1789
1790 pub fn refresh_entry(
1791 &self,
1792 path: Arc<RelPath>,
1793 old_path: Option<Arc<RelPath>>,
1794 cx: &Context<Worktree>,
1795 ) -> Task<Result<Option<Entry>>> {
1796 if self.settings.is_path_excluded(&path) {
1797 return Task::ready(Ok(None));
1798 }
1799 let paths = if let Some(old_path) = old_path.as_ref() {
1800 vec![old_path.clone(), path.clone()]
1801 } else {
1802 vec![path.clone()]
1803 };
1804 let t0 = Instant::now();
1805 let mut refresh = self.refresh_entries_for_paths(paths);
1806 // todo(lw): Hot foreground spawn
1807 cx.spawn(async move |this, cx| {
1808 refresh.recv().await;
1809 log::trace!("refreshed entry {path:?} in {:?}", t0.elapsed());
1810 let new_entry = this.read_with(cx, |this, _| {
1811 this.entry_for_path(&path).cloned().with_context(|| {
1812 format!("Could not find entry in worktree for {path:?} after refresh")
1813 })
1814 })??;
1815 Ok(Some(new_entry))
1816 })
1817 }
1818
1819 fn observe_updates<F, Fut>(&mut self, project_id: u64, cx: &Context<Worktree>, callback: F)
1820 where
1821 F: 'static + Send + Fn(proto::UpdateWorktree) -> Fut,
1822 Fut: 'static + Send + Future<Output = bool>,
1823 {
1824 if let Some(observer) = self.update_observer.as_mut() {
1825 *observer.resume_updates.borrow_mut() = ();
1826 return;
1827 }
1828
1829 let (resume_updates_tx, mut resume_updates_rx) = watch::channel::<()>();
1830 let (snapshots_tx, mut snapshots_rx) =
1831 mpsc::unbounded::<(LocalSnapshot, UpdatedEntriesSet)>();
1832 snapshots_tx
1833 .unbounded_send((self.snapshot(), Arc::default()))
1834 .ok();
1835
1836 let worktree_id = cx.entity_id().as_u64();
1837 let _maintain_remote_snapshot = cx.background_spawn(async move {
1838 let mut is_first = true;
1839 while let Some((snapshot, entry_changes)) = snapshots_rx.next().await {
1840 let update = if is_first {
1841 is_first = false;
1842 snapshot.build_initial_update(project_id, worktree_id)
1843 } else {
1844 snapshot.build_update(project_id, worktree_id, entry_changes)
1845 };
1846
1847 for update in proto::split_worktree_update(update) {
1848 let _ = resume_updates_rx.try_recv();
1849 loop {
1850 let result = callback(update.clone());
1851 if result.await {
1852 break;
1853 } else {
1854 log::info!("waiting to resume updates");
1855 if resume_updates_rx.next().await.is_none() {
1856 return Some(());
1857 }
1858 }
1859 }
1860 }
1861 }
1862 Some(())
1863 });
1864
1865 self.update_observer = Some(UpdateObservationState {
1866 snapshots_tx,
1867 resume_updates: resume_updates_tx,
1868 _maintain_remote_snapshot,
1869 });
1870 }
1871
1872 pub fn share_private_files(&mut self, cx: &Context<Worktree>) {
1873 self.share_private_files = true;
1874 self.restart_background_scanners(cx);
1875 }
1876
1877 pub fn update_abs_path_and_refresh(
1878 &mut self,
1879 new_path: Arc<SanitizedPath>,
1880 cx: &Context<Worktree>,
1881 ) {
1882 self.snapshot.git_repositories = Default::default();
1883 self.snapshot.ignores_by_parent_abs_path = Default::default();
1884 let root_name = new_path
1885 .as_path()
1886 .file_name()
1887 .and_then(|f| f.to_str())
1888 .map_or(RelPath::empty().into(), |f| {
1889 RelPath::unix(f).unwrap().into()
1890 });
1891 self.snapshot.update_abs_path(new_path, root_name);
1892 self.restart_background_scanners(cx);
1893 }
1894}
1895
1896impl RemoteWorktree {
1897 pub fn project_id(&self) -> u64 {
1898 self.project_id
1899 }
1900
1901 pub fn client(&self) -> AnyProtoClient {
1902 self.client.clone()
1903 }
1904
1905 pub fn disconnected_from_host(&mut self) {
1906 self.updates_tx.take();
1907 self.snapshot_subscriptions.clear();
1908 self.disconnected = true;
1909 }
1910
1911 pub fn update_from_remote(&self, update: proto::UpdateWorktree) {
1912 if let Some(updates_tx) = &self.updates_tx {
1913 updates_tx
1914 .unbounded_send(update)
1915 .expect("consumer runs to completion");
1916 }
1917 }
1918
1919 fn observe_updates<F, Fut>(&mut self, project_id: u64, cx: &Context<Worktree>, callback: F)
1920 where
1921 F: 'static + Send + Fn(proto::UpdateWorktree) -> Fut,
1922 Fut: 'static + Send + Future<Output = bool>,
1923 {
1924 let (tx, mut rx) = mpsc::unbounded();
1925 let initial_update = self
1926 .snapshot
1927 .build_initial_update(project_id, self.id().to_proto());
1928 self.update_observer = Some(tx);
1929 cx.spawn(async move |this, cx| {
1930 let mut update = initial_update;
1931 'outer: loop {
1932 // SSH projects use a special project ID of 0, and we need to
1933 // remap it to the correct one here.
1934 update.project_id = project_id;
1935
1936 for chunk in split_worktree_update(update) {
1937 if !callback(chunk).await {
1938 break 'outer;
1939 }
1940 }
1941
1942 if let Some(next_update) = rx.next().await {
1943 update = next_update;
1944 } else {
1945 break;
1946 }
1947 }
1948 this.update(cx, |this, _| {
1949 let this = this.as_remote_mut().unwrap();
1950 this.update_observer.take();
1951 })
1952 })
1953 .detach();
1954 }
1955
1956 fn observed_snapshot(&self, scan_id: usize) -> bool {
1957 self.completed_scan_id >= scan_id
1958 }
1959
1960 pub fn wait_for_snapshot(
1961 &mut self,
1962 scan_id: usize,
1963 ) -> impl Future<Output = Result<()>> + use<> {
1964 let (tx, rx) = oneshot::channel();
1965 if self.observed_snapshot(scan_id) {
1966 let _ = tx.send(());
1967 } else if self.disconnected {
1968 drop(tx);
1969 } else {
1970 match self
1971 .snapshot_subscriptions
1972 .binary_search_by_key(&scan_id, |probe| probe.0)
1973 {
1974 Ok(ix) | Err(ix) => self.snapshot_subscriptions.insert(ix, (scan_id, tx)),
1975 }
1976 }
1977
1978 async move {
1979 rx.await?;
1980 Ok(())
1981 }
1982 }
1983
1984 pub fn insert_entry(
1985 &mut self,
1986 entry: proto::Entry,
1987 scan_id: usize,
1988 cx: &Context<Worktree>,
1989 ) -> Task<Result<Entry>> {
1990 let wait_for_snapshot = self.wait_for_snapshot(scan_id);
1991 cx.spawn(async move |this, cx| {
1992 wait_for_snapshot.await?;
1993 this.update(cx, |worktree, _| {
1994 let worktree = worktree.as_remote_mut().unwrap();
1995 let snapshot = &mut worktree.background_snapshot.lock().0;
1996 let entry = snapshot.insert_entry(entry, &worktree.file_scan_inclusions);
1997 worktree.snapshot = snapshot.clone();
1998 entry
1999 })?
2000 })
2001 }
2002
2003 fn delete_entry(
2004 &self,
2005 entry_id: ProjectEntryId,
2006 trash: bool,
2007 cx: &Context<Worktree>,
2008 ) -> Option<Task<Result<()>>> {
2009 let response = self.client.request(proto::DeleteProjectEntry {
2010 project_id: self.project_id,
2011 entry_id: entry_id.to_proto(),
2012 use_trash: trash,
2013 });
2014 Some(cx.spawn(async move |this, cx| {
2015 let response = response.await?;
2016 let scan_id = response.worktree_scan_id as usize;
2017
2018 this.update(cx, move |this, _| {
2019 this.as_remote_mut().unwrap().wait_for_snapshot(scan_id)
2020 })?
2021 .await?;
2022
2023 this.update(cx, |this, _| {
2024 let this = this.as_remote_mut().unwrap();
2025 let snapshot = &mut this.background_snapshot.lock().0;
2026 snapshot.delete_entry(entry_id);
2027 this.snapshot = snapshot.clone();
2028 })
2029 }))
2030 }
2031
2032 // fn rename_entry(
2033 // &self,
2034 // entry_id: ProjectEntryId,
2035 // new_path: impl Into<Arc<RelPath>>,
2036 // cx: &Context<Worktree>,
2037 // ) -> Task<Result<CreatedEntry>> {
2038 // let new_path: Arc<RelPath> = new_path.into();
2039 // let response = self.client.request(proto::RenameProjectEntry {
2040 // project_id: self.project_id,
2041 // entry_id: entry_id.to_proto(),
2042 // new_worktree_id: new_path.worktree_id,
2043 // new_path: new_path.as_ref().to_proto(),
2044 // });
2045 // cx.spawn(async move |this, cx| {
2046 // let response = response.await?;
2047 // match response.entry {
2048 // Some(entry) => this
2049 // .update(cx, |this, cx| {
2050 // this.as_remote_mut().unwrap().insert_entry(
2051 // entry,
2052 // response.worktree_scan_id as usize,
2053 // cx,
2054 // )
2055 // })?
2056 // .await
2057 // .map(CreatedEntry::Included),
2058 // None => {
2059 // let abs_path =
2060 // this.read_with(cx, |worktree, _| worktree.absolutize(&new_path))?;
2061 // Ok(CreatedEntry::Excluded { abs_path })
2062 // }
2063 // }
2064 // })
2065 // }
2066
2067 fn copy_external_entries(
2068 &self,
2069 target_directory: Arc<RelPath>,
2070 paths_to_copy: Vec<Arc<Path>>,
2071 local_fs: Arc<dyn Fs>,
2072 cx: &Context<Worktree>,
2073 ) -> Task<anyhow::Result<Vec<ProjectEntryId>>> {
2074 let client = self.client.clone();
2075 let worktree_id = self.id().to_proto();
2076 let project_id = self.project_id;
2077
2078 cx.background_spawn(async move {
2079 let mut requests = Vec::new();
2080 for root_path_to_copy in paths_to_copy {
2081 let Some(filename) = root_path_to_copy
2082 .file_name()
2083 .and_then(|name| name.to_str())
2084 .and_then(|filename| RelPath::unix(filename).ok())
2085 else {
2086 continue;
2087 };
2088 for (abs_path, is_directory) in
2089 read_dir_items(local_fs.as_ref(), &root_path_to_copy).await?
2090 {
2091 let Some(relative_path) = abs_path
2092 .strip_prefix(&root_path_to_copy)
2093 .map_err(|e| anyhow::Error::from(e))
2094 .and_then(|relative_path| RelPath::new(relative_path, PathStyle::local()))
2095 .log_err()
2096 else {
2097 continue;
2098 };
2099 let content = if is_directory {
2100 None
2101 } else {
2102 Some(local_fs.load_bytes(&abs_path).await?)
2103 };
2104
2105 let mut target_path = target_directory.join(filename);
2106 if relative_path.file_name().is_some() {
2107 target_path = target_path.join(&relative_path);
2108 }
2109
2110 requests.push(proto::CreateProjectEntry {
2111 project_id,
2112 worktree_id,
2113 path: target_path.to_proto(),
2114 is_directory,
2115 content,
2116 });
2117 }
2118 }
2119 requests.sort_unstable_by(|a, b| a.path.cmp(&b.path));
2120 requests.dedup();
2121
2122 let mut copied_entry_ids = Vec::new();
2123 for request in requests {
2124 let response = client.request(request).await?;
2125 copied_entry_ids.extend(response.entry.map(|e| ProjectEntryId::from_proto(e.id)));
2126 }
2127
2128 Ok(copied_entry_ids)
2129 })
2130 }
2131}
2132
2133impl Snapshot {
2134 pub fn new(
2135 id: u64,
2136 root_name: Arc<RelPath>,
2137 abs_path: Arc<Path>,
2138 path_style: PathStyle,
2139 ) -> Self {
2140 Snapshot {
2141 id: WorktreeId::from_usize(id as usize),
2142 abs_path: SanitizedPath::from_arc(abs_path),
2143 path_style,
2144 root_char_bag: root_name
2145 .as_unix_str()
2146 .chars()
2147 .map(|c| c.to_ascii_lowercase())
2148 .collect(),
2149 root_name,
2150 always_included_entries: Default::default(),
2151 entries_by_path: Default::default(),
2152 entries_by_id: Default::default(),
2153 scan_id: 1,
2154 completed_scan_id: 0,
2155 }
2156 }
2157
2158 pub fn id(&self) -> WorktreeId {
2159 self.id
2160 }
2161
2162 // TODO:
2163 // Consider the following:
2164 //
2165 // ```rust
2166 // let abs_path: Arc<Path> = snapshot.abs_path(); // e.g. "C:\Users\user\Desktop\project"
2167 // let some_non_trimmed_path = Path::new("\\\\?\\C:\\Users\\user\\Desktop\\project\\main.rs");
2168 // // The caller perform some actions here:
2169 // some_non_trimmed_path.strip_prefix(abs_path); // This fails
2170 // some_non_trimmed_path.starts_with(abs_path); // This fails too
2171 // ```
2172 //
2173 // This is definitely a bug, but it's not clear if we should handle it here or not.
2174 pub fn abs_path(&self) -> &Arc<Path> {
2175 SanitizedPath::cast_arc_ref(&self.abs_path)
2176 }
2177
2178 fn build_initial_update(&self, project_id: u64, worktree_id: u64) -> proto::UpdateWorktree {
2179 let mut updated_entries = self
2180 .entries_by_path
2181 .iter()
2182 .map(proto::Entry::from)
2183 .collect::<Vec<_>>();
2184 updated_entries.sort_unstable_by_key(|e| e.id);
2185
2186 proto::UpdateWorktree {
2187 project_id,
2188 worktree_id,
2189 abs_path: self.abs_path().to_string_lossy().into_owned(),
2190 root_name: self.root_name().to_proto(),
2191 updated_entries,
2192 removed_entries: Vec::new(),
2193 scan_id: self.scan_id as u64,
2194 is_last_update: self.completed_scan_id == self.scan_id,
2195 // Sent in separate messages.
2196 updated_repositories: Vec::new(),
2197 removed_repositories: Vec::new(),
2198 }
2199 }
2200
2201 pub fn work_directory_abs_path(&self, work_directory: &WorkDirectory) -> PathBuf {
2202 match work_directory {
2203 WorkDirectory::InProject { relative_path } => self.absolutize(relative_path),
2204 WorkDirectory::AboveProject { absolute_path, .. } => absolute_path.as_ref().to_owned(),
2205 }
2206 }
2207
2208 pub fn absolutize(&self, path: &RelPath) -> PathBuf {
2209 if path.file_name().is_some() {
2210 let mut abs_path = self.abs_path.to_string();
2211 for component in path.components() {
2212 if !abs_path.ends_with(self.path_style.primary_separator()) {
2213 abs_path.push_str(self.path_style.primary_separator());
2214 }
2215 abs_path.push_str(component);
2216 }
2217 PathBuf::from(abs_path)
2218 } else {
2219 self.abs_path.as_path().to_path_buf()
2220 }
2221 }
2222
2223 pub fn contains_entry(&self, entry_id: ProjectEntryId) -> bool {
2224 self.entries_by_id.get(&entry_id, ()).is_some()
2225 }
2226
2227 fn insert_entry(
2228 &mut self,
2229 entry: proto::Entry,
2230 always_included_paths: &PathMatcher,
2231 ) -> Result<Entry> {
2232 let entry = Entry::try_from((&self.root_char_bag, always_included_paths, entry))?;
2233 let old_entry = self.entries_by_id.insert_or_replace(
2234 PathEntry {
2235 id: entry.id,
2236 path: entry.path.clone(),
2237 is_ignored: entry.is_ignored,
2238 scan_id: 0,
2239 },
2240 (),
2241 );
2242 if let Some(old_entry) = old_entry {
2243 self.entries_by_path.remove(&PathKey(old_entry.path), ());
2244 }
2245 self.entries_by_path.insert_or_replace(entry.clone(), ());
2246 Ok(entry)
2247 }
2248
2249 fn delete_entry(&mut self, entry_id: ProjectEntryId) -> Option<Arc<RelPath>> {
2250 let removed_entry = self.entries_by_id.remove(&entry_id, ())?;
2251 self.entries_by_path = {
2252 let mut cursor = self.entries_by_path.cursor::<TraversalProgress>(());
2253 let mut new_entries_by_path =
2254 cursor.slice(&TraversalTarget::path(&removed_entry.path), Bias::Left);
2255 while let Some(entry) = cursor.item() {
2256 if entry.path.starts_with(&removed_entry.path) {
2257 self.entries_by_id.remove(&entry.id, ());
2258 cursor.next();
2259 } else {
2260 break;
2261 }
2262 }
2263 new_entries_by_path.append(cursor.suffix(), ());
2264 new_entries_by_path
2265 };
2266
2267 Some(removed_entry.path)
2268 }
2269
2270 fn update_abs_path(&mut self, abs_path: Arc<SanitizedPath>, root_name: Arc<RelPath>) {
2271 self.abs_path = abs_path;
2272 if root_name != self.root_name {
2273 self.root_char_bag = root_name
2274 .as_unix_str()
2275 .chars()
2276 .map(|c| c.to_ascii_lowercase())
2277 .collect();
2278 self.root_name = root_name;
2279 }
2280 }
2281
2282 fn apply_remote_update(
2283 &mut self,
2284 update: proto::UpdateWorktree,
2285 always_included_paths: &PathMatcher,
2286 ) {
2287 log::debug!(
2288 "applying remote worktree update. {} entries updated, {} removed",
2289 update.updated_entries.len(),
2290 update.removed_entries.len()
2291 );
2292 if let Some(root_name) = RelPath::from_proto(&update.root_name).log_err() {
2293 self.update_abs_path(
2294 SanitizedPath::new_arc(&Path::new(&update.abs_path)),
2295 root_name,
2296 );
2297 }
2298
2299 let mut entries_by_path_edits = Vec::new();
2300 let mut entries_by_id_edits = Vec::new();
2301
2302 for entry_id in update.removed_entries {
2303 let entry_id = ProjectEntryId::from_proto(entry_id);
2304 entries_by_id_edits.push(Edit::Remove(entry_id));
2305 if let Some(entry) = self.entry_for_id(entry_id) {
2306 entries_by_path_edits.push(Edit::Remove(PathKey(entry.path.clone())));
2307 }
2308 }
2309
2310 for entry in update.updated_entries {
2311 let Some(entry) =
2312 Entry::try_from((&self.root_char_bag, always_included_paths, entry)).log_err()
2313 else {
2314 continue;
2315 };
2316 if let Some(PathEntry { path, .. }) = self.entries_by_id.get(&entry.id, ()) {
2317 entries_by_path_edits.push(Edit::Remove(PathKey(path.clone())));
2318 }
2319 if let Some(old_entry) = self.entries_by_path.get(&PathKey(entry.path.clone()), ())
2320 && old_entry.id != entry.id
2321 {
2322 entries_by_id_edits.push(Edit::Remove(old_entry.id));
2323 }
2324 entries_by_id_edits.push(Edit::Insert(PathEntry {
2325 id: entry.id,
2326 path: entry.path.clone(),
2327 is_ignored: entry.is_ignored,
2328 scan_id: 0,
2329 }));
2330 entries_by_path_edits.push(Edit::Insert(entry));
2331 }
2332
2333 self.entries_by_path.edit(entries_by_path_edits, ());
2334 self.entries_by_id.edit(entries_by_id_edits, ());
2335
2336 self.scan_id = update.scan_id as usize;
2337 if update.is_last_update {
2338 self.completed_scan_id = update.scan_id as usize;
2339 }
2340 }
2341
2342 pub fn entry_count(&self) -> usize {
2343 self.entries_by_path.summary().count
2344 }
2345
2346 pub fn visible_entry_count(&self) -> usize {
2347 self.entries_by_path.summary().non_ignored_count
2348 }
2349
2350 pub fn dir_count(&self) -> usize {
2351 let summary = self.entries_by_path.summary();
2352 summary.count - summary.file_count
2353 }
2354
2355 pub fn visible_dir_count(&self) -> usize {
2356 let summary = self.entries_by_path.summary();
2357 summary.non_ignored_count - summary.non_ignored_file_count
2358 }
2359
2360 pub fn file_count(&self) -> usize {
2361 self.entries_by_path.summary().file_count
2362 }
2363
2364 pub fn visible_file_count(&self) -> usize {
2365 self.entries_by_path.summary().non_ignored_file_count
2366 }
2367
2368 fn traverse_from_offset(
2369 &self,
2370 include_files: bool,
2371 include_dirs: bool,
2372 include_ignored: bool,
2373 start_offset: usize,
2374 ) -> Traversal<'_> {
2375 let mut cursor = self.entries_by_path.cursor(());
2376 cursor.seek(
2377 &TraversalTarget::Count {
2378 count: start_offset,
2379 include_files,
2380 include_dirs,
2381 include_ignored,
2382 },
2383 Bias::Right,
2384 );
2385 Traversal {
2386 snapshot: self,
2387 cursor,
2388 include_files,
2389 include_dirs,
2390 include_ignored,
2391 }
2392 }
2393
2394 pub fn traverse_from_path(
2395 &self,
2396 include_files: bool,
2397 include_dirs: bool,
2398 include_ignored: bool,
2399 path: &RelPath,
2400 ) -> Traversal<'_> {
2401 Traversal::new(self, include_files, include_dirs, include_ignored, path)
2402 }
2403
2404 pub fn files(&self, include_ignored: bool, start: usize) -> Traversal<'_> {
2405 self.traverse_from_offset(true, false, include_ignored, start)
2406 }
2407
2408 pub fn directories(&self, include_ignored: bool, start: usize) -> Traversal<'_> {
2409 self.traverse_from_offset(false, true, include_ignored, start)
2410 }
2411
2412 pub fn entries(&self, include_ignored: bool, start: usize) -> Traversal<'_> {
2413 self.traverse_from_offset(true, true, include_ignored, start)
2414 }
2415
2416 pub fn paths(&self) -> impl Iterator<Item = &RelPath> {
2417 self.entries_by_path
2418 .cursor::<()>(())
2419 .filter(move |entry| !entry.path.is_empty())
2420 .map(|entry| entry.path.as_ref())
2421 }
2422
2423 pub fn child_entries<'a>(&'a self, parent_path: &'a RelPath) -> ChildEntriesIter<'a> {
2424 let options = ChildEntriesOptions {
2425 include_files: true,
2426 include_dirs: true,
2427 include_ignored: true,
2428 };
2429 self.child_entries_with_options(parent_path, options)
2430 }
2431
2432 pub fn child_entries_with_options<'a>(
2433 &'a self,
2434 parent_path: &'a RelPath,
2435 options: ChildEntriesOptions,
2436 ) -> ChildEntriesIter<'a> {
2437 let mut cursor = self.entries_by_path.cursor(());
2438 cursor.seek(&TraversalTarget::path(parent_path), Bias::Right);
2439 let traversal = Traversal {
2440 snapshot: self,
2441 cursor,
2442 include_files: options.include_files,
2443 include_dirs: options.include_dirs,
2444 include_ignored: options.include_ignored,
2445 };
2446 ChildEntriesIter {
2447 traversal,
2448 parent_path,
2449 }
2450 }
2451
2452 pub fn root_entry(&self) -> Option<&Entry> {
2453 self.entries_by_path.first()
2454 }
2455
2456 /// Returns `None` for a single file worktree, or `Some(self.abs_path())` if
2457 /// it is a directory.
2458 pub fn root_dir(&self) -> Option<Arc<Path>> {
2459 self.root_entry()
2460 .filter(|entry| entry.is_dir())
2461 .map(|_| self.abs_path().clone())
2462 }
2463
2464 pub fn root_name(&self) -> &RelPath {
2465 &self.root_name
2466 }
2467
2468 pub fn root_name_str(&self) -> &str {
2469 self.root_name.as_unix_str()
2470 }
2471
2472 pub fn scan_id(&self) -> usize {
2473 self.scan_id
2474 }
2475
2476 pub fn entry_for_path(&self, path: &RelPath) -> Option<&Entry> {
2477 self.traverse_from_path(true, true, true, path)
2478 .entry()
2479 .and_then(|entry| {
2480 if entry.path.as_ref() == path {
2481 Some(entry)
2482 } else {
2483 None
2484 }
2485 })
2486 }
2487
2488 /// Resolves a path to an executable using the following heuristics:
2489 ///
2490 /// 1. If the path starts with `~`, it is expanded to the user's home directory.
2491 /// 2. If the path is relative and contains more than one component,
2492 /// it is joined to the worktree root path.
2493 /// 3. If the path is relative and exists in the worktree
2494 /// (even if falls under an exclusion filter),
2495 /// it is joined to the worktree root path.
2496 /// 4. Otherwise the path is returned unmodified.
2497 ///
2498 /// Relative paths that do not exist in the worktree may
2499 /// still be found using the `PATH` environment variable.
2500 pub fn resolve_executable_path(&self, path: PathBuf) -> PathBuf {
2501 if let Some(path_str) = path.to_str() {
2502 if let Some(remaining_path) = path_str.strip_prefix("~/") {
2503 return home_dir().join(remaining_path);
2504 } else if path_str == "~" {
2505 return home_dir().to_path_buf();
2506 }
2507 }
2508
2509 if let Ok(rel_path) = RelPath::new(&path, self.path_style)
2510 && (path.components().count() > 1 || self.entry_for_path(&rel_path).is_some())
2511 {
2512 self.abs_path().join(path)
2513 } else {
2514 path
2515 }
2516 }
2517
2518 pub fn entry_for_id(&self, id: ProjectEntryId) -> Option<&Entry> {
2519 let entry = self.entries_by_id.get(&id, ())?;
2520 self.entry_for_path(&entry.path)
2521 }
2522
2523 pub fn path_style(&self) -> PathStyle {
2524 self.path_style
2525 }
2526}
2527
2528impl LocalSnapshot {
2529 fn local_repo_for_work_directory_path(&self, path: &RelPath) -> Option<&LocalRepositoryEntry> {
2530 self.git_repositories
2531 .iter()
2532 .map(|(_, entry)| entry)
2533 .find(|entry| entry.work_directory.path_key() == PathKey(path.into()))
2534 }
2535
2536 fn build_update(
2537 &self,
2538 project_id: u64,
2539 worktree_id: u64,
2540 entry_changes: UpdatedEntriesSet,
2541 ) -> proto::UpdateWorktree {
2542 let mut updated_entries = Vec::new();
2543 let mut removed_entries = Vec::new();
2544
2545 for (_, entry_id, path_change) in entry_changes.iter() {
2546 if let PathChange::Removed = path_change {
2547 removed_entries.push(entry_id.0 as u64);
2548 } else if let Some(entry) = self.entry_for_id(*entry_id) {
2549 updated_entries.push(proto::Entry::from(entry));
2550 }
2551 }
2552
2553 removed_entries.sort_unstable();
2554 updated_entries.sort_unstable_by_key(|e| e.id);
2555
2556 // TODO - optimize, knowing that removed_entries are sorted.
2557 removed_entries.retain(|id| updated_entries.binary_search_by_key(id, |e| e.id).is_err());
2558
2559 proto::UpdateWorktree {
2560 project_id,
2561 worktree_id,
2562 abs_path: self.abs_path().to_string_lossy().into_owned(),
2563 root_name: self.root_name().to_proto(),
2564 updated_entries,
2565 removed_entries,
2566 scan_id: self.scan_id as u64,
2567 is_last_update: self.completed_scan_id == self.scan_id,
2568 // Sent in separate messages.
2569 updated_repositories: Vec::new(),
2570 removed_repositories: Vec::new(),
2571 }
2572 }
2573
2574 fn insert_entry(&mut self, mut entry: Entry, fs: &dyn Fs) -> Entry {
2575 log::trace!("insert entry {:?}", entry.path);
2576 if entry.is_file() && entry.path.file_name() == Some(&GITIGNORE) {
2577 let abs_path = self.absolutize(&entry.path);
2578 match self.executor.block(build_gitignore(&abs_path, fs)) {
2579 Ok(ignore) => {
2580 self.ignores_by_parent_abs_path
2581 .insert(abs_path.parent().unwrap().into(), (Arc::new(ignore), true));
2582 }
2583 Err(error) => {
2584 log::error!(
2585 "error loading .gitignore file {:?} - {:?}",
2586 &entry.path,
2587 error
2588 );
2589 }
2590 }
2591 }
2592
2593 if entry.kind == EntryKind::PendingDir
2594 && let Some(existing_entry) = self.entries_by_path.get(&PathKey(entry.path.clone()), ())
2595 {
2596 entry.kind = existing_entry.kind;
2597 }
2598
2599 let scan_id = self.scan_id;
2600 let removed = self.entries_by_path.insert_or_replace(entry.clone(), ());
2601 if let Some(removed) = removed
2602 && removed.id != entry.id
2603 {
2604 self.entries_by_id.remove(&removed.id, ());
2605 }
2606 self.entries_by_id.insert_or_replace(
2607 PathEntry {
2608 id: entry.id,
2609 path: entry.path.clone(),
2610 is_ignored: entry.is_ignored,
2611 scan_id,
2612 },
2613 (),
2614 );
2615
2616 entry
2617 }
2618
2619 fn ancestor_inodes_for_path(&self, path: &RelPath) -> TreeSet<u64> {
2620 let mut inodes = TreeSet::default();
2621 for ancestor in path.ancestors().skip(1) {
2622 if let Some(entry) = self.entry_for_path(ancestor) {
2623 inodes.insert(entry.inode);
2624 }
2625 }
2626 inodes
2627 }
2628
2629 async fn ignore_stack_for_abs_path(
2630 &self,
2631 abs_path: &Path,
2632 is_dir: bool,
2633 fs: &dyn Fs,
2634 ) -> IgnoreStack {
2635 let mut new_ignores = Vec::new();
2636 let mut repo_root = None;
2637 for (index, ancestor) in abs_path.ancestors().enumerate() {
2638 if index > 0 {
2639 if let Some((ignore, _)) = self.ignores_by_parent_abs_path.get(ancestor) {
2640 new_ignores.push((ancestor, Some(ignore.clone())));
2641 } else {
2642 new_ignores.push((ancestor, None));
2643 }
2644 }
2645
2646 let metadata = fs.metadata(&ancestor.join(DOT_GIT)).await.ok().flatten();
2647 if metadata.is_some() {
2648 repo_root = Some(Arc::from(ancestor));
2649 break;
2650 }
2651 }
2652
2653 let mut ignore_stack = if let Some(global_gitignore) = self.global_gitignore.clone() {
2654 IgnoreStack::global(global_gitignore)
2655 } else {
2656 IgnoreStack::none()
2657 };
2658
2659 if let Some((repo_exclude, _)) = repo_root
2660 .as_ref()
2661 .and_then(|abs_path| self.repo_exclude_by_work_dir_abs_path.get(abs_path))
2662 {
2663 ignore_stack = ignore_stack.append(IgnoreKind::RepoExclude, repo_exclude.clone());
2664 }
2665 ignore_stack.repo_root = repo_root;
2666 for (parent_abs_path, ignore) in new_ignores.into_iter().rev() {
2667 if ignore_stack.is_abs_path_ignored(parent_abs_path, true) {
2668 ignore_stack = IgnoreStack::all();
2669 break;
2670 } else if let Some(ignore) = ignore {
2671 ignore_stack =
2672 ignore_stack.append(IgnoreKind::Gitignore(parent_abs_path.into()), ignore);
2673 }
2674 }
2675
2676 if ignore_stack.is_abs_path_ignored(abs_path, is_dir) {
2677 ignore_stack = IgnoreStack::all();
2678 }
2679
2680 ignore_stack
2681 }
2682
2683 #[cfg(test)]
2684 fn expanded_entries(&self) -> impl Iterator<Item = &Entry> {
2685 self.entries_by_path
2686 .cursor::<()>(())
2687 .filter(|entry| entry.kind == EntryKind::Dir && (entry.is_external || entry.is_ignored))
2688 }
2689
2690 #[cfg(test)]
2691 pub fn check_invariants(&self, git_state: bool) {
2692 use pretty_assertions::assert_eq;
2693
2694 assert_eq!(
2695 self.entries_by_path
2696 .cursor::<()>(())
2697 .map(|e| (&e.path, e.id))
2698 .collect::<Vec<_>>(),
2699 self.entries_by_id
2700 .cursor::<()>(())
2701 .map(|e| (&e.path, e.id))
2702 .collect::<collections::BTreeSet<_>>()
2703 .into_iter()
2704 .collect::<Vec<_>>(),
2705 "entries_by_path and entries_by_id are inconsistent"
2706 );
2707
2708 let mut files = self.files(true, 0);
2709 let mut visible_files = self.files(false, 0);
2710 for entry in self.entries_by_path.cursor::<()>(()) {
2711 if entry.is_file() {
2712 assert_eq!(files.next().unwrap().inode, entry.inode);
2713 if (!entry.is_ignored && !entry.is_external) || entry.is_always_included {
2714 assert_eq!(visible_files.next().unwrap().inode, entry.inode);
2715 }
2716 }
2717 }
2718
2719 assert!(files.next().is_none());
2720 assert!(visible_files.next().is_none());
2721
2722 let mut bfs_paths = Vec::new();
2723 let mut stack = self
2724 .root_entry()
2725 .map(|e| e.path.as_ref())
2726 .into_iter()
2727 .collect::<Vec<_>>();
2728 while let Some(path) = stack.pop() {
2729 bfs_paths.push(path);
2730 let ix = stack.len();
2731 for child_entry in self.child_entries(path) {
2732 stack.insert(ix, &child_entry.path);
2733 }
2734 }
2735
2736 let dfs_paths_via_iter = self
2737 .entries_by_path
2738 .cursor::<()>(())
2739 .map(|e| e.path.as_ref())
2740 .collect::<Vec<_>>();
2741 assert_eq!(bfs_paths, dfs_paths_via_iter);
2742
2743 let dfs_paths_via_traversal = self
2744 .entries(true, 0)
2745 .map(|e| e.path.as_ref())
2746 .collect::<Vec<_>>();
2747
2748 assert_eq!(dfs_paths_via_traversal, dfs_paths_via_iter);
2749
2750 if git_state {
2751 for ignore_parent_abs_path in self.ignores_by_parent_abs_path.keys() {
2752 let ignore_parent_path = &RelPath::new(
2753 ignore_parent_abs_path
2754 .strip_prefix(self.abs_path.as_path())
2755 .unwrap(),
2756 PathStyle::local(),
2757 )
2758 .unwrap();
2759 assert!(self.entry_for_path(ignore_parent_path).is_some());
2760 assert!(
2761 self.entry_for_path(
2762 &ignore_parent_path.join(RelPath::unix(GITIGNORE).unwrap())
2763 )
2764 .is_some()
2765 );
2766 }
2767 }
2768 }
2769
2770 #[cfg(test)]
2771 pub fn entries_without_ids(&self, include_ignored: bool) -> Vec<(&RelPath, u64, bool)> {
2772 let mut paths = Vec::new();
2773 for entry in self.entries_by_path.cursor::<()>(()) {
2774 if include_ignored || !entry.is_ignored {
2775 paths.push((entry.path.as_ref(), entry.inode, entry.is_ignored));
2776 }
2777 }
2778 paths.sort_by(|a, b| a.0.cmp(b.0));
2779 paths
2780 }
2781}
2782
2783impl BackgroundScannerState {
2784 fn should_scan_directory(&self, entry: &Entry) -> bool {
2785 (self.scanning_enabled && !entry.is_external && (!entry.is_ignored || entry.is_always_included))
2786 || entry.path.file_name() == Some(DOT_GIT)
2787 || entry.path.file_name() == Some(local_settings_folder_name())
2788 || entry.path.file_name() == Some(local_vscode_folder_name())
2789 || self.scanned_dirs.contains(&entry.id) // If we've ever scanned it, keep scanning
2790 || self
2791 .paths_to_scan
2792 .iter()
2793 .any(|p| p.starts_with(&entry.path))
2794 || self
2795 .path_prefixes_to_scan
2796 .iter()
2797 .any(|p| entry.path.starts_with(p))
2798 }
2799
2800 async fn enqueue_scan_dir(
2801 &self,
2802 abs_path: Arc<Path>,
2803 entry: &Entry,
2804 scan_job_tx: &Sender<ScanJob>,
2805 fs: &dyn Fs,
2806 ) {
2807 let path = entry.path.clone();
2808 let ignore_stack = self
2809 .snapshot
2810 .ignore_stack_for_abs_path(&abs_path, true, fs)
2811 .await;
2812 let mut ancestor_inodes = self.snapshot.ancestor_inodes_for_path(&path);
2813
2814 if !ancestor_inodes.contains(&entry.inode) {
2815 ancestor_inodes.insert(entry.inode);
2816 scan_job_tx
2817 .try_send(ScanJob {
2818 abs_path,
2819 path,
2820 ignore_stack,
2821 scan_queue: scan_job_tx.clone(),
2822 ancestor_inodes,
2823 is_external: entry.is_external,
2824 })
2825 .unwrap();
2826 }
2827 }
2828
2829 fn reuse_entry_id(&mut self, entry: &mut Entry) {
2830 if let Some(mtime) = entry.mtime {
2831 // If an entry with the same inode was removed from the worktree during this scan,
2832 // then it *might* represent the same file or directory. But the OS might also have
2833 // re-used the inode for a completely different file or directory.
2834 //
2835 // Conditionally reuse the old entry's id:
2836 // * if the mtime is the same, the file was probably been renamed.
2837 // * if the path is the same, the file may just have been updated
2838 if let Some(removed_entry) = self.removed_entries.remove(&entry.inode) {
2839 if removed_entry.mtime == Some(mtime) || removed_entry.path == entry.path {
2840 entry.id = removed_entry.id;
2841 }
2842 } else if let Some(existing_entry) = self.snapshot.entry_for_path(&entry.path) {
2843 entry.id = existing_entry.id;
2844 }
2845 }
2846 }
2847
2848 fn entry_id_for(
2849 &mut self,
2850 next_entry_id: &AtomicUsize,
2851 path: &RelPath,
2852 metadata: &fs::Metadata,
2853 ) -> ProjectEntryId {
2854 // If an entry with the same inode was removed from the worktree during this scan,
2855 // then it *might* represent the same file or directory. But the OS might also have
2856 // re-used the inode for a completely different file or directory.
2857 //
2858 // Conditionally reuse the old entry's id:
2859 // * if the mtime is the same, the file was probably been renamed.
2860 // * if the path is the same, the file may just have been updated
2861 if let Some(removed_entry) = self.removed_entries.remove(&metadata.inode) {
2862 if removed_entry.mtime == Some(metadata.mtime) || *removed_entry.path == *path {
2863 return removed_entry.id;
2864 }
2865 } else if let Some(existing_entry) = self.snapshot.entry_for_path(path) {
2866 return existing_entry.id;
2867 }
2868 ProjectEntryId::new(next_entry_id)
2869 }
2870
2871 async fn insert_entry(&mut self, entry: Entry, fs: &dyn Fs, watcher: &dyn Watcher) -> Entry {
2872 let entry = self.snapshot.insert_entry(entry, fs);
2873 if entry.path.file_name() == Some(&DOT_GIT) {
2874 self.insert_git_repository(entry.path.clone(), fs, watcher)
2875 .await;
2876 }
2877
2878 #[cfg(test)]
2879 self.snapshot.check_invariants(false);
2880
2881 entry
2882 }
2883
2884 fn populate_dir(
2885 &mut self,
2886 parent_path: Arc<RelPath>,
2887 entries: impl IntoIterator<Item = Entry>,
2888 ignore: Option<Arc<Gitignore>>,
2889 ) {
2890 let mut parent_entry = if let Some(parent_entry) = self
2891 .snapshot
2892 .entries_by_path
2893 .get(&PathKey(parent_path.clone()), ())
2894 {
2895 parent_entry.clone()
2896 } else {
2897 log::warn!(
2898 "populating a directory {:?} that has been removed",
2899 parent_path
2900 );
2901 return;
2902 };
2903
2904 match parent_entry.kind {
2905 EntryKind::PendingDir | EntryKind::UnloadedDir => parent_entry.kind = EntryKind::Dir,
2906 EntryKind::Dir => {}
2907 _ => return,
2908 }
2909
2910 if let Some(ignore) = ignore {
2911 let abs_parent_path = self
2912 .snapshot
2913 .abs_path
2914 .as_path()
2915 .join(parent_path.as_std_path())
2916 .into();
2917 self.snapshot
2918 .ignores_by_parent_abs_path
2919 .insert(abs_parent_path, (ignore, false));
2920 }
2921
2922 let parent_entry_id = parent_entry.id;
2923 self.scanned_dirs.insert(parent_entry_id);
2924 let mut entries_by_path_edits = vec![Edit::Insert(parent_entry)];
2925 let mut entries_by_id_edits = Vec::new();
2926
2927 for entry in entries {
2928 entries_by_id_edits.push(Edit::Insert(PathEntry {
2929 id: entry.id,
2930 path: entry.path.clone(),
2931 is_ignored: entry.is_ignored,
2932 scan_id: self.snapshot.scan_id,
2933 }));
2934 entries_by_path_edits.push(Edit::Insert(entry));
2935 }
2936
2937 self.snapshot
2938 .entries_by_path
2939 .edit(entries_by_path_edits, ());
2940 self.snapshot.entries_by_id.edit(entries_by_id_edits, ());
2941
2942 if let Err(ix) = self.changed_paths.binary_search(&parent_path) {
2943 self.changed_paths.insert(ix, parent_path.clone());
2944 }
2945
2946 #[cfg(test)]
2947 self.snapshot.check_invariants(false);
2948 }
2949
2950 fn remove_path(&mut self, path: &RelPath) {
2951 log::trace!("background scanner removing path {path:?}");
2952 let mut new_entries;
2953 let removed_entries;
2954 {
2955 let mut cursor = self
2956 .snapshot
2957 .entries_by_path
2958 .cursor::<TraversalProgress>(());
2959 new_entries = cursor.slice(&TraversalTarget::path(path), Bias::Left);
2960 removed_entries = cursor.slice(&TraversalTarget::successor(path), Bias::Left);
2961 new_entries.append(cursor.suffix(), ());
2962 }
2963 self.snapshot.entries_by_path = new_entries;
2964
2965 let mut removed_ids = Vec::with_capacity(removed_entries.summary().count);
2966 for entry in removed_entries.cursor::<()>(()) {
2967 match self.removed_entries.entry(entry.inode) {
2968 hash_map::Entry::Occupied(mut e) => {
2969 let prev_removed_entry = e.get_mut();
2970 if entry.id > prev_removed_entry.id {
2971 *prev_removed_entry = entry.clone();
2972 }
2973 }
2974 hash_map::Entry::Vacant(e) => {
2975 e.insert(entry.clone());
2976 }
2977 }
2978
2979 if entry.path.file_name() == Some(GITIGNORE) {
2980 let abs_parent_path = self.snapshot.absolutize(&entry.path.parent().unwrap());
2981 if let Some((_, needs_update)) = self
2982 .snapshot
2983 .ignores_by_parent_abs_path
2984 .get_mut(abs_parent_path.as_path())
2985 {
2986 *needs_update = true;
2987 }
2988 }
2989
2990 if let Err(ix) = removed_ids.binary_search(&entry.id) {
2991 removed_ids.insert(ix, entry.id);
2992 }
2993 }
2994
2995 self.snapshot
2996 .entries_by_id
2997 .edit(removed_ids.iter().map(|&id| Edit::Remove(id)).collect(), ());
2998 self.snapshot
2999 .git_repositories
3000 .retain(|id, _| removed_ids.binary_search(id).is_err());
3001
3002 #[cfg(test)]
3003 self.snapshot.check_invariants(false);
3004 }
3005
3006 async fn insert_git_repository(
3007 &mut self,
3008 dot_git_path: Arc<RelPath>,
3009 fs: &dyn Fs,
3010 watcher: &dyn Watcher,
3011 ) {
3012 let work_dir_path: Arc<RelPath> = match dot_git_path.parent() {
3013 Some(parent_dir) => {
3014 // Guard against repositories inside the repository metadata
3015 if parent_dir
3016 .components()
3017 .any(|component| component == DOT_GIT)
3018 {
3019 log::debug!(
3020 "not building git repository for nested `.git` directory, `.git` path in the worktree: {dot_git_path:?}"
3021 );
3022 return;
3023 };
3024
3025 parent_dir.into()
3026 }
3027 None => {
3028 // `dot_git_path.parent().is_none()` means `.git` directory is the opened worktree itself,
3029 // no files inside that directory are tracked by git, so no need to build the repo around it
3030 log::debug!(
3031 "not building git repository for the worktree itself, `.git` path in the worktree: {dot_git_path:?}"
3032 );
3033 return;
3034 }
3035 };
3036
3037 let dot_git_abs_path = Arc::from(self.snapshot.absolutize(&dot_git_path).as_ref());
3038
3039 self.insert_git_repository_for_path(
3040 WorkDirectory::InProject {
3041 relative_path: work_dir_path,
3042 },
3043 dot_git_abs_path,
3044 fs,
3045 watcher,
3046 )
3047 .await
3048 .log_err();
3049 }
3050
3051 async fn insert_git_repository_for_path(
3052 &mut self,
3053 work_directory: WorkDirectory,
3054 dot_git_abs_path: Arc<Path>,
3055 fs: &dyn Fs,
3056 watcher: &dyn Watcher,
3057 ) -> Result<LocalRepositoryEntry> {
3058 let work_dir_entry = self
3059 .snapshot
3060 .entry_for_path(&work_directory.path_key().0)
3061 .with_context(|| {
3062 format!(
3063 "working directory `{}` not indexed",
3064 work_directory
3065 .path_key()
3066 .0
3067 .display(self.snapshot.path_style)
3068 )
3069 })?;
3070 let work_directory_abs_path = self.snapshot.work_directory_abs_path(&work_directory);
3071
3072 let (repository_dir_abs_path, common_dir_abs_path) =
3073 discover_git_paths(&dot_git_abs_path, fs).await;
3074 watcher
3075 .add(&common_dir_abs_path)
3076 .context("failed to add common directory to watcher")
3077 .log_err();
3078 if !repository_dir_abs_path.starts_with(&common_dir_abs_path) {
3079 watcher
3080 .add(&repository_dir_abs_path)
3081 .context("failed to add repository directory to watcher")
3082 .log_err();
3083 }
3084
3085 let work_directory_id = work_dir_entry.id;
3086
3087 let local_repository = LocalRepositoryEntry {
3088 work_directory_id,
3089 work_directory,
3090 work_directory_abs_path: work_directory_abs_path.as_path().into(),
3091 git_dir_scan_id: 0,
3092 dot_git_abs_path,
3093 common_dir_abs_path,
3094 repository_dir_abs_path,
3095 };
3096
3097 self.snapshot
3098 .git_repositories
3099 .insert(work_directory_id, local_repository.clone());
3100
3101 log::trace!("inserting new local git repository");
3102 Ok(local_repository)
3103 }
3104}
3105
3106async fn is_git_dir(path: &Path, fs: &dyn Fs) -> bool {
3107 if let Some(file_name) = path.file_name()
3108 && file_name == DOT_GIT
3109 {
3110 return true;
3111 }
3112
3113 // If we're in a bare repository, we are not inside a `.git` folder. In a
3114 // bare repository, the root folder contains what would normally be in the
3115 // `.git` folder.
3116 let head_metadata = fs.metadata(&path.join("HEAD")).await;
3117 if !matches!(head_metadata, Ok(Some(_))) {
3118 return false;
3119 }
3120 let config_metadata = fs.metadata(&path.join("config")).await;
3121 matches!(config_metadata, Ok(Some(_)))
3122}
3123
3124async fn build_gitignore(abs_path: &Path, fs: &dyn Fs) -> Result<Gitignore> {
3125 let contents = fs
3126 .load(abs_path)
3127 .await
3128 .with_context(|| format!("failed to load gitignore file at {}", abs_path.display()))?;
3129 let parent = abs_path.parent().unwrap_or_else(|| Path::new("/"));
3130 let mut builder = GitignoreBuilder::new(parent);
3131 for line in contents.lines() {
3132 builder.add_line(Some(abs_path.into()), line)?;
3133 }
3134 Ok(builder.build()?)
3135}
3136
3137impl Deref for Worktree {
3138 type Target = Snapshot;
3139
3140 fn deref(&self) -> &Self::Target {
3141 match self {
3142 Worktree::Local(worktree) => &worktree.snapshot,
3143 Worktree::Remote(worktree) => &worktree.snapshot,
3144 }
3145 }
3146}
3147
3148impl Deref for LocalWorktree {
3149 type Target = LocalSnapshot;
3150
3151 fn deref(&self) -> &Self::Target {
3152 &self.snapshot
3153 }
3154}
3155
3156impl Deref for RemoteWorktree {
3157 type Target = Snapshot;
3158
3159 fn deref(&self) -> &Self::Target {
3160 &self.snapshot
3161 }
3162}
3163
3164impl fmt::Debug for LocalWorktree {
3165 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3166 self.snapshot.fmt(f)
3167 }
3168}
3169
3170impl fmt::Debug for Snapshot {
3171 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3172 struct EntriesById<'a>(&'a SumTree<PathEntry>);
3173 struct EntriesByPath<'a>(&'a SumTree<Entry>);
3174
3175 impl fmt::Debug for EntriesByPath<'_> {
3176 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3177 f.debug_map()
3178 .entries(self.0.iter().map(|entry| (&entry.path, entry.id)))
3179 .finish()
3180 }
3181 }
3182
3183 impl fmt::Debug for EntriesById<'_> {
3184 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3185 f.debug_list().entries(self.0.iter()).finish()
3186 }
3187 }
3188
3189 f.debug_struct("Snapshot")
3190 .field("id", &self.id)
3191 .field("root_name", &self.root_name)
3192 .field("entries_by_path", &EntriesByPath(&self.entries_by_path))
3193 .field("entries_by_id", &EntriesById(&self.entries_by_id))
3194 .finish()
3195 }
3196}
3197
3198#[derive(Debug, Clone, PartialEq)]
3199pub struct File {
3200 pub worktree: Entity<Worktree>,
3201 pub path: Arc<RelPath>,
3202 pub disk_state: DiskState,
3203 pub entry_id: Option<ProjectEntryId>,
3204 pub is_local: bool,
3205 pub is_private: bool,
3206}
3207
3208impl language::File for File {
3209 fn as_local(&self) -> Option<&dyn language::LocalFile> {
3210 if self.is_local { Some(self) } else { None }
3211 }
3212
3213 fn disk_state(&self) -> DiskState {
3214 self.disk_state
3215 }
3216
3217 fn path(&self) -> &Arc<RelPath> {
3218 &self.path
3219 }
3220
3221 fn full_path(&self, cx: &App) -> PathBuf {
3222 self.worktree.read(cx).full_path(&self.path)
3223 }
3224
3225 /// Returns the last component of this handle's absolute path. If this handle refers to the root
3226 /// of its worktree, then this method will return the name of the worktree itself.
3227 fn file_name<'a>(&'a self, cx: &'a App) -> &'a str {
3228 self.path
3229 .file_name()
3230 .unwrap_or_else(|| self.worktree.read(cx).root_name_str())
3231 }
3232
3233 fn worktree_id(&self, cx: &App) -> WorktreeId {
3234 self.worktree.read(cx).id()
3235 }
3236
3237 fn to_proto(&self, cx: &App) -> rpc::proto::File {
3238 rpc::proto::File {
3239 worktree_id: self.worktree.read(cx).id().to_proto(),
3240 entry_id: self.entry_id.map(|id| id.to_proto()),
3241 path: self.path.as_ref().to_proto(),
3242 mtime: self.disk_state.mtime().map(|time| time.into()),
3243 is_deleted: self.disk_state.is_deleted(),
3244 is_historic: matches!(self.disk_state, DiskState::Historic { .. }),
3245 }
3246 }
3247
3248 fn is_private(&self) -> bool {
3249 self.is_private
3250 }
3251
3252 fn path_style(&self, cx: &App) -> PathStyle {
3253 self.worktree.read(cx).path_style()
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
4827 {
4828 let snapshot = &mut self.state.lock().await.snapshot;
4829 let abs_path = snapshot.abs_path.clone();
4830
4831 snapshot.repo_exclude_by_work_dir_abs_path.retain(
4832 |work_dir_abs_path, (exclude, needs_update)| {
4833 if *needs_update {
4834 *needs_update = false;
4835 ignores_to_update.push(work_dir_abs_path.clone());
4836
4837 if let Some((_, repository)) = snapshot
4838 .git_repositories
4839 .iter()
4840 .find(|(_, repo)| &repo.work_directory_abs_path == work_dir_abs_path)
4841 {
4842 let exclude_abs_path =
4843 repository.common_dir_abs_path.join(REPO_EXCLUDE);
4844 if let Ok(current_exclude) = self
4845 .executor
4846 .block(build_gitignore(&exclude_abs_path, self.fs.as_ref()))
4847 {
4848 *exclude = Arc::new(current_exclude);
4849 }
4850 }
4851 }
4852
4853 snapshot
4854 .git_repositories
4855 .iter()
4856 .any(|(_, repo)| &repo.work_directory_abs_path == work_dir_abs_path)
4857 },
4858 );
4859
4860 snapshot
4861 .ignores_by_parent_abs_path
4862 .retain(|parent_abs_path, (_, needs_update)| {
4863 if let Ok(parent_path) = parent_abs_path.strip_prefix(abs_path.as_path())
4864 && let Some(parent_path) =
4865 RelPath::new(&parent_path, PathStyle::local()).log_err()
4866 {
4867 if *needs_update {
4868 *needs_update = false;
4869 if snapshot.snapshot.entry_for_path(&parent_path).is_some() {
4870 ignores_to_update.push(parent_abs_path.clone());
4871 }
4872 }
4873
4874 let ignore_path = parent_path.join(RelPath::unix(GITIGNORE).unwrap());
4875 if snapshot.snapshot.entry_for_path(&ignore_path).is_none() {
4876 return false;
4877 }
4878 }
4879 true
4880 });
4881 }
4882
4883 ignores_to_update
4884 }
4885
4886 async fn order_ignores(&self, mut ignores: Vec<Arc<Path>>) -> Vec<(Arc<Path>, IgnoreStack)> {
4887 let fs = self.fs.clone();
4888 let snapshot = self.state.lock().await.snapshot.clone();
4889 ignores.sort_unstable();
4890 let mut ignores_to_update = ignores.into_iter().peekable();
4891
4892 let mut result = vec![];
4893 while let Some(parent_abs_path) = ignores_to_update.next() {
4894 while ignores_to_update
4895 .peek()
4896 .map_or(false, |p| p.starts_with(&parent_abs_path))
4897 {
4898 ignores_to_update.next().unwrap();
4899 }
4900 let ignore_stack = snapshot
4901 .ignore_stack_for_abs_path(&parent_abs_path, true, fs.as_ref())
4902 .await;
4903 result.push((parent_abs_path, ignore_stack));
4904 }
4905
4906 result
4907 }
4908
4909 async fn update_ignore_status(&self, job: UpdateIgnoreStatusJob, snapshot: &LocalSnapshot) {
4910 log::trace!("update ignore status {:?}", job.abs_path);
4911
4912 let mut ignore_stack = job.ignore_stack;
4913 if let Some((ignore, _)) = snapshot.ignores_by_parent_abs_path.get(&job.abs_path) {
4914 ignore_stack =
4915 ignore_stack.append(IgnoreKind::Gitignore(job.abs_path.clone()), ignore.clone());
4916 }
4917
4918 let mut entries_by_id_edits = Vec::new();
4919 let mut entries_by_path_edits = Vec::new();
4920 let Some(path) = job
4921 .abs_path
4922 .strip_prefix(snapshot.abs_path.as_path())
4923 .map_err(|_| {
4924 anyhow::anyhow!(
4925 "Failed to strip prefix '{}' from path '{}'",
4926 snapshot.abs_path.as_path().display(),
4927 job.abs_path.display()
4928 )
4929 })
4930 .log_err()
4931 else {
4932 return;
4933 };
4934
4935 let Some(path) = RelPath::new(&path, PathStyle::local()).log_err() else {
4936 return;
4937 };
4938
4939 if let Ok(Some(metadata)) = self.fs.metadata(&job.abs_path.join(DOT_GIT)).await
4940 && metadata.is_dir
4941 {
4942 ignore_stack.repo_root = Some(job.abs_path.clone());
4943 }
4944
4945 for mut entry in snapshot.child_entries(&path).cloned() {
4946 let was_ignored = entry.is_ignored;
4947 let abs_path: Arc<Path> = snapshot.absolutize(&entry.path).into();
4948 entry.is_ignored = ignore_stack.is_abs_path_ignored(&abs_path, entry.is_dir());
4949
4950 if entry.is_dir() {
4951 let child_ignore_stack = if entry.is_ignored {
4952 IgnoreStack::all()
4953 } else {
4954 ignore_stack.clone()
4955 };
4956
4957 // Scan any directories that were previously ignored and weren't previously scanned.
4958 if was_ignored && !entry.is_ignored && entry.kind.is_unloaded() {
4959 let state = self.state.lock().await;
4960 if state.should_scan_directory(&entry) {
4961 state
4962 .enqueue_scan_dir(
4963 abs_path.clone(),
4964 &entry,
4965 &job.scan_queue,
4966 self.fs.as_ref(),
4967 )
4968 .await;
4969 }
4970 }
4971
4972 job.ignore_queue
4973 .send(UpdateIgnoreStatusJob {
4974 abs_path: abs_path.clone(),
4975 ignore_stack: child_ignore_stack,
4976 ignore_queue: job.ignore_queue.clone(),
4977 scan_queue: job.scan_queue.clone(),
4978 })
4979 .await
4980 .unwrap();
4981 }
4982
4983 if entry.is_ignored != was_ignored {
4984 let mut path_entry = snapshot.entries_by_id.get(&entry.id, ()).unwrap().clone();
4985 path_entry.scan_id = snapshot.scan_id;
4986 path_entry.is_ignored = entry.is_ignored;
4987 entries_by_id_edits.push(Edit::Insert(path_entry));
4988 entries_by_path_edits.push(Edit::Insert(entry));
4989 }
4990 }
4991
4992 let state = &mut self.state.lock().await;
4993 for edit in &entries_by_path_edits {
4994 if let Edit::Insert(entry) = edit
4995 && let Err(ix) = state.changed_paths.binary_search(&entry.path)
4996 {
4997 state.changed_paths.insert(ix, entry.path.clone());
4998 }
4999 }
5000
5001 state
5002 .snapshot
5003 .entries_by_path
5004 .edit(entries_by_path_edits, ());
5005 state.snapshot.entries_by_id.edit(entries_by_id_edits, ());
5006 }
5007
5008 async fn update_git_repositories(&self, dot_git_paths: Vec<PathBuf>) -> Vec<Arc<Path>> {
5009 log::trace!("reloading repositories: {dot_git_paths:?}");
5010 let mut state = self.state.lock().await;
5011 let scan_id = state.snapshot.scan_id;
5012 let mut affected_repo_roots = Vec::new();
5013 for dot_git_dir in dot_git_paths {
5014 let existing_repository_entry =
5015 state
5016 .snapshot
5017 .git_repositories
5018 .iter()
5019 .find_map(|(_, repo)| {
5020 let dot_git_dir = SanitizedPath::new(&dot_git_dir);
5021 if SanitizedPath::new(repo.common_dir_abs_path.as_ref()) == dot_git_dir
5022 || SanitizedPath::new(repo.repository_dir_abs_path.as_ref())
5023 == dot_git_dir
5024 {
5025 Some(repo.clone())
5026 } else {
5027 None
5028 }
5029 });
5030
5031 match existing_repository_entry {
5032 None => {
5033 let Ok(relative) = dot_git_dir.strip_prefix(state.snapshot.abs_path()) else {
5034 debug_panic!(
5035 "update_git_repositories called with .git directory outside the worktree root"
5036 );
5037 return Vec::new();
5038 };
5039 affected_repo_roots.push(dot_git_dir.parent().unwrap().into());
5040 state
5041 .insert_git_repository(
5042 RelPath::new(relative, PathStyle::local())
5043 .unwrap()
5044 .into_arc(),
5045 self.fs.as_ref(),
5046 self.watcher.as_ref(),
5047 )
5048 .await;
5049 }
5050 Some(local_repository) => {
5051 state.snapshot.git_repositories.update(
5052 &local_repository.work_directory_id,
5053 |entry| {
5054 entry.git_dir_scan_id = scan_id;
5055 },
5056 );
5057 }
5058 };
5059 }
5060
5061 // Remove any git repositories whose .git entry no longer exists.
5062 let snapshot = &mut state.snapshot;
5063 let mut ids_to_preserve = HashSet::default();
5064 for (&work_directory_id, entry) in snapshot.git_repositories.iter() {
5065 let exists_in_snapshot =
5066 snapshot
5067 .entry_for_id(work_directory_id)
5068 .is_some_and(|entry| {
5069 snapshot
5070 .entry_for_path(&entry.path.join(RelPath::unix(DOT_GIT).unwrap()))
5071 .is_some()
5072 });
5073
5074 if exists_in_snapshot
5075 || matches!(
5076 self.fs.metadata(&entry.common_dir_abs_path).await,
5077 Ok(Some(_))
5078 )
5079 {
5080 ids_to_preserve.insert(work_directory_id);
5081 }
5082 }
5083
5084 snapshot
5085 .git_repositories
5086 .retain(|work_directory_id, entry| {
5087 let preserve = ids_to_preserve.contains(work_directory_id);
5088 if !preserve {
5089 affected_repo_roots.push(entry.dot_git_abs_path.parent().unwrap().into());
5090 snapshot
5091 .repo_exclude_by_work_dir_abs_path
5092 .remove(&entry.work_directory_abs_path);
5093 }
5094 preserve
5095 });
5096
5097 affected_repo_roots
5098 }
5099
5100 async fn progress_timer(&self, running: bool) {
5101 if !running {
5102 return futures::future::pending().await;
5103 }
5104
5105 #[cfg(any(test, feature = "test-support"))]
5106 if self.fs.is_fake() {
5107 return self.executor.simulate_random_delay().await;
5108 }
5109
5110 smol::Timer::after(FS_WATCH_LATENCY).await;
5111 }
5112
5113 fn is_path_private(&self, path: &RelPath) -> bool {
5114 !self.share_private_files && self.settings.is_path_private(path)
5115 }
5116
5117 async fn next_scan_request(&self) -> Result<ScanRequest> {
5118 let mut request = self.scan_requests_rx.recv().await?;
5119 while let Ok(next_request) = self.scan_requests_rx.try_recv() {
5120 request.relative_paths.extend(next_request.relative_paths);
5121 request.done.extend(next_request.done);
5122 }
5123 Ok(request)
5124 }
5125}
5126
5127async fn discover_ancestor_git_repo(
5128 fs: Arc<dyn Fs>,
5129 root_abs_path: &SanitizedPath,
5130) -> (
5131 HashMap<Arc<Path>, (Arc<Gitignore>, bool)>,
5132 Option<Arc<Gitignore>>,
5133 Option<(PathBuf, WorkDirectory)>,
5134) {
5135 let mut exclude = None;
5136 let mut ignores = HashMap::default();
5137 for (index, ancestor) in root_abs_path.as_path().ancestors().enumerate() {
5138 if index != 0 {
5139 if ancestor == paths::home_dir() {
5140 // Unless $HOME is itself the worktree root, don't consider it as a
5141 // containing git repository---expensive and likely unwanted.
5142 break;
5143 } else if let Ok(ignore) = build_gitignore(&ancestor.join(GITIGNORE), fs.as_ref()).await
5144 {
5145 ignores.insert(ancestor.into(), (ignore.into(), false));
5146 }
5147 }
5148
5149 let ancestor_dot_git = ancestor.join(DOT_GIT);
5150 log::trace!("considering ancestor: {ancestor_dot_git:?}");
5151 // Check whether the directory or file called `.git` exists (in the
5152 // case of worktrees it's a file.)
5153 if fs
5154 .metadata(&ancestor_dot_git)
5155 .await
5156 .is_ok_and(|metadata| metadata.is_some())
5157 {
5158 if index != 0 {
5159 // We canonicalize, since the FS events use the canonicalized path.
5160 if let Some(ancestor_dot_git) = fs.canonicalize(&ancestor_dot_git).await.log_err() {
5161 let location_in_repo = root_abs_path
5162 .as_path()
5163 .strip_prefix(ancestor)
5164 .unwrap()
5165 .into();
5166 log::info!("inserting parent git repo for this worktree: {location_in_repo:?}");
5167 // We associate the external git repo with our root folder and
5168 // also mark where in the git repo the root folder is located.
5169 return (
5170 ignores,
5171 exclude,
5172 Some((
5173 ancestor_dot_git,
5174 WorkDirectory::AboveProject {
5175 absolute_path: ancestor.into(),
5176 location_in_repo,
5177 },
5178 )),
5179 );
5180 };
5181 }
5182
5183 let repo_exclude_abs_path = ancestor_dot_git.join(REPO_EXCLUDE);
5184 if let Ok(repo_exclude) = build_gitignore(&repo_exclude_abs_path, fs.as_ref()).await {
5185 exclude = Some(Arc::new(repo_exclude));
5186 }
5187
5188 // Reached root of git repository.
5189 break;
5190 }
5191 }
5192
5193 (ignores, exclude, None)
5194}
5195
5196fn build_diff(
5197 phase: BackgroundScannerPhase,
5198 old_snapshot: &Snapshot,
5199 new_snapshot: &Snapshot,
5200 event_paths: &[Arc<RelPath>],
5201) -> UpdatedEntriesSet {
5202 use BackgroundScannerPhase::*;
5203 use PathChange::{Added, AddedOrUpdated, Loaded, Removed, Updated};
5204
5205 // Identify which paths have changed. Use the known set of changed
5206 // parent paths to optimize the search.
5207 let mut changes = Vec::new();
5208 let mut old_paths = old_snapshot.entries_by_path.cursor::<PathKey>(());
5209 let mut new_paths = new_snapshot.entries_by_path.cursor::<PathKey>(());
5210 let mut last_newly_loaded_dir_path = None;
5211 old_paths.next();
5212 new_paths.next();
5213 for path in event_paths {
5214 let path = PathKey(path.clone());
5215 if old_paths.item().is_some_and(|e| e.path < path.0) {
5216 old_paths.seek_forward(&path, Bias::Left);
5217 }
5218 if new_paths.item().is_some_and(|e| e.path < path.0) {
5219 new_paths.seek_forward(&path, Bias::Left);
5220 }
5221 loop {
5222 match (old_paths.item(), new_paths.item()) {
5223 (Some(old_entry), Some(new_entry)) => {
5224 if old_entry.path > path.0
5225 && new_entry.path > path.0
5226 && !old_entry.path.starts_with(&path.0)
5227 && !new_entry.path.starts_with(&path.0)
5228 {
5229 break;
5230 }
5231
5232 match Ord::cmp(&old_entry.path, &new_entry.path) {
5233 Ordering::Less => {
5234 changes.push((old_entry.path.clone(), old_entry.id, Removed));
5235 old_paths.next();
5236 }
5237 Ordering::Equal => {
5238 if phase == EventsReceivedDuringInitialScan {
5239 if old_entry.id != new_entry.id {
5240 changes.push((old_entry.path.clone(), old_entry.id, Removed));
5241 }
5242 // If the worktree was not fully initialized when this event was generated,
5243 // we can't know whether this entry was added during the scan or whether
5244 // it was merely updated.
5245 changes.push((
5246 new_entry.path.clone(),
5247 new_entry.id,
5248 AddedOrUpdated,
5249 ));
5250 } else if old_entry.id != new_entry.id {
5251 changes.push((old_entry.path.clone(), old_entry.id, Removed));
5252 changes.push((new_entry.path.clone(), new_entry.id, Added));
5253 } else if old_entry != new_entry {
5254 if old_entry.kind.is_unloaded() {
5255 last_newly_loaded_dir_path = Some(&new_entry.path);
5256 changes.push((new_entry.path.clone(), new_entry.id, Loaded));
5257 } else {
5258 changes.push((new_entry.path.clone(), new_entry.id, Updated));
5259 }
5260 }
5261 old_paths.next();
5262 new_paths.next();
5263 }
5264 Ordering::Greater => {
5265 let is_newly_loaded = phase == InitialScan
5266 || last_newly_loaded_dir_path
5267 .as_ref()
5268 .is_some_and(|dir| new_entry.path.starts_with(dir));
5269 changes.push((
5270 new_entry.path.clone(),
5271 new_entry.id,
5272 if is_newly_loaded { Loaded } else { Added },
5273 ));
5274 new_paths.next();
5275 }
5276 }
5277 }
5278 (Some(old_entry), None) => {
5279 changes.push((old_entry.path.clone(), old_entry.id, Removed));
5280 old_paths.next();
5281 }
5282 (None, Some(new_entry)) => {
5283 let is_newly_loaded = phase == InitialScan
5284 || last_newly_loaded_dir_path
5285 .as_ref()
5286 .is_some_and(|dir| new_entry.path.starts_with(dir));
5287 changes.push((
5288 new_entry.path.clone(),
5289 new_entry.id,
5290 if is_newly_loaded { Loaded } else { Added },
5291 ));
5292 new_paths.next();
5293 }
5294 (None, None) => break,
5295 }
5296 }
5297 }
5298
5299 changes.into()
5300}
5301
5302fn swap_to_front(child_paths: &mut Vec<PathBuf>, file: &str) {
5303 let position = child_paths
5304 .iter()
5305 .position(|path| path.file_name().unwrap() == file);
5306 if let Some(position) = position {
5307 let temp = child_paths.remove(position);
5308 child_paths.insert(0, temp);
5309 }
5310}
5311
5312fn char_bag_for_path(root_char_bag: CharBag, path: &RelPath) -> CharBag {
5313 let mut result = root_char_bag;
5314 result.extend(path.as_unix_str().chars().map(|c| c.to_ascii_lowercase()));
5315 result
5316}
5317
5318#[derive(Debug)]
5319struct ScanJob {
5320 abs_path: Arc<Path>,
5321 path: Arc<RelPath>,
5322 ignore_stack: IgnoreStack,
5323 scan_queue: Sender<ScanJob>,
5324 ancestor_inodes: TreeSet<u64>,
5325 is_external: bool,
5326}
5327
5328struct UpdateIgnoreStatusJob {
5329 abs_path: Arc<Path>,
5330 ignore_stack: IgnoreStack,
5331 ignore_queue: Sender<UpdateIgnoreStatusJob>,
5332 scan_queue: Sender<ScanJob>,
5333}
5334
5335pub trait WorktreeModelHandle {
5336 #[cfg(any(test, feature = "test-support"))]
5337 fn flush_fs_events<'a>(
5338 &self,
5339 cx: &'a mut gpui::TestAppContext,
5340 ) -> futures::future::LocalBoxFuture<'a, ()>;
5341
5342 #[cfg(any(test, feature = "test-support"))]
5343 fn flush_fs_events_in_root_git_repository<'a>(
5344 &self,
5345 cx: &'a mut gpui::TestAppContext,
5346 ) -> futures::future::LocalBoxFuture<'a, ()>;
5347}
5348
5349impl WorktreeModelHandle for Entity<Worktree> {
5350 // When the worktree's FS event stream sometimes delivers "redundant" events for FS changes that
5351 // occurred before the worktree was constructed. These events can cause the worktree to perform
5352 // extra directory scans, and emit extra scan-state notifications.
5353 //
5354 // This function mutates the worktree's directory and waits for those mutations to be picked up,
5355 // to ensure that all redundant FS events have already been processed.
5356 #[cfg(any(test, feature = "test-support"))]
5357 fn flush_fs_events<'a>(
5358 &self,
5359 cx: &'a mut gpui::TestAppContext,
5360 ) -> futures::future::LocalBoxFuture<'a, ()> {
5361 let file_name = "fs-event-sentinel";
5362
5363 let tree = self.clone();
5364 let (fs, root_path) = self.read_with(cx, |tree, _| {
5365 let tree = tree.as_local().unwrap();
5366 (tree.fs.clone(), tree.abs_path.clone())
5367 });
5368
5369 async move {
5370 fs.create_file(&root_path.join(file_name), Default::default())
5371 .await
5372 .unwrap();
5373
5374 let mut events = cx.events(&tree);
5375 while events.next().await.is_some() {
5376 if tree.read_with(cx, |tree, _| {
5377 tree.entry_for_path(RelPath::unix(file_name).unwrap())
5378 .is_some()
5379 }) {
5380 break;
5381 }
5382 }
5383
5384 fs.remove_file(&root_path.join(file_name), Default::default())
5385 .await
5386 .unwrap();
5387 while events.next().await.is_some() {
5388 if tree.read_with(cx, |tree, _| {
5389 tree.entry_for_path(RelPath::unix(file_name).unwrap())
5390 .is_none()
5391 }) {
5392 break;
5393 }
5394 }
5395
5396 cx.update(|cx| tree.read(cx).as_local().unwrap().scan_complete())
5397 .await;
5398 }
5399 .boxed_local()
5400 }
5401
5402 // This function is similar to flush_fs_events, except that it waits for events to be flushed in
5403 // the .git folder of the root repository.
5404 // The reason for its existence is that a repository's .git folder might live *outside* of the
5405 // worktree and thus its FS events might go through a different path.
5406 // In order to flush those, we need to create artificial events in the .git folder and wait
5407 // for the repository to be reloaded.
5408 #[cfg(any(test, feature = "test-support"))]
5409 fn flush_fs_events_in_root_git_repository<'a>(
5410 &self,
5411 cx: &'a mut gpui::TestAppContext,
5412 ) -> futures::future::LocalBoxFuture<'a, ()> {
5413 let file_name = "fs-event-sentinel";
5414
5415 let tree = self.clone();
5416 let (fs, root_path, mut git_dir_scan_id) = self.read_with(cx, |tree, _| {
5417 let tree = tree.as_local().unwrap();
5418 let local_repo_entry = tree
5419 .git_repositories
5420 .values()
5421 .min_by_key(|local_repo_entry| local_repo_entry.work_directory.clone())
5422 .unwrap();
5423 (
5424 tree.fs.clone(),
5425 local_repo_entry.common_dir_abs_path.clone(),
5426 local_repo_entry.git_dir_scan_id,
5427 )
5428 });
5429
5430 let scan_id_increased = |tree: &mut Worktree, git_dir_scan_id: &mut usize| {
5431 let tree = tree.as_local().unwrap();
5432 // let repository = tree.repositories.first().unwrap();
5433 let local_repo_entry = tree
5434 .git_repositories
5435 .values()
5436 .min_by_key(|local_repo_entry| local_repo_entry.work_directory.clone())
5437 .unwrap();
5438
5439 if local_repo_entry.git_dir_scan_id > *git_dir_scan_id {
5440 *git_dir_scan_id = local_repo_entry.git_dir_scan_id;
5441 true
5442 } else {
5443 false
5444 }
5445 };
5446
5447 async move {
5448 fs.create_file(&root_path.join(file_name), Default::default())
5449 .await
5450 .unwrap();
5451
5452 let mut events = cx.events(&tree);
5453 while events.next().await.is_some() {
5454 if tree.update(cx, |tree, _| scan_id_increased(tree, &mut git_dir_scan_id)) {
5455 break;
5456 }
5457 }
5458
5459 fs.remove_file(&root_path.join(file_name), Default::default())
5460 .await
5461 .unwrap();
5462
5463 while events.next().await.is_some() {
5464 if tree.update(cx, |tree, _| scan_id_increased(tree, &mut git_dir_scan_id)) {
5465 break;
5466 }
5467 }
5468
5469 cx.update(|cx| tree.read(cx).as_local().unwrap().scan_complete())
5470 .await;
5471 }
5472 .boxed_local()
5473 }
5474}
5475
5476#[derive(Clone, Debug)]
5477struct TraversalProgress<'a> {
5478 max_path: &'a RelPath,
5479 count: usize,
5480 non_ignored_count: usize,
5481 file_count: usize,
5482 non_ignored_file_count: usize,
5483}
5484
5485impl TraversalProgress<'_> {
5486 fn count(&self, include_files: bool, include_dirs: bool, include_ignored: bool) -> usize {
5487 match (include_files, include_dirs, include_ignored) {
5488 (true, true, true) => self.count,
5489 (true, true, false) => self.non_ignored_count,
5490 (true, false, true) => self.file_count,
5491 (true, false, false) => self.non_ignored_file_count,
5492 (false, true, true) => self.count - self.file_count,
5493 (false, true, false) => self.non_ignored_count - self.non_ignored_file_count,
5494 (false, false, _) => 0,
5495 }
5496 }
5497}
5498
5499impl<'a> sum_tree::Dimension<'a, EntrySummary> for TraversalProgress<'a> {
5500 fn zero(_cx: ()) -> Self {
5501 Default::default()
5502 }
5503
5504 fn add_summary(&mut self, summary: &'a EntrySummary, _: ()) {
5505 self.max_path = summary.max_path.as_ref();
5506 self.count += summary.count;
5507 self.non_ignored_count += summary.non_ignored_count;
5508 self.file_count += summary.file_count;
5509 self.non_ignored_file_count += summary.non_ignored_file_count;
5510 }
5511}
5512
5513impl Default for TraversalProgress<'_> {
5514 fn default() -> Self {
5515 Self {
5516 max_path: RelPath::empty(),
5517 count: 0,
5518 non_ignored_count: 0,
5519 file_count: 0,
5520 non_ignored_file_count: 0,
5521 }
5522 }
5523}
5524
5525#[derive(Debug)]
5526pub struct Traversal<'a> {
5527 snapshot: &'a Snapshot,
5528 cursor: sum_tree::Cursor<'a, 'static, Entry, TraversalProgress<'a>>,
5529 include_ignored: bool,
5530 include_files: bool,
5531 include_dirs: bool,
5532}
5533
5534impl<'a> Traversal<'a> {
5535 fn new(
5536 snapshot: &'a Snapshot,
5537 include_files: bool,
5538 include_dirs: bool,
5539 include_ignored: bool,
5540 start_path: &RelPath,
5541 ) -> Self {
5542 let mut cursor = snapshot.entries_by_path.cursor(());
5543 cursor.seek(&TraversalTarget::path(start_path), Bias::Left);
5544 let mut traversal = Self {
5545 snapshot,
5546 cursor,
5547 include_files,
5548 include_dirs,
5549 include_ignored,
5550 };
5551 if traversal.end_offset() == traversal.start_offset() {
5552 traversal.next();
5553 }
5554 traversal
5555 }
5556
5557 pub fn advance(&mut self) -> bool {
5558 self.advance_by(1)
5559 }
5560
5561 pub fn advance_by(&mut self, count: usize) -> bool {
5562 self.cursor.seek_forward(
5563 &TraversalTarget::Count {
5564 count: self.end_offset() + count,
5565 include_dirs: self.include_dirs,
5566 include_files: self.include_files,
5567 include_ignored: self.include_ignored,
5568 },
5569 Bias::Left,
5570 )
5571 }
5572
5573 pub fn advance_to_sibling(&mut self) -> bool {
5574 while let Some(entry) = self.cursor.item() {
5575 self.cursor
5576 .seek_forward(&TraversalTarget::successor(&entry.path), Bias::Left);
5577 if let Some(entry) = self.cursor.item()
5578 && (self.include_files || !entry.is_file())
5579 && (self.include_dirs || !entry.is_dir())
5580 && (self.include_ignored || !entry.is_ignored || entry.is_always_included)
5581 {
5582 return true;
5583 }
5584 }
5585 false
5586 }
5587
5588 pub fn back_to_parent(&mut self) -> bool {
5589 let Some(parent_path) = self.cursor.item().and_then(|entry| entry.path.parent()) else {
5590 return false;
5591 };
5592 self.cursor
5593 .seek(&TraversalTarget::path(parent_path), Bias::Left)
5594 }
5595
5596 pub fn entry(&self) -> Option<&'a Entry> {
5597 self.cursor.item()
5598 }
5599
5600 pub fn snapshot(&self) -> &'a Snapshot {
5601 self.snapshot
5602 }
5603
5604 pub fn start_offset(&self) -> usize {
5605 self.cursor
5606 .start()
5607 .count(self.include_files, self.include_dirs, self.include_ignored)
5608 }
5609
5610 pub fn end_offset(&self) -> usize {
5611 self.cursor
5612 .end()
5613 .count(self.include_files, self.include_dirs, self.include_ignored)
5614 }
5615}
5616
5617impl<'a> Iterator for Traversal<'a> {
5618 type Item = &'a Entry;
5619
5620 fn next(&mut self) -> Option<Self::Item> {
5621 if let Some(item) = self.entry() {
5622 self.advance();
5623 Some(item)
5624 } else {
5625 None
5626 }
5627 }
5628}
5629
5630#[derive(Debug, Clone, Copy)]
5631pub enum PathTarget<'a> {
5632 Path(&'a RelPath),
5633 Successor(&'a RelPath),
5634}
5635
5636impl PathTarget<'_> {
5637 fn cmp_path(&self, other: &RelPath) -> Ordering {
5638 match self {
5639 PathTarget::Path(path) => path.cmp(&other),
5640 PathTarget::Successor(path) => {
5641 if other.starts_with(path) {
5642 Ordering::Greater
5643 } else {
5644 Ordering::Equal
5645 }
5646 }
5647 }
5648 }
5649}
5650
5651impl<'a, S: Summary> SeekTarget<'a, PathSummary<S>, PathProgress<'a>> for PathTarget<'_> {
5652 fn cmp(&self, cursor_location: &PathProgress<'a>, _: S::Context<'_>) -> Ordering {
5653 self.cmp_path(cursor_location.max_path)
5654 }
5655}
5656
5657impl<'a, S: Summary> SeekTarget<'a, PathSummary<S>, TraversalProgress<'a>> for PathTarget<'_> {
5658 fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: S::Context<'_>) -> Ordering {
5659 self.cmp_path(cursor_location.max_path)
5660 }
5661}
5662
5663#[derive(Debug)]
5664enum TraversalTarget<'a> {
5665 Path(PathTarget<'a>),
5666 Count {
5667 count: usize,
5668 include_files: bool,
5669 include_ignored: bool,
5670 include_dirs: bool,
5671 },
5672}
5673
5674impl<'a> TraversalTarget<'a> {
5675 fn path(path: &'a RelPath) -> Self {
5676 Self::Path(PathTarget::Path(path))
5677 }
5678
5679 fn successor(path: &'a RelPath) -> Self {
5680 Self::Path(PathTarget::Successor(path))
5681 }
5682
5683 fn cmp_progress(&self, progress: &TraversalProgress) -> Ordering {
5684 match self {
5685 TraversalTarget::Path(path) => path.cmp_path(progress.max_path),
5686 TraversalTarget::Count {
5687 count,
5688 include_files,
5689 include_dirs,
5690 include_ignored,
5691 } => Ord::cmp(
5692 count,
5693 &progress.count(*include_files, *include_dirs, *include_ignored),
5694 ),
5695 }
5696 }
5697}
5698
5699impl<'a> SeekTarget<'a, EntrySummary, TraversalProgress<'a>> for TraversalTarget<'_> {
5700 fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: ()) -> Ordering {
5701 self.cmp_progress(cursor_location)
5702 }
5703}
5704
5705impl<'a> SeekTarget<'a, PathSummary<sum_tree::NoSummary>, TraversalProgress<'a>>
5706 for TraversalTarget<'_>
5707{
5708 fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: ()) -> Ordering {
5709 self.cmp_progress(cursor_location)
5710 }
5711}
5712
5713pub struct ChildEntriesOptions {
5714 pub include_files: bool,
5715 pub include_dirs: bool,
5716 pub include_ignored: bool,
5717}
5718
5719pub struct ChildEntriesIter<'a> {
5720 parent_path: &'a RelPath,
5721 traversal: Traversal<'a>,
5722}
5723
5724impl<'a> Iterator for ChildEntriesIter<'a> {
5725 type Item = &'a Entry;
5726
5727 fn next(&mut self) -> Option<Self::Item> {
5728 if let Some(item) = self.traversal.entry()
5729 && item.path.starts_with(self.parent_path)
5730 {
5731 self.traversal.advance_to_sibling();
5732 return Some(item);
5733 }
5734 None
5735 }
5736}
5737
5738impl<'a> From<&'a Entry> for proto::Entry {
5739 fn from(entry: &'a Entry) -> Self {
5740 Self {
5741 id: entry.id.to_proto(),
5742 is_dir: entry.is_dir(),
5743 path: entry.path.as_ref().to_proto(),
5744 inode: entry.inode,
5745 mtime: entry.mtime.map(|time| time.into()),
5746 is_ignored: entry.is_ignored,
5747 is_hidden: entry.is_hidden,
5748 is_external: entry.is_external,
5749 is_fifo: entry.is_fifo,
5750 size: Some(entry.size),
5751 canonical_path: entry
5752 .canonical_path
5753 .as_ref()
5754 .map(|path| path.to_string_lossy().into_owned()),
5755 }
5756 }
5757}
5758
5759impl TryFrom<(&CharBag, &PathMatcher, proto::Entry)> for Entry {
5760 type Error = anyhow::Error;
5761
5762 fn try_from(
5763 (root_char_bag, always_included, entry): (&CharBag, &PathMatcher, proto::Entry),
5764 ) -> Result<Self> {
5765 let kind = if entry.is_dir {
5766 EntryKind::Dir
5767 } else {
5768 EntryKind::File
5769 };
5770
5771 let path =
5772 RelPath::from_proto(&entry.path).context("invalid relative path in proto message")?;
5773 let char_bag = char_bag_for_path(*root_char_bag, &path);
5774 let is_always_included = always_included.is_match(&path);
5775 Ok(Entry {
5776 id: ProjectEntryId::from_proto(entry.id),
5777 kind,
5778 path,
5779 inode: entry.inode,
5780 mtime: entry.mtime.map(|time| time.into()),
5781 size: entry.size.unwrap_or(0),
5782 canonical_path: entry
5783 .canonical_path
5784 .map(|path_string| Arc::from(PathBuf::from(path_string))),
5785 is_ignored: entry.is_ignored,
5786 is_hidden: entry.is_hidden,
5787 is_always_included,
5788 is_external: entry.is_external,
5789 is_private: false,
5790 char_bag,
5791 is_fifo: entry.is_fifo,
5792 })
5793 }
5794}
5795
5796#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
5797pub struct ProjectEntryId(usize);
5798
5799impl ProjectEntryId {
5800 pub const MAX: Self = Self(usize::MAX);
5801 pub const MIN: Self = Self(usize::MIN);
5802
5803 pub fn new(counter: &AtomicUsize) -> Self {
5804 Self(counter.fetch_add(1, SeqCst))
5805 }
5806
5807 pub fn from_proto(id: u64) -> Self {
5808 Self(id as usize)
5809 }
5810
5811 pub fn to_proto(self) -> u64 {
5812 self.0 as u64
5813 }
5814
5815 pub fn from_usize(id: usize) -> Self {
5816 ProjectEntryId(id)
5817 }
5818
5819 pub fn to_usize(self) -> usize {
5820 self.0
5821 }
5822}
5823
5824#[cfg(any(test, feature = "test-support"))]
5825impl CreatedEntry {
5826 pub fn into_included(self) -> Option<Entry> {
5827 match self {
5828 CreatedEntry::Included(entry) => Some(entry),
5829 CreatedEntry::Excluded { .. } => None,
5830 }
5831 }
5832}
5833
5834fn parse_gitfile(content: &str) -> anyhow::Result<&Path> {
5835 let path = content
5836 .strip_prefix("gitdir:")
5837 .with_context(|| format!("parsing gitfile content {content:?}"))?;
5838 Ok(Path::new(path.trim()))
5839}
5840
5841async fn discover_git_paths(dot_git_abs_path: &Arc<Path>, fs: &dyn Fs) -> (Arc<Path>, Arc<Path>) {
5842 let mut repository_dir_abs_path = dot_git_abs_path.clone();
5843 let mut common_dir_abs_path = dot_git_abs_path.clone();
5844
5845 if let Some(path) = fs
5846 .load(dot_git_abs_path)
5847 .await
5848 .ok()
5849 .as_ref()
5850 .and_then(|contents| parse_gitfile(contents).log_err())
5851 {
5852 let path = dot_git_abs_path
5853 .parent()
5854 .unwrap_or(Path::new(""))
5855 .join(path);
5856 if let Some(path) = fs.canonicalize(&path).await.log_err() {
5857 repository_dir_abs_path = Path::new(&path).into();
5858 common_dir_abs_path = repository_dir_abs_path.clone();
5859
5860 if let Some(commondir_contents) = fs.load(&path.join("commondir")).await.ok()
5861 && let Some(commondir_path) = fs
5862 .canonicalize(&path.join(commondir_contents.trim()))
5863 .await
5864 .log_err()
5865 {
5866 common_dir_abs_path = commondir_path.as_path().into();
5867 }
5868 }
5869 };
5870 (repository_dir_abs_path, common_dir_abs_path)
5871}
5872
5873struct NullWatcher;
5874
5875impl fs::Watcher for NullWatcher {
5876 fn add(&self, _path: &Path) -> Result<()> {
5877 Ok(())
5878 }
5879
5880 fn remove(&self, _path: &Path) -> Result<()> {
5881 Ok(())
5882 }
5883}
5884
5885const FILE_ANALYSIS_BYTES: usize = 1024;
5886
5887async fn decode_file_text(
5888 fs: &dyn Fs,
5889 abs_path: &Path,
5890) -> Result<(String, &'static Encoding, bool)> {
5891 let mut file = fs
5892 .open_sync(&abs_path)
5893 .await
5894 .with_context(|| format!("opening file {abs_path:?}"))?;
5895
5896 // First, read the beginning of the file to determine its kind and encoding.
5897 // We do not want to load an entire large blob into memory only to discard it.
5898 let mut file_first_bytes = Vec::with_capacity(FILE_ANALYSIS_BYTES);
5899 let mut buf = [0u8; FILE_ANALYSIS_BYTES];
5900 let mut reached_eof = false;
5901 loop {
5902 if file_first_bytes.len() >= FILE_ANALYSIS_BYTES {
5903 break;
5904 }
5905 let n = file
5906 .read(&mut buf)
5907 .with_context(|| format!("reading bytes of the file {abs_path:?}"))?;
5908 if n == 0 {
5909 reached_eof = true;
5910 break;
5911 }
5912 file_first_bytes.extend_from_slice(&buf[..n]);
5913 }
5914 let (bom_encoding, byte_content) = decode_byte_header(&file_first_bytes);
5915 anyhow::ensure!(
5916 byte_content != ByteContent::Binary,
5917 "Binary files are not supported"
5918 );
5919
5920 // If the file is eligible for opening, read the rest of the file.
5921 let mut content = file_first_bytes;
5922 if !reached_eof {
5923 let mut buf = [0u8; 8 * 1024];
5924 loop {
5925 let n = file
5926 .read(&mut buf)
5927 .with_context(|| format!("reading remaining bytes of the file {abs_path:?}"))?;
5928 if n == 0 {
5929 break;
5930 }
5931 content.extend_from_slice(&buf[..n]);
5932 }
5933 }
5934 decode_byte_full(content, bom_encoding, byte_content)
5935}
5936
5937fn decode_byte_header(prefix: &[u8]) -> (Option<&'static Encoding>, ByteContent) {
5938 if let Some((encoding, _bom_len)) = Encoding::for_bom(prefix) {
5939 return (Some(encoding), ByteContent::Unknown);
5940 }
5941 (None, analyze_byte_content(prefix))
5942}
5943
5944fn decode_byte_full(
5945 bytes: Vec<u8>,
5946 bom_encoding: Option<&'static Encoding>,
5947 byte_content: ByteContent,
5948) -> Result<(String, &'static Encoding, bool)> {
5949 if let Some(encoding) = bom_encoding {
5950 let (cow, _) = encoding.decode_with_bom_removal(&bytes);
5951 return Ok((cow.into_owned(), encoding, true));
5952 }
5953
5954 match byte_content {
5955 ByteContent::Utf16Le => {
5956 let encoding = encoding_rs::UTF_16LE;
5957 let (cow, _, _) = encoding.decode(&bytes);
5958 return Ok((cow.into_owned(), encoding, false));
5959 }
5960 ByteContent::Utf16Be => {
5961 let encoding = encoding_rs::UTF_16BE;
5962 let (cow, _, _) = encoding.decode(&bytes);
5963 return Ok((cow.into_owned(), encoding, false));
5964 }
5965 ByteContent::Binary => {
5966 anyhow::bail!("Binary files are not supported");
5967 }
5968 ByteContent::Unknown => {}
5969 }
5970
5971 fn detect_encoding(bytes: Vec<u8>) -> (String, &'static Encoding) {
5972 let mut detector = EncodingDetector::new();
5973 detector.feed(&bytes, true);
5974
5975 let encoding = detector.guess(None, true); // Use None for TLD hint to ensure neutral detection logic.
5976
5977 let (cow, _, _) = encoding.decode(&bytes);
5978 (cow.into_owned(), encoding)
5979 }
5980
5981 match String::from_utf8(bytes) {
5982 Ok(text) => {
5983 // ISO-2022-JP (and other ISO-2022 variants) consists entirely of 7-bit ASCII bytes,
5984 // so it is valid UTF-8. However, it contains escape sequences starting with '\x1b'.
5985 // If we find an escape character, we double-check the encoding to prevent
5986 // displaying raw escape sequences instead of the correct characters.
5987 if text.contains('\x1b') {
5988 let (s, enc) = detect_encoding(text.into_bytes());
5989 Ok((s, enc, false))
5990 } else {
5991 Ok((text, encoding_rs::UTF_8, false))
5992 }
5993 }
5994 Err(e) => {
5995 let (s, enc) = detect_encoding(e.into_bytes());
5996 Ok((s, enc, false))
5997 }
5998 }
5999}
6000
6001#[derive(PartialEq)]
6002enum ByteContent {
6003 Utf16Le,
6004 Utf16Be,
6005 Binary,
6006 Unknown,
6007}
6008
6009// Heuristic check using null byte distribution plus a generic text-likeness
6010// heuristic. This prefers UTF-16 when many bytes are NUL and otherwise
6011// distinguishes between text-like and binary-like content.
6012fn analyze_byte_content(bytes: &[u8]) -> ByteContent {
6013 if bytes.len() < 2 {
6014 return ByteContent::Unknown;
6015 }
6016
6017 if is_known_binary_header(bytes) {
6018 return ByteContent::Binary;
6019 }
6020
6021 let limit = bytes.len().min(FILE_ANALYSIS_BYTES);
6022 let mut even_null_count = 0usize;
6023 let mut odd_null_count = 0usize;
6024 let mut non_text_like_count = 0usize;
6025
6026 for (i, &byte) in bytes[..limit].iter().enumerate() {
6027 if byte == 0 {
6028 if i % 2 == 0 {
6029 even_null_count += 1;
6030 } else {
6031 odd_null_count += 1;
6032 }
6033 non_text_like_count += 1;
6034 continue;
6035 }
6036
6037 let is_text_like = match byte {
6038 b'\t' | b'\n' | b'\r' | 0x0C => true,
6039 0x20..=0x7E => true,
6040 // Treat bytes that are likely part of UTF-8 or single-byte encodings as text-like.
6041 0x80..=0xBF | 0xC2..=0xF4 => true,
6042 _ => false,
6043 };
6044
6045 if !is_text_like {
6046 non_text_like_count += 1;
6047 }
6048 }
6049
6050 let total_null_count = even_null_count + odd_null_count;
6051
6052 // If there are no NUL bytes at all, this is overwhelmingly likely to be text.
6053 if total_null_count == 0 {
6054 return ByteContent::Unknown;
6055 }
6056
6057 if total_null_count >= limit / 16 {
6058 if even_null_count > odd_null_count * 4 {
6059 return ByteContent::Utf16Be;
6060 }
6061 if odd_null_count > even_null_count * 4 {
6062 return ByteContent::Utf16Le;
6063 }
6064 return ByteContent::Binary;
6065 }
6066
6067 if non_text_like_count * 100 < limit * 8 {
6068 ByteContent::Unknown
6069 } else {
6070 ByteContent::Binary
6071 }
6072}
6073
6074fn is_known_binary_header(bytes: &[u8]) -> bool {
6075 bytes.starts_with(b"%PDF-") // PDF
6076 || bytes.starts_with(b"PK\x03\x04") // ZIP local header
6077 || bytes.starts_with(b"PK\x05\x06") // ZIP end of central directory
6078 || bytes.starts_with(b"PK\x07\x08") // ZIP spanning/splitting
6079 || bytes.starts_with(b"\x89PNG\r\n\x1a\n") // PNG
6080 || bytes.starts_with(b"\xFF\xD8\xFF") // JPEG
6081 || bytes.starts_with(b"GIF87a") // GIF87a
6082 || bytes.starts_with(b"GIF89a") // GIF89a
6083}