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