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