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