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