1mod ignore;
2mod worktree_settings;
3#[cfg(test)]
4mod worktree_tests;
5
6use ::ignore::gitignore::{Gitignore, GitignoreBuilder};
7use anyhow::{anyhow, Context as _, Result};
8use clock::ReplicaId;
9use collections::{HashMap, HashSet, VecDeque};
10use fs::{copy_recursive, Fs, RemoveOptions, Watcher};
11use futures::{
12 channel::{
13 mpsc::{self, UnboundedSender},
14 oneshot,
15 },
16 select_biased,
17 stream::select,
18 task::Poll,
19 FutureExt as _, Stream, StreamExt,
20};
21use fuzzy::CharBag;
22use git::{
23 repository::{GitFileStatus, GitRepository, RepoPath},
24 status::GitStatus,
25 DOT_GIT, GITIGNORE,
26};
27use gpui::{
28 AppContext, AsyncAppContext, BackgroundExecutor, Context, EventEmitter, Model, ModelContext,
29 Task,
30};
31use ignore::IgnoreStack;
32use itertools::Itertools;
33use parking_lot::Mutex;
34use postage::{
35 barrier,
36 prelude::{Sink as _, Stream as _},
37 watch,
38};
39use rpc::proto;
40use settings::{Settings, SettingsLocation, SettingsStore};
41use smol::channel::{self, Sender};
42use std::{
43 any::Any,
44 cmp::{self, Ordering},
45 convert::TryFrom,
46 ffi::OsStr,
47 fmt,
48 future::Future,
49 mem,
50 ops::{AddAssign, Deref, DerefMut, Sub},
51 path::{Path, PathBuf},
52 pin::Pin,
53 sync::{
54 atomic::{AtomicUsize, Ordering::SeqCst},
55 Arc,
56 },
57 time::{Duration, Instant, SystemTime},
58};
59use sum_tree::{Bias, Edit, SeekTarget, SumTree, TreeMap, TreeSet};
60use text::{LineEnding, Rope};
61use util::{
62 paths::{PathMatcher, HOME},
63 ResultExt,
64};
65
66pub use worktree_settings::WorktreeSettings;
67
68#[cfg(feature = "test-support")]
69pub const FS_WATCH_LATENCY: Duration = Duration::from_millis(100);
70#[cfg(not(feature = "test-support"))]
71pub const FS_WATCH_LATENCY: Duration = Duration::from_millis(100);
72
73#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash, PartialOrd, Ord)]
74pub struct WorktreeId(usize);
75
76/// A set of local or remote files that are being opened as part of a project.
77/// Responsible for tracking related FS (for local)/collab (for remote) events and corresponding updates.
78/// Stores git repositories data and the diagnostics for the file(s).
79///
80/// Has an absolute path, and may be set to be visible in Zed UI or not.
81/// May correspond to a directory or a single file.
82/// Possible examples:
83/// * a drag and dropped file — may be added as an invisible, "ephemeral" entry to the current worktree
84/// * a directory opened in Zed — may be added as a visible entry to the current worktree
85///
86/// Uses [`Entry`] to track the state of each file/directory, can look up absolute paths for entries.
87pub enum Worktree {
88 Local(LocalWorktree),
89 Remote(RemoteWorktree),
90}
91
92/// An entry, created in the worktree.
93#[derive(Debug)]
94pub enum CreatedEntry {
95 /// Got created and indexed by the worktree, receiving a corresponding entry.
96 Included(Entry),
97 /// Got created, but not indexed due to falling under exclusion filters.
98 Excluded { abs_path: PathBuf },
99}
100
101pub struct LocalWorktree {
102 snapshot: LocalSnapshot,
103 scan_requests_tx: channel::Sender<ScanRequest>,
104 path_prefixes_to_scan_tx: channel::Sender<Arc<Path>>,
105 is_scanning: (watch::Sender<bool>, watch::Receiver<bool>),
106 _background_scanner_tasks: Vec<Task<()>>,
107 update_observer: Option<ShareState>,
108 fs: Arc<dyn Fs>,
109 fs_case_sensitive: bool,
110 visible: bool,
111 next_entry_id: Arc<AtomicUsize>,
112}
113
114struct ScanRequest {
115 relative_paths: Vec<Arc<Path>>,
116 done: barrier::Sender,
117}
118
119pub struct RemoteWorktree {
120 snapshot: Snapshot,
121 background_snapshot: Arc<Mutex<Snapshot>>,
122 updates_tx: Option<UnboundedSender<proto::UpdateWorktree>>,
123 snapshot_subscriptions: VecDeque<(usize, oneshot::Sender<()>)>,
124 replica_id: ReplicaId,
125 visible: bool,
126 disconnected: bool,
127}
128
129#[derive(Clone)]
130pub struct Snapshot {
131 id: WorktreeId,
132 abs_path: Arc<Path>,
133 root_name: String,
134 root_char_bag: CharBag,
135 entries_by_path: SumTree<Entry>,
136 entries_by_id: SumTree<PathEntry>,
137 repository_entries: TreeMap<RepositoryWorkDirectory, RepositoryEntry>,
138
139 /// A number that increases every time the worktree begins scanning
140 /// a set of paths from the filesystem. This scanning could be caused
141 /// by some operation performed on the worktree, such as reading or
142 /// writing a file, or by an event reported by the filesystem.
143 scan_id: usize,
144
145 /// The latest scan id that has completed, and whose preceding scans
146 /// have all completed. The current `scan_id` could be more than one
147 /// greater than the `completed_scan_id` if operations are performed
148 /// on the worktree while it is processing a file-system event.
149 completed_scan_id: usize,
150}
151
152#[derive(Clone, Debug, PartialEq, Eq)]
153pub struct RepositoryEntry {
154 pub(crate) work_directory: WorkDirectoryEntry,
155 pub(crate) branch: Option<Arc<str>>,
156
157 /// If location_in_repo is set, it means the .git folder is external
158 /// and in a parent folder of the project root.
159 /// In that case, the work_directory field will point to the
160 /// project-root and location_in_repo contains the location of the
161 /// project-root in the repository.
162 ///
163 /// Example:
164 ///
165 /// my_root_folder/ <-- repository root
166 /// .git
167 /// my_sub_folder_1/
168 /// project_root/ <-- Project root, Zed opened here
169 /// ...
170 ///
171 /// For this setup, the attributes will have the following values:
172 ///
173 /// work_directory: pointing to "" entry
174 /// location_in_repo: Some("my_sub_folder_1/project_root")
175 pub(crate) location_in_repo: Option<Arc<Path>>,
176}
177
178impl RepositoryEntry {
179 pub fn branch(&self) -> Option<Arc<str>> {
180 self.branch.clone()
181 }
182
183 pub fn work_directory_id(&self) -> ProjectEntryId {
184 *self.work_directory
185 }
186
187 pub fn work_directory(&self, snapshot: &Snapshot) -> Option<RepositoryWorkDirectory> {
188 snapshot
189 .entry_for_id(self.work_directory_id())
190 .map(|entry| RepositoryWorkDirectory(entry.path.clone()))
191 }
192
193 pub fn build_update(&self, _: &Self) -> proto::RepositoryEntry {
194 self.into()
195 }
196
197 /// relativize returns the given project path relative to the root folder of the
198 /// repository.
199 /// If the root of the repository (and its .git folder) are located in a parent folder
200 /// of the project root folder, then the returned RepoPath is relative to the root
201 /// of the repository and not a valid path inside the project.
202 pub fn relativize(&self, worktree: &Snapshot, path: &Path) -> Result<RepoPath> {
203 let relativize_path = |path: &Path| {
204 let entry = worktree
205 .entry_for_id(self.work_directory.0)
206 .ok_or_else(|| anyhow!("entry not found"))?;
207
208 let relativized_path = path
209 .strip_prefix(&entry.path)
210 .map_err(|_| anyhow!("could not relativize {:?} against {:?}", path, entry.path))?;
211
212 Ok(relativized_path.into())
213 };
214
215 if let Some(location_in_repo) = &self.location_in_repo {
216 relativize_path(&location_in_repo.join(path))
217 } else {
218 relativize_path(path)
219 }
220 }
221}
222
223impl From<&RepositoryEntry> for proto::RepositoryEntry {
224 fn from(value: &RepositoryEntry) -> Self {
225 proto::RepositoryEntry {
226 work_directory_id: value.work_directory.to_proto(),
227 branch: value.branch.as_ref().map(|str| str.to_string()),
228 }
229 }
230}
231
232/// This path corresponds to the 'content path' of a repository in relation
233/// to Zed's project root.
234/// In the majority of the cases, this is the folder that contains the .git folder.
235/// But if a sub-folder of a git repository is opened, this corresponds to the
236/// project root and the .git folder is located in a parent directory.
237#[derive(Clone, Debug, Ord, PartialOrd, Eq, PartialEq)]
238pub struct RepositoryWorkDirectory(pub(crate) Arc<Path>);
239
240impl Default for RepositoryWorkDirectory {
241 fn default() -> Self {
242 RepositoryWorkDirectory(Arc::from(Path::new("")))
243 }
244}
245
246impl AsRef<Path> for RepositoryWorkDirectory {
247 fn as_ref(&self) -> &Path {
248 self.0.as_ref()
249 }
250}
251
252#[derive(Clone, Debug, Ord, PartialOrd, Eq, PartialEq)]
253pub struct WorkDirectoryEntry(ProjectEntryId);
254
255impl Deref for WorkDirectoryEntry {
256 type Target = ProjectEntryId;
257
258 fn deref(&self) -> &Self::Target {
259 &self.0
260 }
261}
262
263impl From<ProjectEntryId> for WorkDirectoryEntry {
264 fn from(value: ProjectEntryId) -> Self {
265 WorkDirectoryEntry(value)
266 }
267}
268
269#[derive(Debug, Clone)]
270pub struct LocalSnapshot {
271 snapshot: Snapshot,
272 /// All of the gitignore files in the worktree, indexed by their relative path.
273 /// The boolean indicates whether the gitignore needs to be updated.
274 ignores_by_parent_abs_path: HashMap<Arc<Path>, (Arc<Gitignore>, bool)>,
275 /// All of the git repositories in the worktree, indexed by the project entry
276 /// id of their parent directory.
277 git_repositories: TreeMap<ProjectEntryId, LocalRepositoryEntry>,
278 file_scan_exclusions: Vec<PathMatcher>,
279 private_files: Vec<PathMatcher>,
280 share_private_files: bool,
281}
282
283struct BackgroundScannerState {
284 snapshot: LocalSnapshot,
285 scanned_dirs: HashSet<ProjectEntryId>,
286 path_prefixes_to_scan: HashSet<Arc<Path>>,
287 paths_to_scan: HashSet<Arc<Path>>,
288 /// The ids of all of the entries that were removed from the snapshot
289 /// as part of the current update. These entry ids may be re-used
290 /// if the same inode is discovered at a new path, or if the given
291 /// path is re-created after being deleted.
292 removed_entry_ids: HashMap<u64, ProjectEntryId>,
293 changed_paths: Vec<Arc<Path>>,
294 prev_snapshot: Snapshot,
295}
296
297#[derive(Debug, Clone)]
298pub struct LocalRepositoryEntry {
299 pub(crate) git_dir_scan_id: usize,
300 pub(crate) repo_ptr: Arc<dyn GitRepository>,
301 /// Path to the actual .git folder.
302 /// Note: if .git is a file, this points to the folder indicated by the .git file
303 pub(crate) git_dir_path: Arc<Path>,
304}
305
306impl LocalRepositoryEntry {
307 pub fn repo(&self) -> &Arc<dyn GitRepository> {
308 &self.repo_ptr
309 }
310}
311
312impl Deref for LocalSnapshot {
313 type Target = Snapshot;
314
315 fn deref(&self) -> &Self::Target {
316 &self.snapshot
317 }
318}
319
320impl DerefMut for LocalSnapshot {
321 fn deref_mut(&mut self) -> &mut Self::Target {
322 &mut self.snapshot
323 }
324}
325
326enum ScanState {
327 Started,
328 Updated {
329 snapshot: LocalSnapshot,
330 changes: UpdatedEntriesSet,
331 barrier: Option<barrier::Sender>,
332 scanning: bool,
333 },
334}
335
336struct ShareState {
337 snapshots_tx:
338 mpsc::UnboundedSender<(LocalSnapshot, UpdatedEntriesSet, UpdatedGitRepositoriesSet)>,
339 resume_updates: watch::Sender<()>,
340 _maintain_remote_snapshot: Task<Option<()>>,
341}
342
343#[derive(Clone)]
344pub enum Event {
345 UpdatedEntries(UpdatedEntriesSet),
346 UpdatedGitRepositories(UpdatedGitRepositoriesSet),
347}
348
349impl EventEmitter<Event> for Worktree {}
350
351impl Worktree {
352 pub async fn local(
353 path: impl Into<Arc<Path>>,
354 visible: bool,
355 fs: Arc<dyn Fs>,
356 next_entry_id: Arc<AtomicUsize>,
357 cx: &mut AsyncAppContext,
358 ) -> Result<Model<Self>> {
359 // After determining whether the root entry is a file or a directory, populate the
360 // snapshot's "root name", which will be used for the purpose of fuzzy matching.
361 let abs_path = path.into();
362
363 let metadata = fs
364 .metadata(&abs_path)
365 .await
366 .context("failed to stat worktree path")?;
367
368 let fs_case_sensitive = fs.is_case_sensitive().await.unwrap_or_else(|e| {
369 log::error!(
370 "Failed to determine whether filesystem is case sensitive (falling back to true) due to error: {e:#}"
371 );
372 true
373 });
374
375 cx.new_model(move |cx: &mut ModelContext<Worktree>| {
376 cx.observe_global::<SettingsStore>(move |this, cx| {
377 if let Self::Local(this) = this {
378 let new_file_scan_exclusions = path_matchers(
379 WorktreeSettings::get_global(cx)
380 .file_scan_exclusions
381 .as_deref(),
382 "file_scan_exclusions",
383 );
384 let new_private_files = path_matchers(
385 WorktreeSettings::get(Some(settings::SettingsLocation {
386 worktree_id: cx.handle().entity_id().as_u64() as usize,
387 path: Path::new("")
388 }), cx).private_files.as_deref(),
389 "private_files",
390 );
391
392 if new_file_scan_exclusions != this.snapshot.file_scan_exclusions
393 || new_private_files != this.snapshot.private_files
394 {
395 this.snapshot.file_scan_exclusions = new_file_scan_exclusions;
396 this.snapshot.private_files = new_private_files;
397
398 log::info!(
399 "Re-scanning directories, new scan exclude files: {:?}, new dotenv files: {:?}",
400 this.snapshot
401 .file_scan_exclusions
402 .iter()
403 .map(ToString::to_string)
404 .collect::<Vec<_>>(),
405 this.snapshot
406 .private_files
407 .iter()
408 .map(ToString::to_string)
409 .collect::<Vec<_>>()
410 );
411
412 this.restart_background_scanners(cx);
413 }
414 }
415 })
416 .detach();
417
418 let root_name = abs_path
419 .file_name()
420 .map_or(String::new(), |f| f.to_string_lossy().to_string());
421
422 let mut snapshot = LocalSnapshot {
423 file_scan_exclusions: path_matchers(
424 WorktreeSettings::get_global(cx)
425 .file_scan_exclusions
426 .as_deref(),
427 "file_scan_exclusions",
428 ),
429 private_files: path_matchers(
430 WorktreeSettings::get(Some(SettingsLocation {
431 worktree_id: cx.handle().entity_id().as_u64() as usize,
432 path: Path::new(""),
433 }), cx).private_files.as_deref(),
434 "private_files",
435 ),
436 share_private_files: false,
437 ignores_by_parent_abs_path: Default::default(),
438 git_repositories: Default::default(),
439 snapshot: Snapshot {
440 id: WorktreeId::from_usize(cx.entity_id().as_u64() as usize),
441 abs_path: abs_path.to_path_buf().into(),
442 root_name: root_name.clone(),
443 root_char_bag: root_name.chars().map(|c| c.to_ascii_lowercase()).collect(),
444 entries_by_path: Default::default(),
445 entries_by_id: Default::default(),
446 repository_entries: Default::default(),
447 scan_id: 1,
448 completed_scan_id: 0,
449 },
450 };
451
452 if let Some(metadata) = metadata {
453 snapshot.insert_entry(
454 Entry::new(
455 Arc::from(Path::new("")),
456 &metadata,
457 &next_entry_id,
458 snapshot.root_char_bag,
459 None
460 ),
461 fs.as_ref(),
462 );
463 }
464
465 let (scan_requests_tx, scan_requests_rx) = channel::unbounded();
466 let (path_prefixes_to_scan_tx, path_prefixes_to_scan_rx) = channel::unbounded();
467 let task_snapshot = snapshot.clone();
468 Worktree::Local(LocalWorktree {
469 next_entry_id: Arc::clone(&next_entry_id),
470 snapshot,
471 is_scanning: watch::channel_with(true),
472 update_observer: None,
473 scan_requests_tx,
474 path_prefixes_to_scan_tx,
475 _background_scanner_tasks: start_background_scan_tasks(
476 &abs_path,
477 task_snapshot,
478 scan_requests_rx,
479 path_prefixes_to_scan_rx,
480 Arc::clone(&next_entry_id),
481 Arc::clone(&fs),
482 cx,
483 ),
484 fs,
485 fs_case_sensitive,
486 visible,
487 })
488 })
489 }
490
491 pub fn remote(
492 replica_id: ReplicaId,
493 worktree: proto::WorktreeMetadata,
494 cx: &mut AppContext,
495 ) -> Model<Self> {
496 cx.new_model(|cx: &mut ModelContext<Self>| {
497 let snapshot = Snapshot {
498 id: WorktreeId(worktree.id as usize),
499 abs_path: Arc::from(PathBuf::from(worktree.abs_path)),
500 root_name: worktree.root_name.clone(),
501 root_char_bag: worktree
502 .root_name
503 .chars()
504 .map(|c| c.to_ascii_lowercase())
505 .collect(),
506 entries_by_path: Default::default(),
507 entries_by_id: Default::default(),
508 repository_entries: Default::default(),
509 scan_id: 1,
510 completed_scan_id: 0,
511 };
512
513 let (updates_tx, mut updates_rx) = mpsc::unbounded();
514 let background_snapshot = Arc::new(Mutex::new(snapshot.clone()));
515 let (mut snapshot_updated_tx, mut snapshot_updated_rx) = watch::channel();
516
517 cx.background_executor()
518 .spawn({
519 let background_snapshot = background_snapshot.clone();
520 async move {
521 while let Some(update) = updates_rx.next().await {
522 if let Err(error) =
523 background_snapshot.lock().apply_remote_update(update)
524 {
525 log::error!("error applying worktree update: {}", error);
526 }
527 snapshot_updated_tx.send(()).await.ok();
528 }
529 }
530 })
531 .detach();
532
533 cx.spawn(|this, mut cx| async move {
534 while (snapshot_updated_rx.recv().await).is_some() {
535 this.update(&mut cx, |this, cx| {
536 let this = this.as_remote_mut().unwrap();
537 this.snapshot = this.background_snapshot.lock().clone();
538 cx.emit(Event::UpdatedEntries(Arc::from([])));
539 cx.notify();
540 while let Some((scan_id, _)) = this.snapshot_subscriptions.front() {
541 if this.observed_snapshot(*scan_id) {
542 let (_, tx) = this.snapshot_subscriptions.pop_front().unwrap();
543 let _ = tx.send(());
544 } else {
545 break;
546 }
547 }
548 })?;
549 }
550 anyhow::Ok(())
551 })
552 .detach();
553
554 Worktree::Remote(RemoteWorktree {
555 replica_id,
556 snapshot: snapshot.clone(),
557 background_snapshot,
558 updates_tx: Some(updates_tx),
559 snapshot_subscriptions: Default::default(),
560 visible: worktree.visible,
561 disconnected: false,
562 })
563 })
564 }
565
566 pub fn as_local(&self) -> Option<&LocalWorktree> {
567 if let Worktree::Local(worktree) = self {
568 Some(worktree)
569 } else {
570 None
571 }
572 }
573
574 pub fn as_remote(&self) -> Option<&RemoteWorktree> {
575 if let Worktree::Remote(worktree) = self {
576 Some(worktree)
577 } else {
578 None
579 }
580 }
581
582 pub fn as_local_mut(&mut self) -> Option<&mut LocalWorktree> {
583 if let Worktree::Local(worktree) = self {
584 Some(worktree)
585 } else {
586 None
587 }
588 }
589
590 pub fn as_remote_mut(&mut self) -> Option<&mut RemoteWorktree> {
591 if let Worktree::Remote(worktree) = self {
592 Some(worktree)
593 } else {
594 None
595 }
596 }
597
598 pub fn is_local(&self) -> bool {
599 matches!(self, Worktree::Local(_))
600 }
601
602 pub fn is_remote(&self) -> bool {
603 !self.is_local()
604 }
605
606 pub fn snapshot(&self) -> Snapshot {
607 match self {
608 Worktree::Local(worktree) => worktree.snapshot().snapshot,
609 Worktree::Remote(worktree) => worktree.snapshot(),
610 }
611 }
612
613 pub fn scan_id(&self) -> usize {
614 match self {
615 Worktree::Local(worktree) => worktree.snapshot.scan_id,
616 Worktree::Remote(worktree) => worktree.snapshot.scan_id,
617 }
618 }
619
620 pub fn completed_scan_id(&self) -> usize {
621 match self {
622 Worktree::Local(worktree) => worktree.snapshot.completed_scan_id,
623 Worktree::Remote(worktree) => worktree.snapshot.completed_scan_id,
624 }
625 }
626
627 pub fn is_visible(&self) -> bool {
628 match self {
629 Worktree::Local(worktree) => worktree.visible,
630 Worktree::Remote(worktree) => worktree.visible,
631 }
632 }
633
634 pub fn replica_id(&self) -> ReplicaId {
635 match self {
636 Worktree::Local(_) => 0,
637 Worktree::Remote(worktree) => worktree.replica_id,
638 }
639 }
640
641 pub fn abs_path(&self) -> Arc<Path> {
642 match self {
643 Worktree::Local(worktree) => worktree.abs_path.clone(),
644 Worktree::Remote(worktree) => worktree.abs_path.clone(),
645 }
646 }
647
648 pub fn root_file(&self, cx: &mut ModelContext<Self>) -> Option<Arc<File>> {
649 let entry = self.root_entry()?;
650 Some(File::for_entry(entry.clone(), cx.handle()))
651 }
652}
653
654fn start_background_scan_tasks(
655 abs_path: &Path,
656 snapshot: LocalSnapshot,
657 scan_requests_rx: channel::Receiver<ScanRequest>,
658 path_prefixes_to_scan_rx: channel::Receiver<Arc<Path>>,
659 next_entry_id: Arc<AtomicUsize>,
660 fs: Arc<dyn Fs>,
661 cx: &mut ModelContext<'_, Worktree>,
662) -> Vec<Task<()>> {
663 let (scan_states_tx, mut scan_states_rx) = mpsc::unbounded();
664 let background_scanner = cx.background_executor().spawn({
665 let abs_path = if cfg!(target_os = "windows") {
666 abs_path
667 .canonicalize()
668 .unwrap_or_else(|_| abs_path.to_path_buf())
669 } else {
670 abs_path.to_path_buf()
671 };
672 let background = cx.background_executor().clone();
673 async move {
674 let (events, watcher) = fs.watch(&abs_path, FS_WATCH_LATENCY).await;
675 let case_sensitive = fs.is_case_sensitive().await.unwrap_or_else(|e| {
676 log::error!("Failed to determine whether filesystem is case sensitive: {e:#}");
677 true
678 });
679
680 let mut scanner = BackgroundScanner {
681 fs,
682 fs_case_sensitive: case_sensitive,
683 status_updates_tx: scan_states_tx,
684 executor: background,
685 scan_requests_rx,
686 path_prefixes_to_scan_rx,
687 next_entry_id,
688 state: Mutex::new(BackgroundScannerState {
689 prev_snapshot: snapshot.snapshot.clone(),
690 snapshot,
691 scanned_dirs: Default::default(),
692 path_prefixes_to_scan: Default::default(),
693 paths_to_scan: Default::default(),
694 removed_entry_ids: Default::default(),
695 changed_paths: Default::default(),
696 }),
697 phase: BackgroundScannerPhase::InitialScan,
698 watcher,
699 };
700
701 scanner.run(events).await;
702 }
703 });
704 let scan_state_updater = cx.spawn(|this, mut cx| async move {
705 while let Some((state, this)) = scan_states_rx.next().await.zip(this.upgrade()) {
706 this.update(&mut cx, |this, cx| {
707 let this = this.as_local_mut().unwrap();
708 match state {
709 ScanState::Started => {
710 *this.is_scanning.0.borrow_mut() = true;
711 }
712 ScanState::Updated {
713 snapshot,
714 changes,
715 barrier,
716 scanning,
717 } => {
718 *this.is_scanning.0.borrow_mut() = scanning;
719 this.set_snapshot(snapshot, changes, cx);
720 drop(barrier);
721 }
722 }
723 cx.notify();
724 })
725 .ok();
726 }
727 });
728 vec![background_scanner, scan_state_updater]
729}
730
731fn path_matchers(values: Option<&[String]>, context: &'static str) -> Vec<PathMatcher> {
732 values
733 .unwrap_or(&[])
734 .iter()
735 .sorted()
736 .filter_map(|pattern| {
737 PathMatcher::new(pattern)
738 .map(Some)
739 .unwrap_or_else(|e| {
740 log::error!(
741 "Skipping pattern {pattern} in `{}` project settings due to parsing error: {e:#}", context
742 );
743 None
744 })
745 })
746 .collect()
747}
748
749impl LocalWorktree {
750 pub fn contains_abs_path(&self, path: &Path) -> bool {
751 path.starts_with(&self.abs_path)
752 }
753
754 fn restart_background_scanners(&mut self, cx: &mut ModelContext<Worktree>) {
755 let (scan_requests_tx, scan_requests_rx) = channel::unbounded();
756 let (path_prefixes_to_scan_tx, path_prefixes_to_scan_rx) = channel::unbounded();
757 self.scan_requests_tx = scan_requests_tx;
758 self.path_prefixes_to_scan_tx = path_prefixes_to_scan_tx;
759 self._background_scanner_tasks = start_background_scan_tasks(
760 &self.snapshot.abs_path,
761 self.snapshot(),
762 scan_requests_rx,
763 path_prefixes_to_scan_rx,
764 Arc::clone(&self.next_entry_id),
765 Arc::clone(&self.fs),
766 cx,
767 );
768 self.is_scanning = watch::channel_with(true);
769 }
770
771 fn set_snapshot(
772 &mut self,
773 mut new_snapshot: LocalSnapshot,
774 entry_changes: UpdatedEntriesSet,
775 cx: &mut ModelContext<Worktree>,
776 ) {
777 let repo_changes = self.changed_repos(&self.snapshot, &new_snapshot);
778
779 new_snapshot.share_private_files = self.snapshot.share_private_files;
780 self.snapshot = new_snapshot;
781
782 if let Some(share) = self.update_observer.as_mut() {
783 share
784 .snapshots_tx
785 .unbounded_send((
786 self.snapshot.clone(),
787 entry_changes.clone(),
788 repo_changes.clone(),
789 ))
790 .ok();
791 }
792
793 if !entry_changes.is_empty() {
794 cx.emit(Event::UpdatedEntries(entry_changes));
795 }
796 if !repo_changes.is_empty() {
797 cx.emit(Event::UpdatedGitRepositories(repo_changes));
798 }
799 }
800
801 fn changed_repos(
802 &self,
803 old_snapshot: &LocalSnapshot,
804 new_snapshot: &LocalSnapshot,
805 ) -> UpdatedGitRepositoriesSet {
806 let mut changes = Vec::new();
807 let mut old_repos = old_snapshot.git_repositories.iter().peekable();
808 let mut new_repos = new_snapshot.git_repositories.iter().peekable();
809 loop {
810 match (new_repos.peek().map(clone), old_repos.peek().map(clone)) {
811 (Some((new_entry_id, new_repo)), Some((old_entry_id, old_repo))) => {
812 match Ord::cmp(&new_entry_id, &old_entry_id) {
813 Ordering::Less => {
814 if let Some(entry) = new_snapshot.entry_for_id(new_entry_id) {
815 changes.push((
816 entry.path.clone(),
817 GitRepositoryChange {
818 old_repository: None,
819 },
820 ));
821 }
822 new_repos.next();
823 }
824 Ordering::Equal => {
825 if new_repo.git_dir_scan_id != old_repo.git_dir_scan_id {
826 if let Some(entry) = new_snapshot.entry_for_id(new_entry_id) {
827 let old_repo = old_snapshot
828 .repository_entries
829 .get(&RepositoryWorkDirectory(entry.path.clone()))
830 .cloned();
831 changes.push((
832 entry.path.clone(),
833 GitRepositoryChange {
834 old_repository: old_repo,
835 },
836 ));
837 }
838 }
839 new_repos.next();
840 old_repos.next();
841 }
842 Ordering::Greater => {
843 if let Some(entry) = old_snapshot.entry_for_id(old_entry_id) {
844 let old_repo = old_snapshot
845 .repository_entries
846 .get(&RepositoryWorkDirectory(entry.path.clone()))
847 .cloned();
848 changes.push((
849 entry.path.clone(),
850 GitRepositoryChange {
851 old_repository: old_repo,
852 },
853 ));
854 }
855 old_repos.next();
856 }
857 }
858 }
859 (Some((entry_id, _)), None) => {
860 if let Some(entry) = new_snapshot.entry_for_id(entry_id) {
861 changes.push((
862 entry.path.clone(),
863 GitRepositoryChange {
864 old_repository: None,
865 },
866 ));
867 }
868 new_repos.next();
869 }
870 (None, Some((entry_id, _))) => {
871 if let Some(entry) = old_snapshot.entry_for_id(entry_id) {
872 let old_repo = old_snapshot
873 .repository_entries
874 .get(&RepositoryWorkDirectory(entry.path.clone()))
875 .cloned();
876 changes.push((
877 entry.path.clone(),
878 GitRepositoryChange {
879 old_repository: old_repo,
880 },
881 ));
882 }
883 old_repos.next();
884 }
885 (None, None) => break,
886 }
887 }
888
889 fn clone<T: Clone, U: Clone>(value: &(&T, &U)) -> (T, U) {
890 (value.0.clone(), value.1.clone())
891 }
892
893 changes.into()
894 }
895
896 pub fn scan_complete(&self) -> impl Future<Output = ()> {
897 let mut is_scanning_rx = self.is_scanning.1.clone();
898 async move {
899 let mut is_scanning = *is_scanning_rx.borrow();
900 while is_scanning {
901 if let Some(value) = is_scanning_rx.recv().await {
902 is_scanning = value;
903 } else {
904 break;
905 }
906 }
907 }
908 }
909
910 pub fn snapshot(&self) -> LocalSnapshot {
911 self.snapshot.clone()
912 }
913
914 pub fn metadata_proto(&self) -> proto::WorktreeMetadata {
915 proto::WorktreeMetadata {
916 id: self.id().to_proto(),
917 root_name: self.root_name().to_string(),
918 visible: self.visible,
919 abs_path: self.abs_path().as_os_str().to_string_lossy().into(),
920 }
921 }
922
923 pub fn load_file(
924 &self,
925 path: &Path,
926 cx: &mut ModelContext<Worktree>,
927 ) -> Task<Result<(File, String, Option<String>)>> {
928 let path = Arc::from(path);
929 let abs_path = self.absolutize(&path);
930 let fs = self.fs.clone();
931 let entry = self.refresh_entry(path.clone(), None, cx);
932
933 cx.spawn(|this, mut cx| async move {
934 let abs_path = abs_path?;
935 let text = fs.load(&abs_path).await?;
936 let mut index_task = None;
937 let snapshot = this.update(&mut cx, |this, _| this.as_local().unwrap().snapshot())?;
938 if let Some(repo) = snapshot.repository_for_path(&path) {
939 if let Some(repo_path) = repo.relativize(&snapshot, &path).log_err() {
940 if let Some(git_repo) = snapshot.git_repositories.get(&*repo.work_directory) {
941 let git_repo = git_repo.repo_ptr.clone();
942 index_task = Some(cx.background_executor().spawn({
943 let fs = fs.clone();
944 let abs_path = abs_path.clone();
945 async move {
946 let abs_path_metadata = fs
947 .metadata(&abs_path)
948 .await
949 .with_context(|| {
950 format!("loading file and FS metadata for {abs_path:?}")
951 })
952 .log_err()
953 .flatten()?;
954 if abs_path_metadata.is_dir || abs_path_metadata.is_symlink {
955 None
956 } else {
957 git_repo.load_index_text(&repo_path)
958 }
959 }
960 }));
961 }
962 }
963 }
964
965 let diff_base = if let Some(index_task) = index_task {
966 index_task.await
967 } else {
968 None
969 };
970
971 let worktree = this
972 .upgrade()
973 .ok_or_else(|| anyhow!("worktree was dropped"))?;
974 match entry.await? {
975 Some(entry) => Ok((
976 File {
977 entry_id: Some(entry.id),
978 worktree,
979 path: entry.path,
980 mtime: entry.mtime,
981 is_local: true,
982 is_deleted: false,
983 is_private: entry.is_private,
984 },
985 text,
986 diff_base,
987 )),
988 None => {
989 let metadata = fs
990 .metadata(&abs_path)
991 .await
992 .with_context(|| {
993 format!("Loading metadata for excluded file {abs_path:?}")
994 })?
995 .with_context(|| {
996 format!("Excluded file {abs_path:?} got removed during loading")
997 })?;
998 let is_private = snapshot.is_path_private(path.as_ref());
999 Ok((
1000 File {
1001 entry_id: None,
1002 worktree,
1003 path,
1004 mtime: Some(metadata.mtime),
1005 is_local: true,
1006 is_deleted: false,
1007 is_private,
1008 },
1009 text,
1010 diff_base,
1011 ))
1012 }
1013 }
1014 })
1015 }
1016
1017 /// Find the lowest path in the worktree's datastructures that is an ancestor
1018 fn lowest_ancestor(&self, path: &Path) -> PathBuf {
1019 let mut lowest_ancestor = None;
1020 for path in path.ancestors() {
1021 if self.entry_for_path(path).is_some() {
1022 lowest_ancestor = Some(path.to_path_buf());
1023 break;
1024 }
1025 }
1026
1027 lowest_ancestor.unwrap_or_else(|| PathBuf::from(""))
1028 }
1029
1030 pub fn create_entry(
1031 &self,
1032 path: impl Into<Arc<Path>>,
1033 is_dir: bool,
1034 cx: &mut ModelContext<Worktree>,
1035 ) -> Task<Result<CreatedEntry>> {
1036 let path = path.into();
1037 let abs_path = match self.absolutize(&path) {
1038 Ok(path) => path,
1039 Err(e) => return Task::ready(Err(e.context(format!("absolutizing path {path:?}")))),
1040 };
1041 let path_excluded = self.is_path_excluded(&abs_path);
1042 let fs = self.fs.clone();
1043 let task_abs_path = abs_path.clone();
1044 let write = cx.background_executor().spawn(async move {
1045 if is_dir {
1046 fs.create_dir(&task_abs_path)
1047 .await
1048 .with_context(|| format!("creating directory {task_abs_path:?}"))
1049 } else {
1050 fs.save(&task_abs_path, &Rope::default(), LineEnding::default())
1051 .await
1052 .with_context(|| format!("creating file {task_abs_path:?}"))
1053 }
1054 });
1055
1056 let lowest_ancestor = self.lowest_ancestor(&path);
1057 cx.spawn(|this, mut cx| async move {
1058 write.await?;
1059 if path_excluded {
1060 return Ok(CreatedEntry::Excluded { abs_path });
1061 }
1062
1063 let (result, refreshes) = this.update(&mut cx, |this, cx| {
1064 let mut refreshes = Vec::new();
1065 let refresh_paths = path.strip_prefix(&lowest_ancestor).unwrap();
1066 for refresh_path in refresh_paths.ancestors() {
1067 if refresh_path == Path::new("") {
1068 continue;
1069 }
1070 let refresh_full_path = lowest_ancestor.join(refresh_path);
1071
1072 refreshes.push(this.as_local_mut().unwrap().refresh_entry(
1073 refresh_full_path.into(),
1074 None,
1075 cx,
1076 ));
1077 }
1078 (
1079 this.as_local_mut().unwrap().refresh_entry(path, None, cx),
1080 refreshes,
1081 )
1082 })?;
1083 for refresh in refreshes {
1084 refresh.await.log_err();
1085 }
1086
1087 Ok(result
1088 .await?
1089 .map(CreatedEntry::Included)
1090 .unwrap_or_else(|| CreatedEntry::Excluded { abs_path }))
1091 })
1092 }
1093
1094 pub fn write_file(
1095 &self,
1096 path: impl Into<Arc<Path>>,
1097 text: Rope,
1098 line_ending: LineEnding,
1099 cx: &mut ModelContext<Worktree>,
1100 ) -> Task<Result<Option<Entry>>> {
1101 let path: Arc<Path> = path.into();
1102 let abs_path = self.absolutize(&path);
1103 let fs = self.fs.clone();
1104 let write = cx
1105 .background_executor()
1106 .spawn(async move { fs.save(&abs_path?, &text, line_ending).await });
1107
1108 cx.spawn(|this, mut cx| async move {
1109 write.await?;
1110 this.update(&mut cx, |this, cx| {
1111 this.as_local_mut().unwrap().refresh_entry(path, None, cx)
1112 })?
1113 .await
1114 })
1115 }
1116
1117 pub fn delete_entry(
1118 &self,
1119 entry_id: ProjectEntryId,
1120 trash: bool,
1121 cx: &mut ModelContext<Worktree>,
1122 ) -> Option<Task<Result<()>>> {
1123 let entry = self.entry_for_id(entry_id)?.clone();
1124 let abs_path = self.absolutize(&entry.path);
1125 let fs = self.fs.clone();
1126
1127 let delete = cx.background_executor().spawn(async move {
1128 if entry.is_file() {
1129 if trash {
1130 fs.trash_file(&abs_path?, Default::default()).await?;
1131 } else {
1132 fs.remove_file(&abs_path?, Default::default()).await?;
1133 }
1134 } else {
1135 if trash {
1136 fs.trash_dir(
1137 &abs_path?,
1138 RemoveOptions {
1139 recursive: true,
1140 ignore_if_not_exists: false,
1141 },
1142 )
1143 .await?;
1144 } else {
1145 fs.remove_dir(
1146 &abs_path?,
1147 RemoveOptions {
1148 recursive: true,
1149 ignore_if_not_exists: false,
1150 },
1151 )
1152 .await?;
1153 }
1154 }
1155 anyhow::Ok(entry.path)
1156 });
1157
1158 Some(cx.spawn(|this, mut cx| async move {
1159 let path = delete.await?;
1160 this.update(&mut cx, |this, _| {
1161 this.as_local_mut()
1162 .unwrap()
1163 .refresh_entries_for_paths(vec![path])
1164 })?
1165 .recv()
1166 .await;
1167 Ok(())
1168 }))
1169 }
1170
1171 pub fn rename_entry(
1172 &self,
1173 entry_id: ProjectEntryId,
1174 new_path: impl Into<Arc<Path>>,
1175 cx: &mut ModelContext<Worktree>,
1176 ) -> Task<Result<CreatedEntry>> {
1177 let old_path = match self.entry_for_id(entry_id) {
1178 Some(entry) => entry.path.clone(),
1179 None => return Task::ready(Err(anyhow!("no entry to rename for id {entry_id:?}"))),
1180 };
1181 let new_path = new_path.into();
1182 let abs_old_path = self.absolutize(&old_path);
1183 let Ok(abs_new_path) = self.absolutize(&new_path) else {
1184 return Task::ready(Err(anyhow!("absolutizing path {new_path:?}")));
1185 };
1186 let abs_path = abs_new_path.clone();
1187 let fs = self.fs.clone();
1188 let case_sensitive = self.fs_case_sensitive;
1189 let rename = cx.background_executor().spawn(async move {
1190 let abs_old_path = abs_old_path?;
1191 let abs_new_path = abs_new_path;
1192
1193 let abs_old_path_lower = abs_old_path.to_str().map(|p| p.to_lowercase());
1194 let abs_new_path_lower = abs_new_path.to_str().map(|p| p.to_lowercase());
1195
1196 // If we're on a case-insensitive FS and we're doing a case-only rename (i.e. `foobar` to `FOOBAR`)
1197 // we want to overwrite, because otherwise we run into a file-already-exists error.
1198 let overwrite = !case_sensitive
1199 && abs_old_path != abs_new_path
1200 && abs_old_path_lower == abs_new_path_lower;
1201
1202 fs.rename(
1203 &abs_old_path,
1204 &abs_new_path,
1205 fs::RenameOptions {
1206 overwrite,
1207 ..Default::default()
1208 },
1209 )
1210 .await
1211 .with_context(|| format!("Renaming {abs_old_path:?} into {abs_new_path:?}"))
1212 });
1213
1214 cx.spawn(|this, mut cx| async move {
1215 rename.await?;
1216 Ok(this
1217 .update(&mut cx, |this, cx| {
1218 this.as_local_mut()
1219 .unwrap()
1220 .refresh_entry(new_path.clone(), Some(old_path), cx)
1221 })?
1222 .await?
1223 .map(CreatedEntry::Included)
1224 .unwrap_or_else(|| CreatedEntry::Excluded { abs_path }))
1225 })
1226 }
1227
1228 pub fn copy_entry(
1229 &self,
1230 entry_id: ProjectEntryId,
1231 new_path: impl Into<Arc<Path>>,
1232 cx: &mut ModelContext<Worktree>,
1233 ) -> Task<Result<Option<Entry>>> {
1234 let old_path = match self.entry_for_id(entry_id) {
1235 Some(entry) => entry.path.clone(),
1236 None => return Task::ready(Ok(None)),
1237 };
1238 let new_path = new_path.into();
1239 let abs_old_path = self.absolutize(&old_path);
1240 let abs_new_path = self.absolutize(&new_path);
1241 let fs = self.fs.clone();
1242 let copy = cx.background_executor().spawn(async move {
1243 copy_recursive(
1244 fs.as_ref(),
1245 &abs_old_path?,
1246 &abs_new_path?,
1247 Default::default(),
1248 )
1249 .await
1250 });
1251
1252 cx.spawn(|this, mut cx| async move {
1253 copy.await?;
1254 this.update(&mut cx, |this, cx| {
1255 this.as_local_mut()
1256 .unwrap()
1257 .refresh_entry(new_path.clone(), None, cx)
1258 })?
1259 .await
1260 })
1261 }
1262
1263 pub fn expand_entry(
1264 &mut self,
1265 entry_id: ProjectEntryId,
1266 cx: &mut ModelContext<Worktree>,
1267 ) -> Option<Task<Result<()>>> {
1268 let path = self.entry_for_id(entry_id)?.path.clone();
1269 let mut refresh = self.refresh_entries_for_paths(vec![path]);
1270 Some(cx.background_executor().spawn(async move {
1271 refresh.next().await;
1272 Ok(())
1273 }))
1274 }
1275
1276 pub fn refresh_entries_for_paths(&self, paths: Vec<Arc<Path>>) -> barrier::Receiver {
1277 let (tx, rx) = barrier::channel();
1278 self.scan_requests_tx
1279 .try_send(ScanRequest {
1280 relative_paths: paths,
1281 done: tx,
1282 })
1283 .ok();
1284 rx
1285 }
1286
1287 pub fn add_path_prefix_to_scan(&self, path_prefix: Arc<Path>) {
1288 self.path_prefixes_to_scan_tx.try_send(path_prefix).ok();
1289 }
1290
1291 fn refresh_entry(
1292 &self,
1293 path: Arc<Path>,
1294 old_path: Option<Arc<Path>>,
1295 cx: &mut ModelContext<Worktree>,
1296 ) -> Task<Result<Option<Entry>>> {
1297 if self.is_path_excluded(&path) {
1298 return Task::ready(Ok(None));
1299 }
1300 let paths = if let Some(old_path) = old_path.as_ref() {
1301 vec![old_path.clone(), path.clone()]
1302 } else {
1303 vec![path.clone()]
1304 };
1305 let t0 = Instant::now();
1306 let mut refresh = self.refresh_entries_for_paths(paths);
1307 cx.spawn(move |this, mut cx| async move {
1308 refresh.recv().await;
1309 log::trace!("refreshed entry {path:?} in {:?}", t0.elapsed());
1310 let new_entry = this.update(&mut cx, |this, _| {
1311 this.entry_for_path(path)
1312 .cloned()
1313 .ok_or_else(|| anyhow!("failed to read path after update"))
1314 })??;
1315 Ok(Some(new_entry))
1316 })
1317 }
1318
1319 pub fn observe_updates<F, Fut>(
1320 &mut self,
1321 project_id: u64,
1322 cx: &mut ModelContext<Worktree>,
1323 callback: F,
1324 ) where
1325 F: 'static + Send + Fn(proto::UpdateWorktree) -> Fut,
1326 Fut: Send + Future<Output = bool>,
1327 {
1328 #[cfg(any(test, feature = "test-support"))]
1329 const MAX_CHUNK_SIZE: usize = 2;
1330 #[cfg(not(any(test, feature = "test-support")))]
1331 const MAX_CHUNK_SIZE: usize = 256;
1332
1333 if let Some(observer) = self.update_observer.as_mut() {
1334 *observer.resume_updates.borrow_mut() = ();
1335 return;
1336 }
1337
1338 let (resume_updates_tx, mut resume_updates_rx) = watch::channel::<()>();
1339 let (snapshots_tx, mut snapshots_rx) =
1340 mpsc::unbounded::<(LocalSnapshot, UpdatedEntriesSet, UpdatedGitRepositoriesSet)>();
1341 snapshots_tx
1342 .unbounded_send((self.snapshot(), Arc::from([]), Arc::from([])))
1343 .ok();
1344
1345 let worktree_id = cx.entity_id().as_u64();
1346 let _maintain_remote_snapshot = cx.background_executor().spawn(async move {
1347 let mut is_first = true;
1348 while let Some((snapshot, entry_changes, repo_changes)) = snapshots_rx.next().await {
1349 let update;
1350 if is_first {
1351 update = snapshot.build_initial_update(project_id, worktree_id);
1352 is_first = false;
1353 } else {
1354 update =
1355 snapshot.build_update(project_id, worktree_id, entry_changes, repo_changes);
1356 }
1357
1358 for update in proto::split_worktree_update(update, MAX_CHUNK_SIZE) {
1359 let _ = resume_updates_rx.try_recv();
1360 loop {
1361 let result = callback(update.clone());
1362 if result.await {
1363 break;
1364 } else {
1365 log::info!("waiting to resume updates");
1366 if resume_updates_rx.next().await.is_none() {
1367 return Some(());
1368 }
1369 }
1370 }
1371 }
1372 }
1373 Some(())
1374 });
1375
1376 self.update_observer = Some(ShareState {
1377 snapshots_tx,
1378 resume_updates: resume_updates_tx,
1379 _maintain_remote_snapshot,
1380 });
1381 }
1382
1383 pub fn stop_observing_updates(&mut self) {
1384 self.update_observer.take();
1385 }
1386
1387 #[cfg(any(test, feature = "test-support"))]
1388 pub fn has_update_observer(&self) -> bool {
1389 self.update_observer.is_some()
1390 }
1391
1392 pub fn share_private_files(&mut self, cx: &mut ModelContext<Worktree>) {
1393 self.snapshot.share_private_files = true;
1394 self.restart_background_scanners(cx);
1395 }
1396}
1397
1398impl RemoteWorktree {
1399 fn snapshot(&self) -> Snapshot {
1400 self.snapshot.clone()
1401 }
1402
1403 pub fn disconnected_from_host(&mut self) {
1404 self.updates_tx.take();
1405 self.snapshot_subscriptions.clear();
1406 self.disconnected = true;
1407 }
1408
1409 pub fn update_from_remote(&mut self, update: proto::UpdateWorktree) {
1410 if let Some(updates_tx) = &self.updates_tx {
1411 updates_tx
1412 .unbounded_send(update)
1413 .expect("consumer runs to completion");
1414 }
1415 }
1416
1417 fn observed_snapshot(&self, scan_id: usize) -> bool {
1418 self.completed_scan_id >= scan_id
1419 }
1420
1421 pub fn wait_for_snapshot(&mut self, scan_id: usize) -> impl Future<Output = Result<()>> {
1422 let (tx, rx) = oneshot::channel();
1423 if self.observed_snapshot(scan_id) {
1424 let _ = tx.send(());
1425 } else if self.disconnected {
1426 drop(tx);
1427 } else {
1428 match self
1429 .snapshot_subscriptions
1430 .binary_search_by_key(&scan_id, |probe| probe.0)
1431 {
1432 Ok(ix) | Err(ix) => self.snapshot_subscriptions.insert(ix, (scan_id, tx)),
1433 }
1434 }
1435
1436 async move {
1437 rx.await?;
1438 Ok(())
1439 }
1440 }
1441
1442 pub fn insert_entry(
1443 &mut self,
1444 entry: proto::Entry,
1445 scan_id: usize,
1446 cx: &mut ModelContext<Worktree>,
1447 ) -> Task<Result<Entry>> {
1448 let wait_for_snapshot = self.wait_for_snapshot(scan_id);
1449 cx.spawn(|this, mut cx| async move {
1450 wait_for_snapshot.await?;
1451 this.update(&mut cx, |worktree, _| {
1452 let worktree = worktree.as_remote_mut().unwrap();
1453 let mut snapshot = worktree.background_snapshot.lock();
1454 let entry = snapshot.insert_entry(entry);
1455 worktree.snapshot = snapshot.clone();
1456 entry
1457 })?
1458 })
1459 }
1460
1461 pub fn delete_entry(
1462 &mut self,
1463 id: ProjectEntryId,
1464 scan_id: usize,
1465 cx: &mut ModelContext<Worktree>,
1466 ) -> Task<Result<()>> {
1467 let wait_for_snapshot = self.wait_for_snapshot(scan_id);
1468 cx.spawn(move |this, mut cx| async move {
1469 wait_for_snapshot.await?;
1470 this.update(&mut cx, |worktree, _| {
1471 let worktree = worktree.as_remote_mut().unwrap();
1472 let mut snapshot = worktree.background_snapshot.lock();
1473 snapshot.delete_entry(id);
1474 worktree.snapshot = snapshot.clone();
1475 })?;
1476 Ok(())
1477 })
1478 }
1479}
1480
1481impl Snapshot {
1482 pub fn id(&self) -> WorktreeId {
1483 self.id
1484 }
1485
1486 pub fn abs_path(&self) -> &Arc<Path> {
1487 &self.abs_path
1488 }
1489
1490 pub fn absolutize(&self, path: &Path) -> Result<PathBuf> {
1491 if path
1492 .components()
1493 .any(|component| !matches!(component, std::path::Component::Normal(_)))
1494 {
1495 return Err(anyhow!("invalid path"));
1496 }
1497 if path.file_name().is_some() {
1498 Ok(self.abs_path.join(path))
1499 } else {
1500 Ok(self.abs_path.to_path_buf())
1501 }
1502 }
1503
1504 pub fn contains_entry(&self, entry_id: ProjectEntryId) -> bool {
1505 self.entries_by_id.get(&entry_id, &()).is_some()
1506 }
1507
1508 fn insert_entry(&mut self, entry: proto::Entry) -> Result<Entry> {
1509 let entry = Entry::try_from((&self.root_char_bag, entry))?;
1510 let old_entry = self.entries_by_id.insert_or_replace(
1511 PathEntry {
1512 id: entry.id,
1513 path: entry.path.clone(),
1514 is_ignored: entry.is_ignored,
1515 scan_id: 0,
1516 },
1517 &(),
1518 );
1519 if let Some(old_entry) = old_entry {
1520 self.entries_by_path.remove(&PathKey(old_entry.path), &());
1521 }
1522 self.entries_by_path.insert_or_replace(entry.clone(), &());
1523 Ok(entry)
1524 }
1525
1526 fn delete_entry(&mut self, entry_id: ProjectEntryId) -> Option<Arc<Path>> {
1527 let removed_entry = self.entries_by_id.remove(&entry_id, &())?;
1528 self.entries_by_path = {
1529 let mut cursor = self.entries_by_path.cursor::<TraversalProgress>();
1530 let mut new_entries_by_path =
1531 cursor.slice(&TraversalTarget::Path(&removed_entry.path), Bias::Left, &());
1532 while let Some(entry) = cursor.item() {
1533 if entry.path.starts_with(&removed_entry.path) {
1534 self.entries_by_id.remove(&entry.id, &());
1535 cursor.next(&());
1536 } else {
1537 break;
1538 }
1539 }
1540 new_entries_by_path.append(cursor.suffix(&()), &());
1541 new_entries_by_path
1542 };
1543
1544 Some(removed_entry.path)
1545 }
1546
1547 #[cfg(any(test, feature = "test-support"))]
1548 pub fn status_for_file(&self, path: impl Into<PathBuf>) -> Option<GitFileStatus> {
1549 let path = path.into();
1550 self.entries_by_path
1551 .get(&PathKey(Arc::from(path)), &())
1552 .and_then(|entry| entry.git_status)
1553 }
1554
1555 pub(crate) fn apply_remote_update(&mut self, mut update: proto::UpdateWorktree) -> Result<()> {
1556 let mut entries_by_path_edits = Vec::new();
1557 let mut entries_by_id_edits = Vec::new();
1558
1559 for entry_id in update.removed_entries {
1560 let entry_id = ProjectEntryId::from_proto(entry_id);
1561 entries_by_id_edits.push(Edit::Remove(entry_id));
1562 if let Some(entry) = self.entry_for_id(entry_id) {
1563 entries_by_path_edits.push(Edit::Remove(PathKey(entry.path.clone())));
1564 }
1565 }
1566
1567 for entry in update.updated_entries {
1568 let entry = Entry::try_from((&self.root_char_bag, entry))?;
1569 if let Some(PathEntry { path, .. }) = self.entries_by_id.get(&entry.id, &()) {
1570 entries_by_path_edits.push(Edit::Remove(PathKey(path.clone())));
1571 }
1572 if let Some(old_entry) = self.entries_by_path.get(&PathKey(entry.path.clone()), &()) {
1573 if old_entry.id != entry.id {
1574 entries_by_id_edits.push(Edit::Remove(old_entry.id));
1575 }
1576 }
1577 entries_by_id_edits.push(Edit::Insert(PathEntry {
1578 id: entry.id,
1579 path: entry.path.clone(),
1580 is_ignored: entry.is_ignored,
1581 scan_id: 0,
1582 }));
1583 entries_by_path_edits.push(Edit::Insert(entry));
1584 }
1585
1586 self.entries_by_path.edit(entries_by_path_edits, &());
1587 self.entries_by_id.edit(entries_by_id_edits, &());
1588
1589 update.removed_repositories.sort_unstable();
1590 self.repository_entries.retain(|_, entry| {
1591 if let Ok(_) = update
1592 .removed_repositories
1593 .binary_search(&entry.work_directory.to_proto())
1594 {
1595 false
1596 } else {
1597 true
1598 }
1599 });
1600
1601 for repository in update.updated_repositories {
1602 let work_directory_entry: WorkDirectoryEntry =
1603 ProjectEntryId::from_proto(repository.work_directory_id).into();
1604
1605 if let Some(entry) = self.entry_for_id(*work_directory_entry) {
1606 let work_directory = RepositoryWorkDirectory(entry.path.clone());
1607 if self.repository_entries.get(&work_directory).is_some() {
1608 self.repository_entries.update(&work_directory, |repo| {
1609 repo.branch = repository.branch.map(Into::into);
1610 });
1611 } else {
1612 self.repository_entries.insert(
1613 work_directory,
1614 RepositoryEntry {
1615 work_directory: work_directory_entry,
1616 branch: repository.branch.map(Into::into),
1617 // When syncing repository entries from a peer, we don't need
1618 // the location_in_repo field, since git operations don't happen locally
1619 // anyway.
1620 location_in_repo: None,
1621 },
1622 )
1623 }
1624 } else {
1625 log::error!("no work directory entry for repository {:?}", repository)
1626 }
1627 }
1628
1629 self.scan_id = update.scan_id as usize;
1630 if update.is_last_update {
1631 self.completed_scan_id = update.scan_id as usize;
1632 }
1633
1634 Ok(())
1635 }
1636
1637 pub fn file_count(&self) -> usize {
1638 self.entries_by_path.summary().file_count
1639 }
1640
1641 pub fn visible_file_count(&self) -> usize {
1642 self.entries_by_path.summary().non_ignored_file_count
1643 }
1644
1645 fn traverse_from_offset(
1646 &self,
1647 include_files: bool,
1648 include_dirs: bool,
1649 include_ignored: bool,
1650 start_offset: usize,
1651 ) -> Traversal {
1652 let mut cursor = self.entries_by_path.cursor();
1653 cursor.seek(
1654 &TraversalTarget::Count {
1655 count: start_offset,
1656 include_files,
1657 include_dirs,
1658 include_ignored,
1659 },
1660 Bias::Right,
1661 &(),
1662 );
1663 Traversal {
1664 cursor,
1665 include_files,
1666 include_dirs,
1667 include_ignored,
1668 }
1669 }
1670
1671 fn traverse_from_path(
1672 &self,
1673 include_files: bool,
1674 include_dirs: bool,
1675 include_ignored: bool,
1676 path: &Path,
1677 ) -> Traversal {
1678 Traversal::new(
1679 &self.entries_by_path,
1680 include_files,
1681 include_dirs,
1682 include_ignored,
1683 path,
1684 )
1685 }
1686
1687 pub fn files(&self, include_ignored: bool, start: usize) -> Traversal {
1688 self.traverse_from_offset(true, false, include_ignored, start)
1689 }
1690
1691 pub fn directories(&self, include_ignored: bool, start: usize) -> Traversal {
1692 self.traverse_from_offset(false, true, include_ignored, start)
1693 }
1694
1695 pub fn entries(&self, include_ignored: bool) -> Traversal {
1696 self.traverse_from_offset(true, true, include_ignored, 0)
1697 }
1698
1699 pub fn repositories(&self) -> impl Iterator<Item = (&Arc<Path>, &RepositoryEntry)> {
1700 self.repository_entries
1701 .iter()
1702 .map(|(path, entry)| (&path.0, entry))
1703 }
1704
1705 /// Get the repository whose work directory contains the given path.
1706 pub fn repository_for_work_directory(&self, path: &Path) -> Option<RepositoryEntry> {
1707 self.repository_entries
1708 .get(&RepositoryWorkDirectory(path.into()))
1709 .cloned()
1710 }
1711
1712 /// Get the repository whose work directory contains the given path.
1713 pub fn repository_for_path(&self, path: &Path) -> Option<RepositoryEntry> {
1714 self.repository_and_work_directory_for_path(path)
1715 .map(|e| e.1)
1716 }
1717
1718 pub fn repository_and_work_directory_for_path(
1719 &self,
1720 path: &Path,
1721 ) -> Option<(RepositoryWorkDirectory, RepositoryEntry)> {
1722 self.repository_entries
1723 .iter()
1724 .filter(|(workdir_path, _)| path.starts_with(workdir_path))
1725 .last()
1726 .map(|(path, repo)| (path.clone(), repo.clone()))
1727 }
1728
1729 /// Given an ordered iterator of entries, returns an iterator of those entries,
1730 /// along with their containing git repository.
1731 pub fn entries_with_repositories<'a>(
1732 &'a self,
1733 entries: impl 'a + Iterator<Item = &'a Entry>,
1734 ) -> impl 'a + Iterator<Item = (&'a Entry, Option<&'a RepositoryEntry>)> {
1735 let mut containing_repos = Vec::<(&Arc<Path>, &RepositoryEntry)>::new();
1736 let mut repositories = self.repositories().peekable();
1737 entries.map(move |entry| {
1738 while let Some((repo_path, _)) = containing_repos.last() {
1739 if entry.path.starts_with(repo_path) {
1740 break;
1741 } else {
1742 containing_repos.pop();
1743 }
1744 }
1745 while let Some((repo_path, _)) = repositories.peek() {
1746 if entry.path.starts_with(repo_path) {
1747 containing_repos.push(repositories.next().unwrap());
1748 } else {
1749 break;
1750 }
1751 }
1752 let repo = containing_repos.last().map(|(_, repo)| *repo);
1753 (entry, repo)
1754 })
1755 }
1756
1757 /// Updates the `git_status` of the given entries such that files'
1758 /// statuses bubble up to their ancestor directories.
1759 pub fn propagate_git_statuses(&self, result: &mut [Entry]) {
1760 let mut cursor = self
1761 .entries_by_path
1762 .cursor::<(TraversalProgress, GitStatuses)>();
1763 let mut entry_stack = Vec::<(usize, GitStatuses)>::new();
1764
1765 let mut result_ix = 0;
1766 loop {
1767 let next_entry = result.get(result_ix);
1768 let containing_entry = entry_stack.last().map(|(ix, _)| &result[*ix]);
1769
1770 let entry_to_finish = match (containing_entry, next_entry) {
1771 (Some(_), None) => entry_stack.pop(),
1772 (Some(containing_entry), Some(next_path)) => {
1773 if next_path.path.starts_with(&containing_entry.path) {
1774 None
1775 } else {
1776 entry_stack.pop()
1777 }
1778 }
1779 (None, Some(_)) => None,
1780 (None, None) => break,
1781 };
1782
1783 if let Some((entry_ix, prev_statuses)) = entry_to_finish {
1784 cursor.seek_forward(
1785 &TraversalTarget::PathSuccessor(&result[entry_ix].path),
1786 Bias::Left,
1787 &(),
1788 );
1789
1790 let statuses = cursor.start().1 - prev_statuses;
1791
1792 result[entry_ix].git_status = if statuses.conflict > 0 {
1793 Some(GitFileStatus::Conflict)
1794 } else if statuses.modified > 0 {
1795 Some(GitFileStatus::Modified)
1796 } else if statuses.added > 0 {
1797 Some(GitFileStatus::Added)
1798 } else {
1799 None
1800 };
1801 } else {
1802 if result[result_ix].is_dir() {
1803 cursor.seek_forward(
1804 &TraversalTarget::Path(&result[result_ix].path),
1805 Bias::Left,
1806 &(),
1807 );
1808 entry_stack.push((result_ix, cursor.start().1));
1809 }
1810 result_ix += 1;
1811 }
1812 }
1813 }
1814
1815 pub fn paths(&self) -> impl Iterator<Item = &Arc<Path>> {
1816 let empty_path = Path::new("");
1817 self.entries_by_path
1818 .cursor::<()>()
1819 .filter(move |entry| entry.path.as_ref() != empty_path)
1820 .map(|entry| &entry.path)
1821 }
1822
1823 pub fn child_entries<'a>(&'a self, parent_path: &'a Path) -> ChildEntriesIter<'a> {
1824 let mut cursor = self.entries_by_path.cursor();
1825 cursor.seek(&TraversalTarget::Path(parent_path), Bias::Right, &());
1826 let traversal = Traversal {
1827 cursor,
1828 include_files: true,
1829 include_dirs: true,
1830 include_ignored: true,
1831 };
1832 ChildEntriesIter {
1833 traversal,
1834 parent_path,
1835 }
1836 }
1837
1838 pub fn root_entry(&self) -> Option<&Entry> {
1839 self.entry_for_path("")
1840 }
1841
1842 pub fn root_name(&self) -> &str {
1843 &self.root_name
1844 }
1845
1846 pub fn root_git_entry(&self) -> Option<RepositoryEntry> {
1847 self.repository_entries
1848 .get(&RepositoryWorkDirectory(Path::new("").into()))
1849 .map(|entry| entry.to_owned())
1850 }
1851
1852 pub fn git_entries(&self) -> impl Iterator<Item = &RepositoryEntry> {
1853 self.repository_entries.values()
1854 }
1855
1856 pub fn scan_id(&self) -> usize {
1857 self.scan_id
1858 }
1859
1860 pub fn entry_for_path(&self, path: impl AsRef<Path>) -> Option<&Entry> {
1861 let path = path.as_ref();
1862 self.traverse_from_path(true, true, true, path)
1863 .entry()
1864 .and_then(|entry| {
1865 if entry.path.as_ref() == path {
1866 Some(entry)
1867 } else {
1868 None
1869 }
1870 })
1871 }
1872
1873 pub fn entry_for_id(&self, id: ProjectEntryId) -> Option<&Entry> {
1874 let entry = self.entries_by_id.get(&id, &())?;
1875 self.entry_for_path(&entry.path)
1876 }
1877
1878 pub fn inode_for_path(&self, path: impl AsRef<Path>) -> Option<u64> {
1879 self.entry_for_path(path.as_ref()).map(|e| e.inode)
1880 }
1881}
1882
1883impl LocalSnapshot {
1884 pub fn get_local_repo(&self, repo: &RepositoryEntry) -> Option<&LocalRepositoryEntry> {
1885 self.git_repositories.get(&repo.work_directory.0)
1886 }
1887
1888 pub fn repo_for_path(&self, path: &Path) -> Option<(RepositoryEntry, &LocalRepositoryEntry)> {
1889 let (_, repo_entry) = self.repository_and_work_directory_for_path(path)?;
1890 let work_directory_id = repo_entry.work_directory_id();
1891 Some((repo_entry, self.git_repositories.get(&work_directory_id)?))
1892 }
1893
1894 pub fn local_git_repo(&self, path: &Path) -> Option<Arc<dyn GitRepository>> {
1895 self.repo_for_path(path)
1896 .map(|(_, entry)| entry.repo_ptr.clone())
1897 }
1898
1899 fn build_update(
1900 &self,
1901 project_id: u64,
1902 worktree_id: u64,
1903 entry_changes: UpdatedEntriesSet,
1904 repo_changes: UpdatedGitRepositoriesSet,
1905 ) -> proto::UpdateWorktree {
1906 let mut updated_entries = Vec::new();
1907 let mut removed_entries = Vec::new();
1908 let mut updated_repositories = Vec::new();
1909 let mut removed_repositories = Vec::new();
1910
1911 for (_, entry_id, path_change) in entry_changes.iter() {
1912 if let PathChange::Removed = path_change {
1913 removed_entries.push(entry_id.0 as u64);
1914 } else if let Some(entry) = self.entry_for_id(*entry_id) {
1915 updated_entries.push(proto::Entry::from(entry));
1916 }
1917 }
1918
1919 for (work_dir_path, change) in repo_changes.iter() {
1920 let new_repo = self
1921 .repository_entries
1922 .get(&RepositoryWorkDirectory(work_dir_path.clone()));
1923 match (&change.old_repository, new_repo) {
1924 (Some(old_repo), Some(new_repo)) => {
1925 updated_repositories.push(new_repo.build_update(old_repo));
1926 }
1927 (None, Some(new_repo)) => {
1928 updated_repositories.push(proto::RepositoryEntry::from(new_repo));
1929 }
1930 (Some(old_repo), None) => {
1931 removed_repositories.push(old_repo.work_directory.0.to_proto());
1932 }
1933 _ => {}
1934 }
1935 }
1936
1937 removed_entries.sort_unstable();
1938 updated_entries.sort_unstable_by_key(|e| e.id);
1939 removed_repositories.sort_unstable();
1940 updated_repositories.sort_unstable_by_key(|e| e.work_directory_id);
1941
1942 // TODO - optimize, knowing that removed_entries are sorted.
1943 removed_entries.retain(|id| updated_entries.binary_search_by_key(id, |e| e.id).is_err());
1944
1945 proto::UpdateWorktree {
1946 project_id,
1947 worktree_id,
1948 abs_path: self.abs_path().to_string_lossy().into(),
1949 root_name: self.root_name().to_string(),
1950 updated_entries,
1951 removed_entries,
1952 scan_id: self.scan_id as u64,
1953 is_last_update: self.completed_scan_id == self.scan_id,
1954 updated_repositories,
1955 removed_repositories,
1956 }
1957 }
1958
1959 fn build_initial_update(&self, project_id: u64, worktree_id: u64) -> proto::UpdateWorktree {
1960 let mut updated_entries = self
1961 .entries_by_path
1962 .iter()
1963 .map(proto::Entry::from)
1964 .collect::<Vec<_>>();
1965 updated_entries.sort_unstable_by_key(|e| e.id);
1966
1967 let mut updated_repositories = self
1968 .repository_entries
1969 .values()
1970 .map(proto::RepositoryEntry::from)
1971 .collect::<Vec<_>>();
1972 updated_repositories.sort_unstable_by_key(|e| e.work_directory_id);
1973
1974 proto::UpdateWorktree {
1975 project_id,
1976 worktree_id,
1977 abs_path: self.abs_path().to_string_lossy().into(),
1978 root_name: self.root_name().to_string(),
1979 updated_entries,
1980 removed_entries: Vec::new(),
1981 scan_id: self.scan_id as u64,
1982 is_last_update: self.completed_scan_id == self.scan_id,
1983 updated_repositories,
1984 removed_repositories: Vec::new(),
1985 }
1986 }
1987
1988 fn insert_entry(&mut self, mut entry: Entry, fs: &dyn Fs) -> Entry {
1989 if entry.is_file() && entry.path.file_name() == Some(&GITIGNORE) {
1990 let abs_path = self.abs_path.join(&entry.path);
1991 match smol::block_on(build_gitignore(&abs_path, fs)) {
1992 Ok(ignore) => {
1993 self.ignores_by_parent_abs_path
1994 .insert(abs_path.parent().unwrap().into(), (Arc::new(ignore), true));
1995 }
1996 Err(error) => {
1997 log::error!(
1998 "error loading .gitignore file {:?} - {:?}",
1999 &entry.path,
2000 error
2001 );
2002 }
2003 }
2004 }
2005
2006 if entry.kind == EntryKind::PendingDir {
2007 if let Some(existing_entry) =
2008 self.entries_by_path.get(&PathKey(entry.path.clone()), &())
2009 {
2010 entry.kind = existing_entry.kind;
2011 }
2012 }
2013
2014 let scan_id = self.scan_id;
2015 let removed = self.entries_by_path.insert_or_replace(entry.clone(), &());
2016 if let Some(removed) = removed {
2017 if removed.id != entry.id {
2018 self.entries_by_id.remove(&removed.id, &());
2019 }
2020 }
2021 self.entries_by_id.insert_or_replace(
2022 PathEntry {
2023 id: entry.id,
2024 path: entry.path.clone(),
2025 is_ignored: entry.is_ignored,
2026 scan_id,
2027 },
2028 &(),
2029 );
2030
2031 entry
2032 }
2033
2034 fn ancestor_inodes_for_path(&self, path: &Path) -> TreeSet<u64> {
2035 let mut inodes = TreeSet::default();
2036 for ancestor in path.ancestors().skip(1) {
2037 if let Some(entry) = self.entry_for_path(ancestor) {
2038 inodes.insert(entry.inode);
2039 }
2040 }
2041 inodes
2042 }
2043
2044 fn ignore_stack_for_abs_path(&self, abs_path: &Path, is_dir: bool) -> Arc<IgnoreStack> {
2045 let mut new_ignores = Vec::new();
2046 for (index, ancestor) in abs_path.ancestors().enumerate() {
2047 if index > 0 {
2048 if let Some((ignore, _)) = self.ignores_by_parent_abs_path.get(ancestor) {
2049 new_ignores.push((ancestor, Some(ignore.clone())));
2050 } else {
2051 new_ignores.push((ancestor, None));
2052 }
2053 }
2054 if ancestor.join(&*DOT_GIT).is_dir() {
2055 break;
2056 }
2057 }
2058
2059 let mut ignore_stack = IgnoreStack::none();
2060 for (parent_abs_path, ignore) in new_ignores.into_iter().rev() {
2061 if ignore_stack.is_abs_path_ignored(parent_abs_path, true) {
2062 ignore_stack = IgnoreStack::all();
2063 break;
2064 } else if let Some(ignore) = ignore {
2065 ignore_stack = ignore_stack.append(parent_abs_path.into(), ignore);
2066 }
2067 }
2068
2069 if ignore_stack.is_abs_path_ignored(abs_path, is_dir) {
2070 ignore_stack = IgnoreStack::all();
2071 }
2072
2073 ignore_stack
2074 }
2075
2076 #[cfg(test)]
2077 pub(crate) fn expanded_entries(&self) -> impl Iterator<Item = &Entry> {
2078 self.entries_by_path
2079 .cursor::<()>()
2080 .filter(|entry| entry.kind == EntryKind::Dir && (entry.is_external || entry.is_ignored))
2081 }
2082
2083 #[cfg(test)]
2084 pub fn check_invariants(&self, git_state: bool) {
2085 use pretty_assertions::assert_eq;
2086
2087 assert_eq!(
2088 self.entries_by_path
2089 .cursor::<()>()
2090 .map(|e| (&e.path, e.id))
2091 .collect::<Vec<_>>(),
2092 self.entries_by_id
2093 .cursor::<()>()
2094 .map(|e| (&e.path, e.id))
2095 .collect::<collections::BTreeSet<_>>()
2096 .into_iter()
2097 .collect::<Vec<_>>(),
2098 "entries_by_path and entries_by_id are inconsistent"
2099 );
2100
2101 let mut files = self.files(true, 0);
2102 let mut visible_files = self.files(false, 0);
2103 for entry in self.entries_by_path.cursor::<()>() {
2104 if entry.is_file() {
2105 assert_eq!(files.next().unwrap().inode, entry.inode);
2106 if !entry.is_ignored && !entry.is_external {
2107 assert_eq!(visible_files.next().unwrap().inode, entry.inode);
2108 }
2109 }
2110 }
2111
2112 assert!(files.next().is_none());
2113 assert!(visible_files.next().is_none());
2114
2115 let mut bfs_paths = Vec::new();
2116 let mut stack = self
2117 .root_entry()
2118 .map(|e| e.path.as_ref())
2119 .into_iter()
2120 .collect::<Vec<_>>();
2121 while let Some(path) = stack.pop() {
2122 bfs_paths.push(path);
2123 let ix = stack.len();
2124 for child_entry in self.child_entries(path) {
2125 stack.insert(ix, &child_entry.path);
2126 }
2127 }
2128
2129 let dfs_paths_via_iter = self
2130 .entries_by_path
2131 .cursor::<()>()
2132 .map(|e| e.path.as_ref())
2133 .collect::<Vec<_>>();
2134 assert_eq!(bfs_paths, dfs_paths_via_iter);
2135
2136 let dfs_paths_via_traversal = self
2137 .entries(true)
2138 .map(|e| e.path.as_ref())
2139 .collect::<Vec<_>>();
2140 assert_eq!(dfs_paths_via_traversal, dfs_paths_via_iter);
2141
2142 if git_state {
2143 for ignore_parent_abs_path in self.ignores_by_parent_abs_path.keys() {
2144 let ignore_parent_path =
2145 ignore_parent_abs_path.strip_prefix(&self.abs_path).unwrap();
2146 assert!(self.entry_for_path(&ignore_parent_path).is_some());
2147 assert!(self
2148 .entry_for_path(ignore_parent_path.join(&*GITIGNORE))
2149 .is_some());
2150 }
2151 }
2152 }
2153
2154 #[cfg(test)]
2155 pub fn entries_without_ids(&self, include_ignored: bool) -> Vec<(&Path, u64, bool)> {
2156 let mut paths = Vec::new();
2157 for entry in self.entries_by_path.cursor::<()>() {
2158 if include_ignored || !entry.is_ignored {
2159 paths.push((entry.path.as_ref(), entry.inode, entry.is_ignored));
2160 }
2161 }
2162 paths.sort_by(|a, b| a.0.cmp(b.0));
2163 paths
2164 }
2165
2166 pub fn is_path_private(&self, path: &Path) -> bool {
2167 if self.share_private_files {
2168 return false;
2169 }
2170 path.ancestors().any(|ancestor| {
2171 self.private_files
2172 .iter()
2173 .any(|exclude_matcher| exclude_matcher.is_match(&ancestor))
2174 })
2175 }
2176
2177 pub fn is_path_excluded(&self, path: &Path) -> bool {
2178 path.ancestors().any(|path| {
2179 self.file_scan_exclusions
2180 .iter()
2181 .any(|exclude_matcher| exclude_matcher.is_match(&path))
2182 })
2183 }
2184}
2185
2186impl BackgroundScannerState {
2187 fn should_scan_directory(&self, entry: &Entry) -> bool {
2188 (!entry.is_external && !entry.is_ignored)
2189 || entry.path.file_name() == Some(*DOT_GIT)
2190 || self.scanned_dirs.contains(&entry.id) // If we've ever scanned it, keep scanning
2191 || self
2192 .paths_to_scan
2193 .iter()
2194 .any(|p| p.starts_with(&entry.path))
2195 || self
2196 .path_prefixes_to_scan
2197 .iter()
2198 .any(|p| entry.path.starts_with(p))
2199 }
2200
2201 fn enqueue_scan_dir(&self, abs_path: Arc<Path>, entry: &Entry, scan_job_tx: &Sender<ScanJob>) {
2202 let path = entry.path.clone();
2203 let ignore_stack = self.snapshot.ignore_stack_for_abs_path(&abs_path, true);
2204 let mut ancestor_inodes = self.snapshot.ancestor_inodes_for_path(&path);
2205 let mut containing_repository = None;
2206 if !ignore_stack.is_abs_path_ignored(&abs_path, true) {
2207 if let Some((repo_entry, repo)) = self.snapshot.repo_for_path(&path) {
2208 if let Some(workdir_path) = repo_entry.work_directory(&self.snapshot) {
2209 if let Ok(repo_path) = repo_entry.relativize(&self.snapshot, &path) {
2210 containing_repository = Some(ScanJobContainingRepository {
2211 work_directory: workdir_path,
2212 statuses: repo
2213 .repo_ptr
2214 .statuses(&repo_path)
2215 .log_err()
2216 .unwrap_or_default(),
2217 });
2218 }
2219 }
2220 }
2221 }
2222 if !ancestor_inodes.contains(&entry.inode) {
2223 ancestor_inodes.insert(entry.inode);
2224 scan_job_tx
2225 .try_send(ScanJob {
2226 abs_path,
2227 path,
2228 ignore_stack,
2229 scan_queue: scan_job_tx.clone(),
2230 ancestor_inodes,
2231 is_external: entry.is_external,
2232 containing_repository,
2233 })
2234 .unwrap();
2235 }
2236 }
2237
2238 fn reuse_entry_id(&mut self, entry: &mut Entry) {
2239 if let Some(removed_entry_id) = self.removed_entry_ids.remove(&entry.inode) {
2240 entry.id = removed_entry_id;
2241 } else if let Some(existing_entry) = self.snapshot.entry_for_path(&entry.path) {
2242 entry.id = existing_entry.id;
2243 }
2244 }
2245
2246 fn insert_entry(&mut self, mut entry: Entry, fs: &dyn Fs) -> Entry {
2247 self.reuse_entry_id(&mut entry);
2248 let entry = self.snapshot.insert_entry(entry, fs);
2249 if entry.path.file_name() == Some(&DOT_GIT) {
2250 self.build_git_repository(entry.path.clone(), fs);
2251 }
2252
2253 #[cfg(test)]
2254 self.snapshot.check_invariants(false);
2255
2256 entry
2257 }
2258
2259 fn populate_dir(
2260 &mut self,
2261 parent_path: &Arc<Path>,
2262 entries: impl IntoIterator<Item = Entry>,
2263 ignore: Option<Arc<Gitignore>>,
2264 ) {
2265 let mut parent_entry = if let Some(parent_entry) = self
2266 .snapshot
2267 .entries_by_path
2268 .get(&PathKey(parent_path.clone()), &())
2269 {
2270 parent_entry.clone()
2271 } else {
2272 log::warn!(
2273 "populating a directory {:?} that has been removed",
2274 parent_path
2275 );
2276 return;
2277 };
2278
2279 match parent_entry.kind {
2280 EntryKind::PendingDir | EntryKind::UnloadedDir => parent_entry.kind = EntryKind::Dir,
2281 EntryKind::Dir => {}
2282 _ => return,
2283 }
2284
2285 if let Some(ignore) = ignore {
2286 let abs_parent_path = self.snapshot.abs_path.join(&parent_path).into();
2287 self.snapshot
2288 .ignores_by_parent_abs_path
2289 .insert(abs_parent_path, (ignore, false));
2290 }
2291
2292 let parent_entry_id = parent_entry.id;
2293 self.scanned_dirs.insert(parent_entry_id);
2294 let mut entries_by_path_edits = vec![Edit::Insert(parent_entry)];
2295 let mut entries_by_id_edits = Vec::new();
2296
2297 for entry in entries {
2298 entries_by_id_edits.push(Edit::Insert(PathEntry {
2299 id: entry.id,
2300 path: entry.path.clone(),
2301 is_ignored: entry.is_ignored,
2302 scan_id: self.snapshot.scan_id,
2303 }));
2304 entries_by_path_edits.push(Edit::Insert(entry));
2305 }
2306
2307 self.snapshot
2308 .entries_by_path
2309 .edit(entries_by_path_edits, &());
2310 self.snapshot.entries_by_id.edit(entries_by_id_edits, &());
2311
2312 if let Err(ix) = self.changed_paths.binary_search(parent_path) {
2313 self.changed_paths.insert(ix, parent_path.clone());
2314 }
2315
2316 #[cfg(test)]
2317 self.snapshot.check_invariants(false);
2318 }
2319
2320 fn remove_path(&mut self, path: &Path) {
2321 let mut new_entries;
2322 let removed_entries;
2323 {
2324 let mut cursor = self.snapshot.entries_by_path.cursor::<TraversalProgress>();
2325 new_entries = cursor.slice(&TraversalTarget::Path(path), Bias::Left, &());
2326 removed_entries = cursor.slice(&TraversalTarget::PathSuccessor(path), Bias::Left, &());
2327 new_entries.append(cursor.suffix(&()), &());
2328 }
2329 self.snapshot.entries_by_path = new_entries;
2330
2331 let mut entries_by_id_edits = Vec::new();
2332 for entry in removed_entries.cursor::<()>() {
2333 let removed_entry_id = self
2334 .removed_entry_ids
2335 .entry(entry.inode)
2336 .or_insert(entry.id);
2337 *removed_entry_id = cmp::max(*removed_entry_id, entry.id);
2338 entries_by_id_edits.push(Edit::Remove(entry.id));
2339 }
2340 self.snapshot.entries_by_id.edit(entries_by_id_edits, &());
2341
2342 if path.file_name() == Some(&GITIGNORE) {
2343 let abs_parent_path = self.snapshot.abs_path.join(path.parent().unwrap());
2344 if let Some((_, needs_update)) = self
2345 .snapshot
2346 .ignores_by_parent_abs_path
2347 .get_mut(abs_parent_path.as_path())
2348 {
2349 *needs_update = true;
2350 }
2351 }
2352
2353 #[cfg(test)]
2354 self.snapshot.check_invariants(false);
2355 }
2356
2357 fn build_git_repository(
2358 &mut self,
2359 dot_git_path: Arc<Path>,
2360 fs: &dyn Fs,
2361 ) -> Option<(RepositoryWorkDirectory, Arc<dyn GitRepository>)> {
2362 let work_dir_path: Arc<Path> = match dot_git_path.parent() {
2363 Some(parent_dir) => {
2364 // Guard against repositories inside the repository metadata
2365 if parent_dir.iter().any(|component| component == *DOT_GIT) {
2366 log::info!(
2367 "not building git repository for nested `.git` directory, `.git` path in the worktree: {dot_git_path:?}"
2368 );
2369 return None;
2370 };
2371 log::info!(
2372 "building git repository, `.git` path in the worktree: {dot_git_path:?}"
2373 );
2374
2375 parent_dir.into()
2376 }
2377 None => {
2378 // `dot_git_path.parent().is_none()` means `.git` directory is the opened worktree itself,
2379 // no files inside that directory are tracked by git, so no need to build the repo around it
2380 log::info!(
2381 "not building git repository for the worktree itself, `.git` path in the worktree: {dot_git_path:?}"
2382 );
2383 return None;
2384 }
2385 };
2386
2387 self.build_git_repository_for_path(work_dir_path, dot_git_path, None, fs)
2388 }
2389
2390 fn build_git_repository_for_path(
2391 &mut self,
2392 work_dir_path: Arc<Path>,
2393 dot_git_path: Arc<Path>,
2394 location_in_repo: Option<Arc<Path>>,
2395 fs: &dyn Fs,
2396 ) -> Option<(RepositoryWorkDirectory, Arc<dyn GitRepository>)> {
2397 let work_dir_id = self
2398 .snapshot
2399 .entry_for_path(work_dir_path.clone())
2400 .map(|entry| entry.id)?;
2401
2402 if self.snapshot.git_repositories.get(&work_dir_id).is_some() {
2403 return None;
2404 }
2405
2406 let abs_path = self.snapshot.abs_path.join(&dot_git_path);
2407 let t0 = Instant::now();
2408 let repository = fs.open_repo(&abs_path)?;
2409 log::trace!("constructed libgit2 repo in {:?}", t0.elapsed());
2410 let work_directory = RepositoryWorkDirectory(work_dir_path.clone());
2411
2412 self.snapshot.repository_entries.insert(
2413 work_directory.clone(),
2414 RepositoryEntry {
2415 work_directory: work_dir_id.into(),
2416 branch: repository.branch_name().map(Into::into),
2417 location_in_repo,
2418 },
2419 );
2420 self.snapshot.git_repositories.insert(
2421 work_dir_id,
2422 LocalRepositoryEntry {
2423 git_dir_scan_id: 0,
2424 repo_ptr: repository.clone(),
2425 git_dir_path: dot_git_path.clone(),
2426 },
2427 );
2428
2429 Some((work_directory, repository))
2430 }
2431}
2432
2433async fn build_gitignore(abs_path: &Path, fs: &dyn Fs) -> Result<Gitignore> {
2434 let contents = fs.load(abs_path).await?;
2435 let parent = abs_path.parent().unwrap_or_else(|| Path::new("/"));
2436 let mut builder = GitignoreBuilder::new(parent);
2437 for line in contents.lines() {
2438 builder.add_line(Some(abs_path.into()), line)?;
2439 }
2440 Ok(builder.build()?)
2441}
2442
2443impl WorktreeId {
2444 pub fn from_usize(handle_id: usize) -> Self {
2445 Self(handle_id)
2446 }
2447
2448 pub fn from_proto(id: u64) -> Self {
2449 Self(id as usize)
2450 }
2451
2452 pub fn to_proto(&self) -> u64 {
2453 self.0 as u64
2454 }
2455
2456 pub fn to_usize(&self) -> usize {
2457 self.0
2458 }
2459}
2460
2461impl fmt::Display for WorktreeId {
2462 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2463 self.0.fmt(f)
2464 }
2465}
2466
2467impl Deref for Worktree {
2468 type Target = Snapshot;
2469
2470 fn deref(&self) -> &Self::Target {
2471 match self {
2472 Worktree::Local(worktree) => &worktree.snapshot,
2473 Worktree::Remote(worktree) => &worktree.snapshot,
2474 }
2475 }
2476}
2477
2478impl Deref for LocalWorktree {
2479 type Target = LocalSnapshot;
2480
2481 fn deref(&self) -> &Self::Target {
2482 &self.snapshot
2483 }
2484}
2485
2486impl Deref for RemoteWorktree {
2487 type Target = Snapshot;
2488
2489 fn deref(&self) -> &Self::Target {
2490 &self.snapshot
2491 }
2492}
2493
2494impl fmt::Debug for LocalWorktree {
2495 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2496 self.snapshot.fmt(f)
2497 }
2498}
2499
2500impl fmt::Debug for Snapshot {
2501 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2502 struct EntriesById<'a>(&'a SumTree<PathEntry>);
2503 struct EntriesByPath<'a>(&'a SumTree<Entry>);
2504
2505 impl<'a> fmt::Debug for EntriesByPath<'a> {
2506 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2507 f.debug_map()
2508 .entries(self.0.iter().map(|entry| (&entry.path, entry.id)))
2509 .finish()
2510 }
2511 }
2512
2513 impl<'a> fmt::Debug for EntriesById<'a> {
2514 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2515 f.debug_list().entries(self.0.iter()).finish()
2516 }
2517 }
2518
2519 f.debug_struct("Snapshot")
2520 .field("id", &self.id)
2521 .field("root_name", &self.root_name)
2522 .field("entries_by_path", &EntriesByPath(&self.entries_by_path))
2523 .field("entries_by_id", &EntriesById(&self.entries_by_id))
2524 .finish()
2525 }
2526}
2527
2528#[derive(Clone, PartialEq)]
2529pub struct File {
2530 pub worktree: Model<Worktree>,
2531 pub path: Arc<Path>,
2532 pub mtime: Option<SystemTime>,
2533 pub entry_id: Option<ProjectEntryId>,
2534 pub is_local: bool,
2535 pub is_deleted: bool,
2536 pub is_private: bool,
2537}
2538
2539impl language::File for File {
2540 fn as_local(&self) -> Option<&dyn language::LocalFile> {
2541 if self.is_local {
2542 Some(self)
2543 } else {
2544 None
2545 }
2546 }
2547
2548 fn mtime(&self) -> Option<SystemTime> {
2549 self.mtime
2550 }
2551
2552 fn path(&self) -> &Arc<Path> {
2553 &self.path
2554 }
2555
2556 fn full_path(&self, cx: &AppContext) -> PathBuf {
2557 let mut full_path = PathBuf::new();
2558 let worktree = self.worktree.read(cx);
2559
2560 if worktree.is_visible() {
2561 full_path.push(worktree.root_name());
2562 } else {
2563 let path = worktree.abs_path();
2564
2565 if worktree.is_local() && path.starts_with(HOME.as_path()) {
2566 full_path.push("~");
2567 full_path.push(path.strip_prefix(HOME.as_path()).unwrap());
2568 } else {
2569 full_path.push(path)
2570 }
2571 }
2572
2573 if self.path.components().next().is_some() {
2574 full_path.push(&self.path);
2575 }
2576
2577 full_path
2578 }
2579
2580 /// Returns the last component of this handle's absolute path. If this handle refers to the root
2581 /// of its worktree, then this method will return the name of the worktree itself.
2582 fn file_name<'a>(&'a self, cx: &'a AppContext) -> &'a OsStr {
2583 self.path
2584 .file_name()
2585 .unwrap_or_else(|| OsStr::new(&self.worktree.read(cx).root_name))
2586 }
2587
2588 fn worktree_id(&self) -> usize {
2589 self.worktree.entity_id().as_u64() as usize
2590 }
2591
2592 fn is_deleted(&self) -> bool {
2593 self.is_deleted
2594 }
2595
2596 fn as_any(&self) -> &dyn Any {
2597 self
2598 }
2599
2600 fn to_proto(&self) -> rpc::proto::File {
2601 rpc::proto::File {
2602 worktree_id: self.worktree.entity_id().as_u64(),
2603 entry_id: self.entry_id.map(|id| id.to_proto()),
2604 path: self.path.to_string_lossy().into(),
2605 mtime: self.mtime.map(|time| time.into()),
2606 is_deleted: self.is_deleted,
2607 }
2608 }
2609
2610 fn is_private(&self) -> bool {
2611 self.is_private
2612 }
2613}
2614
2615impl language::LocalFile for File {
2616 fn abs_path(&self, cx: &AppContext) -> PathBuf {
2617 let worktree_path = &self.worktree.read(cx).as_local().unwrap().abs_path;
2618 if self.path.as_ref() == Path::new("") {
2619 worktree_path.to_path_buf()
2620 } else {
2621 worktree_path.join(&self.path)
2622 }
2623 }
2624
2625 fn load(&self, cx: &AppContext) -> Task<Result<String>> {
2626 let worktree = self.worktree.read(cx).as_local().unwrap();
2627 let abs_path = worktree.absolutize(&self.path);
2628 let fs = worktree.fs.clone();
2629 cx.background_executor()
2630 .spawn(async move { fs.load(&abs_path?).await })
2631 }
2632}
2633
2634impl File {
2635 pub fn for_entry(entry: Entry, worktree: Model<Worktree>) -> Arc<Self> {
2636 Arc::new(Self {
2637 worktree,
2638 path: entry.path.clone(),
2639 mtime: entry.mtime,
2640 entry_id: Some(entry.id),
2641 is_local: true,
2642 is_deleted: false,
2643 is_private: entry.is_private,
2644 })
2645 }
2646
2647 pub fn from_proto(
2648 proto: rpc::proto::File,
2649 worktree: Model<Worktree>,
2650 cx: &AppContext,
2651 ) -> Result<Self> {
2652 let worktree_id = worktree
2653 .read(cx)
2654 .as_remote()
2655 .ok_or_else(|| anyhow!("not remote"))?
2656 .id();
2657
2658 if worktree_id.to_proto() != proto.worktree_id {
2659 return Err(anyhow!("worktree id does not match file"));
2660 }
2661
2662 Ok(Self {
2663 worktree,
2664 path: Path::new(&proto.path).into(),
2665 mtime: proto.mtime.map(|time| time.into()),
2666 entry_id: proto.entry_id.map(ProjectEntryId::from_proto),
2667 is_local: false,
2668 is_deleted: proto.is_deleted,
2669 is_private: false,
2670 })
2671 }
2672
2673 pub fn from_dyn(file: Option<&Arc<dyn language::File>>) -> Option<&Self> {
2674 file.and_then(|f| f.as_any().downcast_ref())
2675 }
2676
2677 pub fn worktree_id(&self, cx: &AppContext) -> WorktreeId {
2678 self.worktree.read(cx).id()
2679 }
2680
2681 pub fn project_entry_id(&self, _: &AppContext) -> Option<ProjectEntryId> {
2682 if self.is_deleted {
2683 None
2684 } else {
2685 self.entry_id
2686 }
2687 }
2688}
2689
2690#[derive(Clone, Debug, PartialEq, Eq)]
2691pub struct Entry {
2692 pub id: ProjectEntryId,
2693 pub kind: EntryKind,
2694 pub path: Arc<Path>,
2695 pub inode: u64,
2696 pub mtime: Option<SystemTime>,
2697
2698 pub canonical_path: Option<PathBuf>,
2699 pub is_symlink: bool,
2700 /// Whether this entry is ignored by Git.
2701 ///
2702 /// We only scan ignored entries once the directory is expanded and
2703 /// exclude them from searches.
2704 pub is_ignored: bool,
2705
2706 /// Whether this entry's canonical path is outside of the worktree.
2707 /// This means the entry is only accessible from the worktree root via a
2708 /// symlink.
2709 ///
2710 /// We only scan entries outside of the worktree once the symlinked
2711 /// directory is expanded. External entries are treated like gitignored
2712 /// entries in that they are not included in searches.
2713 pub is_external: bool,
2714 pub git_status: Option<GitFileStatus>,
2715 /// Whether this entry is considered to be a `.env` file.
2716 pub is_private: bool,
2717}
2718
2719#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2720pub enum EntryKind {
2721 UnloadedDir,
2722 PendingDir,
2723 Dir,
2724 File(CharBag),
2725}
2726
2727#[derive(Clone, Copy, Debug, PartialEq)]
2728pub enum PathChange {
2729 /// A filesystem entry was was created.
2730 Added,
2731 /// A filesystem entry was removed.
2732 Removed,
2733 /// A filesystem entry was updated.
2734 Updated,
2735 /// A filesystem entry was either updated or added. We don't know
2736 /// whether or not it already existed, because the path had not
2737 /// been loaded before the event.
2738 AddedOrUpdated,
2739 /// A filesystem entry was found during the initial scan of the worktree.
2740 Loaded,
2741}
2742
2743pub struct GitRepositoryChange {
2744 /// The previous state of the repository, if it already existed.
2745 pub old_repository: Option<RepositoryEntry>,
2746}
2747
2748pub type UpdatedEntriesSet = Arc<[(Arc<Path>, ProjectEntryId, PathChange)]>;
2749pub type UpdatedGitRepositoriesSet = Arc<[(Arc<Path>, GitRepositoryChange)]>;
2750
2751impl Entry {
2752 fn new(
2753 path: Arc<Path>,
2754 metadata: &fs::Metadata,
2755 next_entry_id: &AtomicUsize,
2756 root_char_bag: CharBag,
2757 canonical_path: Option<PathBuf>,
2758 ) -> Self {
2759 Self {
2760 id: ProjectEntryId::new(next_entry_id),
2761 kind: if metadata.is_dir {
2762 EntryKind::PendingDir
2763 } else {
2764 EntryKind::File(char_bag_for_path(root_char_bag, &path))
2765 },
2766 path,
2767 inode: metadata.inode,
2768 mtime: Some(metadata.mtime),
2769 canonical_path,
2770 is_symlink: metadata.is_symlink,
2771 is_ignored: false,
2772 is_external: false,
2773 is_private: false,
2774 git_status: None,
2775 }
2776 }
2777
2778 pub fn is_created(&self) -> bool {
2779 self.mtime.is_some()
2780 }
2781
2782 pub fn is_dir(&self) -> bool {
2783 self.kind.is_dir()
2784 }
2785
2786 pub fn is_file(&self) -> bool {
2787 self.kind.is_file()
2788 }
2789
2790 pub fn git_status(&self) -> Option<GitFileStatus> {
2791 self.git_status
2792 }
2793}
2794
2795impl EntryKind {
2796 pub fn is_dir(&self) -> bool {
2797 matches!(
2798 self,
2799 EntryKind::Dir | EntryKind::PendingDir | EntryKind::UnloadedDir
2800 )
2801 }
2802
2803 pub fn is_unloaded(&self) -> bool {
2804 matches!(self, EntryKind::UnloadedDir)
2805 }
2806
2807 pub fn is_file(&self) -> bool {
2808 matches!(self, EntryKind::File(_))
2809 }
2810}
2811
2812impl sum_tree::Item for Entry {
2813 type Summary = EntrySummary;
2814
2815 fn summary(&self) -> Self::Summary {
2816 let non_ignored_count = if self.is_ignored || self.is_external {
2817 0
2818 } else {
2819 1
2820 };
2821 let file_count;
2822 let non_ignored_file_count;
2823 if self.is_file() {
2824 file_count = 1;
2825 non_ignored_file_count = non_ignored_count;
2826 } else {
2827 file_count = 0;
2828 non_ignored_file_count = 0;
2829 }
2830
2831 let mut statuses = GitStatuses::default();
2832 match self.git_status {
2833 Some(status) => match status {
2834 GitFileStatus::Added => statuses.added = 1,
2835 GitFileStatus::Modified => statuses.modified = 1,
2836 GitFileStatus::Conflict => statuses.conflict = 1,
2837 },
2838 None => {}
2839 }
2840
2841 EntrySummary {
2842 max_path: self.path.clone(),
2843 count: 1,
2844 non_ignored_count,
2845 file_count,
2846 non_ignored_file_count,
2847 statuses,
2848 }
2849 }
2850}
2851
2852impl sum_tree::KeyedItem for Entry {
2853 type Key = PathKey;
2854
2855 fn key(&self) -> Self::Key {
2856 PathKey(self.path.clone())
2857 }
2858}
2859
2860#[derive(Clone, Debug)]
2861pub struct EntrySummary {
2862 max_path: Arc<Path>,
2863 count: usize,
2864 non_ignored_count: usize,
2865 file_count: usize,
2866 non_ignored_file_count: usize,
2867 statuses: GitStatuses,
2868}
2869
2870impl Default for EntrySummary {
2871 fn default() -> Self {
2872 Self {
2873 max_path: Arc::from(Path::new("")),
2874 count: 0,
2875 non_ignored_count: 0,
2876 file_count: 0,
2877 non_ignored_file_count: 0,
2878 statuses: Default::default(),
2879 }
2880 }
2881}
2882
2883impl sum_tree::Summary for EntrySummary {
2884 type Context = ();
2885
2886 fn add_summary(&mut self, rhs: &Self, _: &()) {
2887 self.max_path = rhs.max_path.clone();
2888 self.count += rhs.count;
2889 self.non_ignored_count += rhs.non_ignored_count;
2890 self.file_count += rhs.file_count;
2891 self.non_ignored_file_count += rhs.non_ignored_file_count;
2892 self.statuses += rhs.statuses;
2893 }
2894}
2895
2896#[derive(Clone, Debug)]
2897struct PathEntry {
2898 id: ProjectEntryId,
2899 path: Arc<Path>,
2900 is_ignored: bool,
2901 scan_id: usize,
2902}
2903
2904impl sum_tree::Item for PathEntry {
2905 type Summary = PathEntrySummary;
2906
2907 fn summary(&self) -> Self::Summary {
2908 PathEntrySummary { max_id: self.id }
2909 }
2910}
2911
2912impl sum_tree::KeyedItem for PathEntry {
2913 type Key = ProjectEntryId;
2914
2915 fn key(&self) -> Self::Key {
2916 self.id
2917 }
2918}
2919
2920#[derive(Clone, Debug, Default)]
2921struct PathEntrySummary {
2922 max_id: ProjectEntryId,
2923}
2924
2925impl sum_tree::Summary for PathEntrySummary {
2926 type Context = ();
2927
2928 fn add_summary(&mut self, summary: &Self, _: &Self::Context) {
2929 self.max_id = summary.max_id;
2930 }
2931}
2932
2933impl<'a> sum_tree::Dimension<'a, PathEntrySummary> for ProjectEntryId {
2934 fn add_summary(&mut self, summary: &'a PathEntrySummary, _: &()) {
2935 *self = summary.max_id;
2936 }
2937}
2938
2939#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
2940pub struct PathKey(Arc<Path>);
2941
2942impl Default for PathKey {
2943 fn default() -> Self {
2944 Self(Path::new("").into())
2945 }
2946}
2947
2948impl<'a> sum_tree::Dimension<'a, EntrySummary> for PathKey {
2949 fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
2950 self.0 = summary.max_path.clone();
2951 }
2952}
2953
2954struct BackgroundScanner {
2955 state: Mutex<BackgroundScannerState>,
2956 fs: Arc<dyn Fs>,
2957 fs_case_sensitive: bool,
2958 status_updates_tx: UnboundedSender<ScanState>,
2959 executor: BackgroundExecutor,
2960 scan_requests_rx: channel::Receiver<ScanRequest>,
2961 path_prefixes_to_scan_rx: channel::Receiver<Arc<Path>>,
2962 next_entry_id: Arc<AtomicUsize>,
2963 phase: BackgroundScannerPhase,
2964 watcher: Arc<dyn Watcher>,
2965}
2966
2967#[derive(PartialEq)]
2968enum BackgroundScannerPhase {
2969 InitialScan,
2970 EventsReceivedDuringInitialScan,
2971 Events,
2972}
2973
2974impl BackgroundScanner {
2975 async fn run(&mut self, mut fs_events_rx: Pin<Box<dyn Send + Stream<Item = Vec<PathBuf>>>>) {
2976 use futures::FutureExt as _;
2977
2978 // If the worktree root does not contain a git repository, then find
2979 // the git repository in an ancestor directory. Find any gitignore files
2980 // in ancestor directories.
2981 let root_abs_path = self.state.lock().snapshot.abs_path.clone();
2982 for (index, ancestor) in root_abs_path.ancestors().enumerate() {
2983 if index != 0 {
2984 if let Ok(ignore) =
2985 build_gitignore(&ancestor.join(&*GITIGNORE), self.fs.as_ref()).await
2986 {
2987 self.state
2988 .lock()
2989 .snapshot
2990 .ignores_by_parent_abs_path
2991 .insert(ancestor.into(), (ignore.into(), false));
2992 }
2993 }
2994
2995 let ancestor_dot_git = ancestor.join(&*DOT_GIT);
2996 if ancestor_dot_git.is_dir() {
2997 if index != 0 {
2998 // We canonicalize, since the FS events use the canonicalized path.
2999 if let Some(ancestor_dot_git) =
3000 self.fs.canonicalize(&ancestor_dot_git).await.log_err()
3001 {
3002 let (ancestor_git_events, _) =
3003 self.fs.watch(&ancestor_dot_git, FS_WATCH_LATENCY).await;
3004 fs_events_rx = select(fs_events_rx, ancestor_git_events).boxed();
3005
3006 // We associate the external git repo with our root folder and
3007 // also mark where in the git repo the root folder is located.
3008 self.state.lock().build_git_repository_for_path(
3009 Path::new("").into(),
3010 ancestor_dot_git.into(),
3011 Some(root_abs_path.strip_prefix(ancestor).unwrap().into()),
3012 self.fs.as_ref(),
3013 );
3014 };
3015 }
3016
3017 // Reached root of git repository.
3018 break;
3019 }
3020 }
3021
3022 let (scan_job_tx, scan_job_rx) = channel::unbounded();
3023 {
3024 let mut state = self.state.lock();
3025 state.snapshot.scan_id += 1;
3026 if let Some(mut root_entry) = state.snapshot.root_entry().cloned() {
3027 let ignore_stack = state
3028 .snapshot
3029 .ignore_stack_for_abs_path(&root_abs_path, true);
3030 if ignore_stack.is_abs_path_ignored(&root_abs_path, true) {
3031 root_entry.is_ignored = true;
3032 state.insert_entry(root_entry.clone(), self.fs.as_ref());
3033 }
3034 state.enqueue_scan_dir(root_abs_path, &root_entry, &scan_job_tx);
3035 }
3036 };
3037
3038 // Perform an initial scan of the directory.
3039 drop(scan_job_tx);
3040 self.scan_dirs(true, scan_job_rx).await;
3041 {
3042 let mut state = self.state.lock();
3043 state.snapshot.completed_scan_id = state.snapshot.scan_id;
3044 }
3045
3046 self.send_status_update(false, None);
3047
3048 // Process any any FS events that occurred while performing the initial scan.
3049 // For these events, update events cannot be as precise, because we didn't
3050 // have the previous state loaded yet.
3051 self.phase = BackgroundScannerPhase::EventsReceivedDuringInitialScan;
3052 if let Poll::Ready(Some(mut paths)) = futures::poll!(fs_events_rx.next()) {
3053 while let Poll::Ready(Some(more_paths)) = futures::poll!(fs_events_rx.next()) {
3054 paths.extend(more_paths);
3055 }
3056 self.process_events(paths).await;
3057 }
3058
3059 // Continue processing events until the worktree is dropped.
3060 self.phase = BackgroundScannerPhase::Events;
3061
3062 loop {
3063 select_biased! {
3064 // Process any path refresh requests from the worktree. Prioritize
3065 // these before handling changes reported by the filesystem.
3066 request = self.scan_requests_rx.recv().fuse() => {
3067 let Ok(request) = request else { break };
3068 if !self.process_scan_request(request, false).await {
3069 return;
3070 }
3071 }
3072
3073 path_prefix = self.path_prefixes_to_scan_rx.recv().fuse() => {
3074 let Ok(path_prefix) = path_prefix else { break };
3075 log::trace!("adding path prefix {:?}", path_prefix);
3076
3077 let did_scan = self.forcibly_load_paths(&[path_prefix.clone()]).await;
3078 if did_scan {
3079 let abs_path =
3080 {
3081 let mut state = self.state.lock();
3082 state.path_prefixes_to_scan.insert(path_prefix.clone());
3083 state.snapshot.abs_path.join(&path_prefix)
3084 };
3085
3086 if let Some(abs_path) = self.fs.canonicalize(&abs_path).await.log_err() {
3087 self.process_events(vec![abs_path]).await;
3088 }
3089 }
3090 }
3091
3092 paths = fs_events_rx.next().fuse() => {
3093 let Some(mut paths) = paths else { break };
3094 while let Poll::Ready(Some(more_paths)) = futures::poll!(fs_events_rx.next()) {
3095 paths.extend(more_paths);
3096 }
3097 self.process_events(paths.clone()).await;
3098 }
3099 }
3100 }
3101 }
3102
3103 async fn process_scan_request(&self, mut request: ScanRequest, scanning: bool) -> bool {
3104 log::debug!("rescanning paths {:?}", request.relative_paths);
3105
3106 request.relative_paths.sort_unstable();
3107 self.forcibly_load_paths(&request.relative_paths).await;
3108
3109 let root_path = self.state.lock().snapshot.abs_path.clone();
3110 let root_canonical_path = match self.fs.canonicalize(&root_path).await {
3111 Ok(path) => path,
3112 Err(err) => {
3113 log::error!("failed to canonicalize root path: {}", err);
3114 return true;
3115 }
3116 };
3117 let abs_paths = request
3118 .relative_paths
3119 .iter()
3120 .map(|path| {
3121 if path.file_name().is_some() {
3122 root_canonical_path.join(path)
3123 } else {
3124 root_canonical_path.clone()
3125 }
3126 })
3127 .collect::<Vec<_>>();
3128
3129 {
3130 let mut state = self.state.lock();
3131 let is_idle = state.snapshot.completed_scan_id == state.snapshot.scan_id;
3132 state.snapshot.scan_id += 1;
3133 if is_idle {
3134 state.snapshot.completed_scan_id = state.snapshot.scan_id;
3135 }
3136 }
3137
3138 self.reload_entries_for_paths(
3139 root_path,
3140 root_canonical_path,
3141 &request.relative_paths,
3142 abs_paths,
3143 None,
3144 )
3145 .await;
3146
3147 self.send_status_update(scanning, Some(request.done))
3148 }
3149
3150 async fn process_events(&mut self, mut abs_paths: Vec<PathBuf>) {
3151 let root_path = self.state.lock().snapshot.abs_path.clone();
3152 let root_canonical_path = match self.fs.canonicalize(&root_path).await {
3153 Ok(path) => path,
3154 Err(err) => {
3155 log::error!("failed to canonicalize root path: {}", err);
3156 return;
3157 }
3158 };
3159
3160 let mut relative_paths = Vec::with_capacity(abs_paths.len());
3161 let mut dot_git_paths = Vec::new();
3162 abs_paths.sort_unstable();
3163 abs_paths.dedup_by(|a, b| a.starts_with(&b));
3164 abs_paths.retain(|abs_path| {
3165 let snapshot = &self.state.lock().snapshot;
3166 {
3167 let mut is_git_related = false;
3168 if let Some(dot_git_dir) = abs_path
3169 .ancestors()
3170 .find(|ancestor| ancestor.file_name() == Some(*DOT_GIT))
3171 {
3172 let dot_git_path = dot_git_dir
3173 .strip_prefix(&root_canonical_path)
3174 .unwrap_or(dot_git_dir)
3175 .to_path_buf();
3176 if !dot_git_paths.contains(&dot_git_path) {
3177 dot_git_paths.push(dot_git_path);
3178 }
3179 is_git_related = true;
3180 }
3181
3182 let relative_path: Arc<Path> =
3183 if let Ok(path) = abs_path.strip_prefix(&root_canonical_path) {
3184 path.into()
3185 } else {
3186 if is_git_related {
3187 log::debug!(
3188 "ignoring event {abs_path:?}, since it's in git dir outside of root path {root_canonical_path:?}",
3189 );
3190 } else {
3191 log::error!(
3192 "ignoring event {abs_path:?} outside of root path {root_canonical_path:?}",
3193 );
3194 }
3195 return false;
3196 };
3197
3198 let parent_dir_is_loaded = relative_path.parent().map_or(true, |parent| {
3199 snapshot
3200 .entry_for_path(parent)
3201 .map_or(false, |entry| entry.kind == EntryKind::Dir)
3202 });
3203 if !parent_dir_is_loaded {
3204 log::debug!("ignoring event {relative_path:?} within unloaded directory");
3205 return false;
3206 }
3207
3208 if snapshot.is_path_excluded(&relative_path) {
3209 if !is_git_related {
3210 log::debug!("ignoring FS event for excluded path {relative_path:?}");
3211 }
3212 return false;
3213 }
3214
3215 relative_paths.push(relative_path);
3216 true
3217 }
3218 });
3219
3220 if relative_paths.is_empty() && dot_git_paths.is_empty() {
3221 return;
3222 }
3223
3224 self.state.lock().snapshot.scan_id += 1;
3225
3226 let (scan_job_tx, scan_job_rx) = channel::unbounded();
3227 log::debug!("received fs events {:?}", relative_paths);
3228 self.reload_entries_for_paths(
3229 root_path,
3230 root_canonical_path,
3231 &relative_paths,
3232 abs_paths,
3233 Some(scan_job_tx.clone()),
3234 )
3235 .await;
3236
3237 self.update_ignore_statuses(scan_job_tx).await;
3238 self.scan_dirs(false, scan_job_rx).await;
3239
3240 if !dot_git_paths.is_empty() {
3241 self.update_git_repositories(dot_git_paths).await;
3242 }
3243
3244 {
3245 let mut state = self.state.lock();
3246 state.snapshot.completed_scan_id = state.snapshot.scan_id;
3247 for (_, entry_id) in mem::take(&mut state.removed_entry_ids) {
3248 state.scanned_dirs.remove(&entry_id);
3249 }
3250 }
3251
3252 self.send_status_update(false, None);
3253 }
3254
3255 async fn forcibly_load_paths(&self, paths: &[Arc<Path>]) -> bool {
3256 let (scan_job_tx, mut scan_job_rx) = channel::unbounded();
3257 {
3258 let mut state = self.state.lock();
3259 let root_path = state.snapshot.abs_path.clone();
3260 for path in paths {
3261 for ancestor in path.ancestors() {
3262 if let Some(entry) = state.snapshot.entry_for_path(ancestor) {
3263 if entry.kind == EntryKind::UnloadedDir {
3264 let abs_path = root_path.join(ancestor);
3265 state.enqueue_scan_dir(abs_path.into(), entry, &scan_job_tx);
3266 state.paths_to_scan.insert(path.clone());
3267 break;
3268 }
3269 }
3270 }
3271 }
3272 drop(scan_job_tx);
3273 }
3274 while let Some(job) = scan_job_rx.next().await {
3275 self.scan_dir(&job).await.log_err();
3276 }
3277
3278 mem::take(&mut self.state.lock().paths_to_scan).len() > 0
3279 }
3280
3281 async fn scan_dirs(
3282 &self,
3283 enable_progress_updates: bool,
3284 scan_jobs_rx: channel::Receiver<ScanJob>,
3285 ) {
3286 use futures::FutureExt as _;
3287
3288 if self
3289 .status_updates_tx
3290 .unbounded_send(ScanState::Started)
3291 .is_err()
3292 {
3293 return;
3294 }
3295
3296 let progress_update_count = AtomicUsize::new(0);
3297 self.executor
3298 .scoped(|scope| {
3299 for _ in 0..self.executor.num_cpus() {
3300 scope.spawn(async {
3301 let mut last_progress_update_count = 0;
3302 let progress_update_timer = self.progress_timer(enable_progress_updates).fuse();
3303 futures::pin_mut!(progress_update_timer);
3304
3305 loop {
3306 select_biased! {
3307 // Process any path refresh requests before moving on to process
3308 // the scan queue, so that user operations are prioritized.
3309 request = self.scan_requests_rx.recv().fuse() => {
3310 let Ok(request) = request else { break };
3311 if !self.process_scan_request(request, true).await {
3312 return;
3313 }
3314 }
3315
3316 // Send periodic progress updates to the worktree. Use an atomic counter
3317 // to ensure that only one of the workers sends a progress update after
3318 // the update interval elapses.
3319 _ = progress_update_timer => {
3320 match progress_update_count.compare_exchange(
3321 last_progress_update_count,
3322 last_progress_update_count + 1,
3323 SeqCst,
3324 SeqCst
3325 ) {
3326 Ok(_) => {
3327 last_progress_update_count += 1;
3328 self.send_status_update(true, None);
3329 }
3330 Err(count) => {
3331 last_progress_update_count = count;
3332 }
3333 }
3334 progress_update_timer.set(self.progress_timer(enable_progress_updates).fuse());
3335 }
3336
3337 // Recursively load directories from the file system.
3338 job = scan_jobs_rx.recv().fuse() => {
3339 let Ok(job) = job else { break };
3340 if let Err(err) = self.scan_dir(&job).await {
3341 if job.path.as_ref() != Path::new("") {
3342 log::error!("error scanning directory {:?}: {}", job.abs_path, err);
3343 }
3344 }
3345 }
3346 }
3347 }
3348 })
3349 }
3350 })
3351 .await;
3352 }
3353
3354 fn send_status_update(&self, scanning: bool, barrier: Option<barrier::Sender>) -> bool {
3355 let mut state = self.state.lock();
3356 if state.changed_paths.is_empty() && scanning {
3357 return true;
3358 }
3359
3360 let new_snapshot = state.snapshot.clone();
3361 let old_snapshot = mem::replace(&mut state.prev_snapshot, new_snapshot.snapshot.clone());
3362 let changes = self.build_change_set(&old_snapshot, &new_snapshot, &state.changed_paths);
3363 state.changed_paths.clear();
3364
3365 self.status_updates_tx
3366 .unbounded_send(ScanState::Updated {
3367 snapshot: new_snapshot,
3368 changes,
3369 scanning,
3370 barrier,
3371 })
3372 .is_ok()
3373 }
3374
3375 async fn scan_dir(&self, job: &ScanJob) -> Result<()> {
3376 let root_abs_path;
3377 let root_char_bag;
3378 {
3379 let snapshot = &self.state.lock().snapshot;
3380 if snapshot.is_path_excluded(&job.path) {
3381 log::error!("skipping excluded directory {:?}", job.path);
3382 return Ok(());
3383 }
3384 log::debug!("scanning directory {:?}", job.path);
3385 root_abs_path = snapshot.abs_path().clone();
3386 root_char_bag = snapshot.root_char_bag;
3387 }
3388
3389 let next_entry_id = self.next_entry_id.clone();
3390 let mut ignore_stack = job.ignore_stack.clone();
3391 let mut containing_repository = job.containing_repository.clone();
3392 let mut new_ignore = None;
3393 let mut root_canonical_path = None;
3394 let mut new_entries: Vec<Entry> = Vec::new();
3395 let mut new_jobs: Vec<Option<ScanJob>> = Vec::new();
3396 let mut child_paths = self
3397 .fs
3398 .read_dir(&job.abs_path)
3399 .await?
3400 .filter_map(|entry| async {
3401 match entry {
3402 Ok(entry) => Some(entry),
3403 Err(error) => {
3404 log::error!("error processing entry {:?}", error);
3405 None
3406 }
3407 }
3408 })
3409 .collect::<Vec<_>>()
3410 .await;
3411
3412 // Ensure .git and gitignore files are processed first.
3413 let mut ixs_to_move_to_front = Vec::new();
3414 for (ix, child_abs_path) in child_paths.iter().enumerate() {
3415 let filename = child_abs_path.file_name().unwrap();
3416 if filename == *DOT_GIT {
3417 ixs_to_move_to_front.insert(0, ix);
3418 } else if filename == *GITIGNORE {
3419 ixs_to_move_to_front.push(ix);
3420 }
3421 }
3422 for (dest_ix, src_ix) in ixs_to_move_to_front.into_iter().enumerate() {
3423 child_paths.swap(dest_ix, src_ix);
3424 }
3425
3426 for child_abs_path in child_paths {
3427 let child_abs_path: Arc<Path> = child_abs_path.into();
3428 let child_name = child_abs_path.file_name().unwrap();
3429 let child_path: Arc<Path> = job.path.join(child_name).into();
3430
3431 if child_name == *DOT_GIT {
3432 let repo = self
3433 .state
3434 .lock()
3435 .build_git_repository(child_path.clone(), self.fs.as_ref());
3436 if let Some((work_directory, repository)) = repo {
3437 let t0 = Instant::now();
3438 let statuses = repository
3439 .statuses(Path::new(""))
3440 .log_err()
3441 .unwrap_or_default();
3442 log::trace!("computed git status in {:?}", t0.elapsed());
3443 containing_repository = Some(ScanJobContainingRepository {
3444 work_directory,
3445 statuses,
3446 });
3447 }
3448 } else if child_name == *GITIGNORE {
3449 match build_gitignore(&child_abs_path, self.fs.as_ref()).await {
3450 Ok(ignore) => {
3451 let ignore = Arc::new(ignore);
3452 ignore_stack = ignore_stack.append(job.abs_path.clone(), ignore.clone());
3453 new_ignore = Some(ignore);
3454 }
3455 Err(error) => {
3456 log::error!(
3457 "error loading .gitignore file {:?} - {:?}",
3458 child_name,
3459 error
3460 );
3461 }
3462 }
3463 }
3464
3465 {
3466 let mut state = self.state.lock();
3467 if state.snapshot.is_path_excluded(&child_path) {
3468 log::debug!("skipping excluded child entry {child_path:?}");
3469 state.remove_path(&child_path);
3470 continue;
3471 }
3472 }
3473
3474 let child_metadata = match self.fs.metadata(&child_abs_path).await {
3475 Ok(Some(metadata)) => metadata,
3476 Ok(None) => continue,
3477 Err(err) => {
3478 log::error!("error processing {child_abs_path:?}: {err:?}");
3479 continue;
3480 }
3481 };
3482
3483 let mut child_entry = Entry::new(
3484 child_path.clone(),
3485 &child_metadata,
3486 &next_entry_id,
3487 root_char_bag,
3488 None,
3489 );
3490
3491 if job.is_external {
3492 child_entry.is_external = true;
3493 } else if child_metadata.is_symlink {
3494 let canonical_path = match self.fs.canonicalize(&child_abs_path).await {
3495 Ok(path) => path,
3496 Err(err) => {
3497 log::error!(
3498 "error reading target of symlink {:?}: {:?}",
3499 child_abs_path,
3500 err
3501 );
3502 continue;
3503 }
3504 };
3505
3506 // lazily canonicalize the root path in order to determine if
3507 // symlinks point outside of the worktree.
3508 let root_canonical_path = match &root_canonical_path {
3509 Some(path) => path,
3510 None => match self.fs.canonicalize(&root_abs_path).await {
3511 Ok(path) => root_canonical_path.insert(path),
3512 Err(err) => {
3513 log::error!("error canonicalizing root {:?}: {:?}", root_abs_path, err);
3514 continue;
3515 }
3516 },
3517 };
3518
3519 if !canonical_path.starts_with(root_canonical_path) {
3520 child_entry.is_external = true;
3521 }
3522
3523 child_entry.canonical_path = Some(canonical_path);
3524 }
3525
3526 if child_entry.is_dir() {
3527 child_entry.is_ignored = ignore_stack.is_abs_path_ignored(&child_abs_path, true);
3528
3529 // Avoid recursing until crash in the case of a recursive symlink
3530 if job.ancestor_inodes.contains(&child_entry.inode) {
3531 new_jobs.push(None);
3532 } else {
3533 let mut ancestor_inodes = job.ancestor_inodes.clone();
3534 ancestor_inodes.insert(child_entry.inode);
3535
3536 new_jobs.push(Some(ScanJob {
3537 abs_path: child_abs_path.clone(),
3538 path: child_path,
3539 is_external: child_entry.is_external,
3540 ignore_stack: if child_entry.is_ignored {
3541 IgnoreStack::all()
3542 } else {
3543 ignore_stack.clone()
3544 },
3545 ancestor_inodes,
3546 scan_queue: job.scan_queue.clone(),
3547 containing_repository: containing_repository.clone(),
3548 }));
3549 }
3550 } else {
3551 child_entry.is_ignored = ignore_stack.is_abs_path_ignored(&child_abs_path, false);
3552 if !child_entry.is_ignored {
3553 if let Some(repo) = &containing_repository {
3554 if let Ok(repo_path) = child_entry.path.strip_prefix(&repo.work_directory) {
3555 let repo_path = RepoPath(repo_path.into());
3556 child_entry.git_status = repo.statuses.get(&repo_path);
3557 }
3558 }
3559 }
3560 }
3561
3562 {
3563 let relative_path = job.path.join(child_name);
3564 let state = self.state.lock();
3565 if state.snapshot.is_path_private(&relative_path) {
3566 log::debug!("detected private file: {relative_path:?}");
3567 child_entry.is_private = true;
3568 }
3569 drop(state)
3570 }
3571
3572 new_entries.push(child_entry);
3573 }
3574
3575 let mut state = self.state.lock();
3576
3577 // Identify any subdirectories that should not be scanned.
3578 let mut job_ix = 0;
3579 for entry in &mut new_entries {
3580 state.reuse_entry_id(entry);
3581 if entry.is_dir() {
3582 if state.should_scan_directory(entry) {
3583 job_ix += 1;
3584 } else {
3585 log::debug!("defer scanning directory {:?}", entry.path);
3586 entry.kind = EntryKind::UnloadedDir;
3587 new_jobs.remove(job_ix);
3588 }
3589 }
3590 }
3591
3592 state.populate_dir(&job.path, new_entries, new_ignore);
3593 self.watcher.add(job.abs_path.as_ref()).log_err();
3594
3595 for new_job in new_jobs.into_iter().flatten() {
3596 job.scan_queue
3597 .try_send(new_job)
3598 .expect("channel is unbounded");
3599 }
3600
3601 Ok(())
3602 }
3603
3604 async fn reload_entries_for_paths(
3605 &self,
3606 root_abs_path: Arc<Path>,
3607 root_canonical_path: PathBuf,
3608 relative_paths: &[Arc<Path>],
3609 abs_paths: Vec<PathBuf>,
3610 scan_queue_tx: Option<Sender<ScanJob>>,
3611 ) {
3612 let metadata = futures::future::join_all(
3613 abs_paths
3614 .iter()
3615 .map(|abs_path| async move {
3616 let metadata = self.fs.metadata(abs_path).await?;
3617 if let Some(metadata) = metadata {
3618 let canonical_path = self.fs.canonicalize(abs_path).await?;
3619
3620 // If we're on a case-insensitive filesystem (default on macOS), we want
3621 // to only ignore metadata for non-symlink files if their absolute-path matches
3622 // the canonical-path.
3623 // Because if not, this might be a case-only-renaming (`mv test.txt TEST.TXT`)
3624 // and we want to ignore the metadata for the old path (`test.txt`) so it's
3625 // treated as removed.
3626 if !self.fs_case_sensitive && !metadata.is_symlink {
3627 let canonical_file_name = canonical_path.file_name();
3628 let file_name = abs_path.file_name();
3629 if canonical_file_name != file_name {
3630 return Ok(None);
3631 }
3632 }
3633
3634 anyhow::Ok(Some((metadata, canonical_path)))
3635 } else {
3636 Ok(None)
3637 }
3638 })
3639 .collect::<Vec<_>>(),
3640 )
3641 .await;
3642
3643 let mut state = self.state.lock();
3644 let doing_recursive_update = scan_queue_tx.is_some();
3645
3646 // Remove any entries for paths that no longer exist or are being recursively
3647 // refreshed. Do this before adding any new entries, so that renames can be
3648 // detected regardless of the order of the paths.
3649 for (path, metadata) in relative_paths.iter().zip(metadata.iter()) {
3650 if matches!(metadata, Ok(None)) || doing_recursive_update {
3651 log::trace!("remove path {:?}", path);
3652 state.remove_path(path);
3653 }
3654 }
3655
3656 for (path, metadata) in relative_paths.iter().zip(metadata.iter()) {
3657 let abs_path: Arc<Path> = root_abs_path.join(&path).into();
3658 match metadata {
3659 Ok(Some((metadata, canonical_path))) => {
3660 let ignore_stack = state
3661 .snapshot
3662 .ignore_stack_for_abs_path(&abs_path, metadata.is_dir);
3663
3664 let mut fs_entry = Entry::new(
3665 path.clone(),
3666 metadata,
3667 self.next_entry_id.as_ref(),
3668 state.snapshot.root_char_bag,
3669 if metadata.is_symlink {
3670 Some(canonical_path.to_path_buf())
3671 } else {
3672 None
3673 },
3674 );
3675
3676 let is_dir = fs_entry.is_dir();
3677 fs_entry.is_ignored = ignore_stack.is_abs_path_ignored(&abs_path, is_dir);
3678 fs_entry.is_external = !canonical_path.starts_with(&root_canonical_path);
3679 fs_entry.is_private = state.snapshot.is_path_private(path);
3680
3681 if !is_dir && !fs_entry.is_ignored && !fs_entry.is_external {
3682 if let Some((repo_entry, repo)) = state.snapshot.repo_for_path(path) {
3683 if let Ok(repo_path) = repo_entry.relativize(&state.snapshot, path) {
3684 fs_entry.git_status = repo.repo_ptr.status(&repo_path);
3685 }
3686 }
3687 }
3688
3689 if let (Some(scan_queue_tx), true) = (&scan_queue_tx, fs_entry.is_dir()) {
3690 if state.should_scan_directory(&fs_entry) {
3691 state.enqueue_scan_dir(abs_path, &fs_entry, scan_queue_tx);
3692 } else {
3693 fs_entry.kind = EntryKind::UnloadedDir;
3694 }
3695 }
3696
3697 state.insert_entry(fs_entry, self.fs.as_ref());
3698 }
3699 Ok(None) => {
3700 self.remove_repo_path(path, &mut state.snapshot);
3701 }
3702 Err(err) => {
3703 // TODO - create a special 'error' entry in the entries tree to mark this
3704 log::error!("error reading file {abs_path:?} on event: {err:#}");
3705 }
3706 }
3707 }
3708
3709 util::extend_sorted(
3710 &mut state.changed_paths,
3711 relative_paths.iter().cloned(),
3712 usize::MAX,
3713 Ord::cmp,
3714 );
3715 }
3716
3717 fn remove_repo_path(&self, path: &Path, snapshot: &mut LocalSnapshot) -> Option<()> {
3718 if !path
3719 .components()
3720 .any(|component| component.as_os_str() == *DOT_GIT)
3721 {
3722 if let Some(repository) = snapshot.repository_for_work_directory(path) {
3723 let entry = repository.work_directory.0;
3724 snapshot.git_repositories.remove(&entry);
3725 snapshot
3726 .snapshot
3727 .repository_entries
3728 .remove(&RepositoryWorkDirectory(path.into()));
3729 return Some(());
3730 }
3731 }
3732
3733 // TODO statuses
3734 // Track when a .git is removed and iterate over the file system there
3735
3736 Some(())
3737 }
3738
3739 async fn update_ignore_statuses(&self, scan_job_tx: Sender<ScanJob>) {
3740 use futures::FutureExt as _;
3741
3742 let mut snapshot = self.state.lock().snapshot.clone();
3743 let mut ignores_to_update = Vec::new();
3744 let mut ignores_to_delete = Vec::new();
3745 let abs_path = snapshot.abs_path.clone();
3746 for (parent_abs_path, (_, needs_update)) in &mut snapshot.ignores_by_parent_abs_path {
3747 if let Ok(parent_path) = parent_abs_path.strip_prefix(&abs_path) {
3748 if *needs_update {
3749 *needs_update = false;
3750 if snapshot.snapshot.entry_for_path(parent_path).is_some() {
3751 ignores_to_update.push(parent_abs_path.clone());
3752 }
3753 }
3754
3755 let ignore_path = parent_path.join(&*GITIGNORE);
3756 if snapshot.snapshot.entry_for_path(ignore_path).is_none() {
3757 ignores_to_delete.push(parent_abs_path.clone());
3758 }
3759 }
3760 }
3761
3762 for parent_abs_path in ignores_to_delete {
3763 snapshot.ignores_by_parent_abs_path.remove(&parent_abs_path);
3764 self.state
3765 .lock()
3766 .snapshot
3767 .ignores_by_parent_abs_path
3768 .remove(&parent_abs_path);
3769 }
3770
3771 let (ignore_queue_tx, ignore_queue_rx) = channel::unbounded();
3772 ignores_to_update.sort_unstable();
3773 let mut ignores_to_update = ignores_to_update.into_iter().peekable();
3774 while let Some(parent_abs_path) = ignores_to_update.next() {
3775 while ignores_to_update
3776 .peek()
3777 .map_or(false, |p| p.starts_with(&parent_abs_path))
3778 {
3779 ignores_to_update.next().unwrap();
3780 }
3781
3782 let ignore_stack = snapshot.ignore_stack_for_abs_path(&parent_abs_path, true);
3783 smol::block_on(ignore_queue_tx.send(UpdateIgnoreStatusJob {
3784 abs_path: parent_abs_path,
3785 ignore_stack,
3786 ignore_queue: ignore_queue_tx.clone(),
3787 scan_queue: scan_job_tx.clone(),
3788 }))
3789 .unwrap();
3790 }
3791 drop(ignore_queue_tx);
3792
3793 self.executor
3794 .scoped(|scope| {
3795 for _ in 0..self.executor.num_cpus() {
3796 scope.spawn(async {
3797 loop {
3798 select_biased! {
3799 // Process any path refresh requests before moving on to process
3800 // the queue of ignore statuses.
3801 request = self.scan_requests_rx.recv().fuse() => {
3802 let Ok(request) = request else { break };
3803 if !self.process_scan_request(request, true).await {
3804 return;
3805 }
3806 }
3807
3808 // Recursively process directories whose ignores have changed.
3809 job = ignore_queue_rx.recv().fuse() => {
3810 let Ok(job) = job else { break };
3811 self.update_ignore_status(job, &snapshot).await;
3812 }
3813 }
3814 }
3815 });
3816 }
3817 })
3818 .await;
3819 }
3820
3821 async fn update_ignore_status(&self, job: UpdateIgnoreStatusJob, snapshot: &LocalSnapshot) {
3822 log::trace!("update ignore status {:?}", job.abs_path);
3823
3824 let mut ignore_stack = job.ignore_stack;
3825 if let Some((ignore, _)) = snapshot.ignores_by_parent_abs_path.get(&job.abs_path) {
3826 ignore_stack = ignore_stack.append(job.abs_path.clone(), ignore.clone());
3827 }
3828
3829 let mut entries_by_id_edits = Vec::new();
3830 let mut entries_by_path_edits = Vec::new();
3831 let path = job.abs_path.strip_prefix(&snapshot.abs_path).unwrap();
3832 let repo = snapshot.repo_for_path(path);
3833 for mut entry in snapshot.child_entries(path).cloned() {
3834 let was_ignored = entry.is_ignored;
3835 let abs_path: Arc<Path> = snapshot.abs_path().join(&entry.path).into();
3836 entry.is_ignored = ignore_stack.is_abs_path_ignored(&abs_path, entry.is_dir());
3837 if entry.is_dir() {
3838 let child_ignore_stack = if entry.is_ignored {
3839 IgnoreStack::all()
3840 } else {
3841 ignore_stack.clone()
3842 };
3843
3844 // Scan any directories that were previously ignored and weren't previously scanned.
3845 if was_ignored && !entry.is_ignored && entry.kind.is_unloaded() {
3846 let state = self.state.lock();
3847 if state.should_scan_directory(&entry) {
3848 state.enqueue_scan_dir(abs_path.clone(), &entry, &job.scan_queue);
3849 }
3850 }
3851
3852 job.ignore_queue
3853 .send(UpdateIgnoreStatusJob {
3854 abs_path: abs_path.clone(),
3855 ignore_stack: child_ignore_stack,
3856 ignore_queue: job.ignore_queue.clone(),
3857 scan_queue: job.scan_queue.clone(),
3858 })
3859 .await
3860 .unwrap();
3861 }
3862
3863 if entry.is_ignored != was_ignored {
3864 let mut path_entry = snapshot.entries_by_id.get(&entry.id, &()).unwrap().clone();
3865 path_entry.scan_id = snapshot.scan_id;
3866 path_entry.is_ignored = entry.is_ignored;
3867 if !entry.is_dir() && !entry.is_ignored && !entry.is_external {
3868 if let Some((ref repo_entry, local_repo)) = repo {
3869 if let Ok(repo_path) = repo_entry.relativize(&snapshot, &entry.path) {
3870 entry.git_status = local_repo.repo_ptr.status(&repo_path);
3871 }
3872 }
3873 }
3874 entries_by_id_edits.push(Edit::Insert(path_entry));
3875 entries_by_path_edits.push(Edit::Insert(entry));
3876 }
3877 }
3878
3879 let state = &mut self.state.lock();
3880 for edit in &entries_by_path_edits {
3881 if let Edit::Insert(entry) = edit {
3882 if let Err(ix) = state.changed_paths.binary_search(&entry.path) {
3883 state.changed_paths.insert(ix, entry.path.clone());
3884 }
3885 }
3886 }
3887
3888 state
3889 .snapshot
3890 .entries_by_path
3891 .edit(entries_by_path_edits, &());
3892 state.snapshot.entries_by_id.edit(entries_by_id_edits, &());
3893 }
3894
3895 async fn update_git_repositories(&self, dot_git_paths: Vec<PathBuf>) {
3896 log::debug!("reloading repositories: {dot_git_paths:?}");
3897
3898 let mut repo_updates = Vec::new();
3899 {
3900 let mut state = self.state.lock();
3901 let scan_id = state.snapshot.scan_id;
3902 for dot_git_dir in dot_git_paths {
3903 let existing_repository_entry =
3904 state
3905 .snapshot
3906 .git_repositories
3907 .iter()
3908 .find_map(|(entry_id, repo)| {
3909 (repo.git_dir_path.as_ref() == dot_git_dir)
3910 .then(|| (*entry_id, repo.clone()))
3911 });
3912
3913 let (work_directory, repository) = match existing_repository_entry {
3914 None => {
3915 match state.build_git_repository(dot_git_dir.into(), self.fs.as_ref()) {
3916 Some(output) => output,
3917 None => continue,
3918 }
3919 }
3920 Some((entry_id, repository)) => {
3921 if repository.git_dir_scan_id == scan_id {
3922 continue;
3923 }
3924 let Some(work_dir) = state
3925 .snapshot
3926 .entry_for_id(entry_id)
3927 .map(|entry| RepositoryWorkDirectory(entry.path.clone()))
3928 else {
3929 continue;
3930 };
3931
3932 let repo = &repository.repo_ptr;
3933 let branch = repo.branch_name();
3934 repo.reload_index();
3935
3936 state
3937 .snapshot
3938 .git_repositories
3939 .update(&entry_id, |entry| entry.git_dir_scan_id = scan_id);
3940 state
3941 .snapshot
3942 .snapshot
3943 .repository_entries
3944 .update(&work_dir, |entry| entry.branch = branch.map(Into::into));
3945 (work_dir, repository.repo_ptr.clone())
3946 }
3947 };
3948
3949 repo_updates.push(UpdateGitStatusesJob {
3950 location_in_repo: state
3951 .snapshot
3952 .repository_entries
3953 .get(&work_directory)
3954 .and_then(|repo| repo.location_in_repo.clone())
3955 .clone(),
3956 work_directory,
3957 repository,
3958 });
3959 }
3960
3961 // Remove any git repositories whose .git entry no longer exists.
3962 let snapshot = &mut state.snapshot;
3963 let mut ids_to_preserve = HashSet::default();
3964 for (&work_directory_id, entry) in snapshot.git_repositories.iter() {
3965 let exists_in_snapshot = snapshot
3966 .entry_for_id(work_directory_id)
3967 .map_or(false, |entry| {
3968 snapshot.entry_for_path(entry.path.join(*DOT_GIT)).is_some()
3969 });
3970 if exists_in_snapshot {
3971 ids_to_preserve.insert(work_directory_id);
3972 } else {
3973 let git_dir_abs_path = snapshot.abs_path().join(&entry.git_dir_path);
3974 let git_dir_excluded = snapshot.is_path_excluded(&entry.git_dir_path);
3975 if git_dir_excluded
3976 && !matches!(
3977 smol::block_on(self.fs.metadata(&git_dir_abs_path)),
3978 Ok(None)
3979 )
3980 {
3981 ids_to_preserve.insert(work_directory_id);
3982 }
3983 }
3984 }
3985
3986 snapshot
3987 .git_repositories
3988 .retain(|work_directory_id, _| ids_to_preserve.contains(work_directory_id));
3989 snapshot
3990 .repository_entries
3991 .retain(|_, entry| ids_to_preserve.contains(&entry.work_directory.0));
3992 }
3993
3994 let (mut updates_done_tx, mut updates_done_rx) = barrier::channel();
3995 self.executor
3996 .scoped(|scope| {
3997 scope.spawn(async {
3998 for repo_update in repo_updates {
3999 self.update_git_statuses(repo_update);
4000 }
4001 updates_done_tx.blocking_send(()).ok();
4002 });
4003
4004 scope.spawn(async {
4005 loop {
4006 select_biased! {
4007 // Process any path refresh requests before moving on to process
4008 // the queue of git statuses.
4009 request = self.scan_requests_rx.recv().fuse() => {
4010 let Ok(request) = request else { break };
4011 if !self.process_scan_request(request, true).await {
4012 return;
4013 }
4014 }
4015 _ = updates_done_rx.recv().fuse() => break,
4016 }
4017 }
4018 });
4019 })
4020 .await;
4021 }
4022
4023 /// Update the git statuses for a given batch of entries.
4024 fn update_git_statuses(&self, job: UpdateGitStatusesJob) {
4025 log::trace!("updating git statuses for repo {:?}", job.work_directory.0);
4026 let t0 = Instant::now();
4027 let Some(statuses) = job.repository.statuses(Path::new("")).log_err() else {
4028 return;
4029 };
4030 log::trace!(
4031 "computed git statuses for repo {:?} in {:?}",
4032 job.work_directory.0,
4033 t0.elapsed()
4034 );
4035
4036 let t0 = Instant::now();
4037 let mut changes = Vec::new();
4038 let snapshot = self.state.lock().snapshot.snapshot.clone();
4039 for file in snapshot.traverse_from_path(true, false, false, job.work_directory.0.as_ref()) {
4040 let Ok(repo_path) = file.path.strip_prefix(&job.work_directory.0) else {
4041 break;
4042 };
4043 let git_status = if let Some(location) = &job.location_in_repo {
4044 statuses.get(&location.join(repo_path))
4045 } else {
4046 statuses.get(&repo_path)
4047 };
4048 if file.git_status != git_status {
4049 let mut entry = file.clone();
4050 entry.git_status = git_status;
4051 changes.push((entry.path, git_status));
4052 }
4053 }
4054
4055 let mut state = self.state.lock();
4056 let edits = changes
4057 .iter()
4058 .filter_map(|(path, git_status)| {
4059 let entry = state.snapshot.entry_for_path(path)?.clone();
4060 Some(Edit::Insert(Entry {
4061 git_status: *git_status,
4062 ..entry.clone()
4063 }))
4064 })
4065 .collect();
4066
4067 // Apply the git status changes.
4068 util::extend_sorted(
4069 &mut state.changed_paths,
4070 changes.iter().map(|p| p.0.clone()),
4071 usize::MAX,
4072 Ord::cmp,
4073 );
4074 state.snapshot.entries_by_path.edit(edits, &());
4075 log::trace!(
4076 "applied git status updates for repo {:?} in {:?}",
4077 job.work_directory.0,
4078 t0.elapsed(),
4079 );
4080 }
4081
4082 fn build_change_set(
4083 &self,
4084 old_snapshot: &Snapshot,
4085 new_snapshot: &Snapshot,
4086 event_paths: &[Arc<Path>],
4087 ) -> UpdatedEntriesSet {
4088 use BackgroundScannerPhase::*;
4089 use PathChange::{Added, AddedOrUpdated, Loaded, Removed, Updated};
4090
4091 // Identify which paths have changed. Use the known set of changed
4092 // parent paths to optimize the search.
4093 let mut changes = Vec::new();
4094 let mut old_paths = old_snapshot.entries_by_path.cursor::<PathKey>();
4095 let mut new_paths = new_snapshot.entries_by_path.cursor::<PathKey>();
4096 let mut last_newly_loaded_dir_path = None;
4097 old_paths.next(&());
4098 new_paths.next(&());
4099 for path in event_paths {
4100 let path = PathKey(path.clone());
4101 if old_paths.item().map_or(false, |e| e.path < path.0) {
4102 old_paths.seek_forward(&path, Bias::Left, &());
4103 }
4104 if new_paths.item().map_or(false, |e| e.path < path.0) {
4105 new_paths.seek_forward(&path, Bias::Left, &());
4106 }
4107 loop {
4108 match (old_paths.item(), new_paths.item()) {
4109 (Some(old_entry), Some(new_entry)) => {
4110 if old_entry.path > path.0
4111 && new_entry.path > path.0
4112 && !old_entry.path.starts_with(&path.0)
4113 && !new_entry.path.starts_with(&path.0)
4114 {
4115 break;
4116 }
4117
4118 match Ord::cmp(&old_entry.path, &new_entry.path) {
4119 Ordering::Less => {
4120 changes.push((old_entry.path.clone(), old_entry.id, Removed));
4121 old_paths.next(&());
4122 }
4123 Ordering::Equal => {
4124 if self.phase == EventsReceivedDuringInitialScan {
4125 if old_entry.id != new_entry.id {
4126 changes.push((
4127 old_entry.path.clone(),
4128 old_entry.id,
4129 Removed,
4130 ));
4131 }
4132 // If the worktree was not fully initialized when this event was generated,
4133 // we can't know whether this entry was added during the scan or whether
4134 // it was merely updated.
4135 changes.push((
4136 new_entry.path.clone(),
4137 new_entry.id,
4138 AddedOrUpdated,
4139 ));
4140 } else if old_entry.id != new_entry.id {
4141 changes.push((old_entry.path.clone(), old_entry.id, Removed));
4142 changes.push((new_entry.path.clone(), new_entry.id, Added));
4143 } else if old_entry != new_entry {
4144 if old_entry.kind.is_unloaded() {
4145 last_newly_loaded_dir_path = Some(&new_entry.path);
4146 changes.push((
4147 new_entry.path.clone(),
4148 new_entry.id,
4149 Loaded,
4150 ));
4151 } else {
4152 changes.push((
4153 new_entry.path.clone(),
4154 new_entry.id,
4155 Updated,
4156 ));
4157 }
4158 }
4159 old_paths.next(&());
4160 new_paths.next(&());
4161 }
4162 Ordering::Greater => {
4163 let is_newly_loaded = self.phase == InitialScan
4164 || last_newly_loaded_dir_path
4165 .as_ref()
4166 .map_or(false, |dir| new_entry.path.starts_with(&dir));
4167 changes.push((
4168 new_entry.path.clone(),
4169 new_entry.id,
4170 if is_newly_loaded { Loaded } else { Added },
4171 ));
4172 new_paths.next(&());
4173 }
4174 }
4175 }
4176 (Some(old_entry), None) => {
4177 changes.push((old_entry.path.clone(), old_entry.id, Removed));
4178 old_paths.next(&());
4179 }
4180 (None, Some(new_entry)) => {
4181 let is_newly_loaded = self.phase == InitialScan
4182 || last_newly_loaded_dir_path
4183 .as_ref()
4184 .map_or(false, |dir| new_entry.path.starts_with(&dir));
4185 changes.push((
4186 new_entry.path.clone(),
4187 new_entry.id,
4188 if is_newly_loaded { Loaded } else { Added },
4189 ));
4190 new_paths.next(&());
4191 }
4192 (None, None) => break,
4193 }
4194 }
4195 }
4196
4197 changes.into()
4198 }
4199
4200 async fn progress_timer(&self, running: bool) {
4201 if !running {
4202 return futures::future::pending().await;
4203 }
4204
4205 #[cfg(any(test, feature = "test-support"))]
4206 if self.fs.is_fake() {
4207 return self.executor.simulate_random_delay().await;
4208 }
4209
4210 smol::Timer::after(FS_WATCH_LATENCY).await;
4211 }
4212}
4213
4214fn char_bag_for_path(root_char_bag: CharBag, path: &Path) -> CharBag {
4215 let mut result = root_char_bag;
4216 result.extend(
4217 path.to_string_lossy()
4218 .chars()
4219 .map(|c| c.to_ascii_lowercase()),
4220 );
4221 result
4222}
4223
4224struct ScanJob {
4225 abs_path: Arc<Path>,
4226 path: Arc<Path>,
4227 ignore_stack: Arc<IgnoreStack>,
4228 scan_queue: Sender<ScanJob>,
4229 ancestor_inodes: TreeSet<u64>,
4230 is_external: bool,
4231 containing_repository: Option<ScanJobContainingRepository>,
4232}
4233
4234#[derive(Clone)]
4235struct ScanJobContainingRepository {
4236 work_directory: RepositoryWorkDirectory,
4237 statuses: GitStatus,
4238}
4239
4240struct UpdateIgnoreStatusJob {
4241 abs_path: Arc<Path>,
4242 ignore_stack: Arc<IgnoreStack>,
4243 ignore_queue: Sender<UpdateIgnoreStatusJob>,
4244 scan_queue: Sender<ScanJob>,
4245}
4246
4247struct UpdateGitStatusesJob {
4248 work_directory: RepositoryWorkDirectory,
4249 location_in_repo: Option<Arc<Path>>,
4250 repository: Arc<dyn GitRepository>,
4251}
4252
4253pub trait WorktreeModelHandle {
4254 #[cfg(any(test, feature = "test-support"))]
4255 fn flush_fs_events<'a>(
4256 &self,
4257 cx: &'a mut gpui::TestAppContext,
4258 ) -> futures::future::LocalBoxFuture<'a, ()>;
4259
4260 #[cfg(any(test, feature = "test-support"))]
4261 fn flush_fs_events_in_root_git_repository<'a>(
4262 &self,
4263 cx: &'a mut gpui::TestAppContext,
4264 ) -> futures::future::LocalBoxFuture<'a, ()>;
4265}
4266
4267impl WorktreeModelHandle for Model<Worktree> {
4268 // When the worktree's FS event stream sometimes delivers "redundant" events for FS changes that
4269 // occurred before the worktree was constructed. These events can cause the worktree to perform
4270 // extra directory scans, and emit extra scan-state notifications.
4271 //
4272 // This function mutates the worktree's directory and waits for those mutations to be picked up,
4273 // to ensure that all redundant FS events have already been processed.
4274 #[cfg(any(test, feature = "test-support"))]
4275 fn flush_fs_events<'a>(
4276 &self,
4277 cx: &'a mut gpui::TestAppContext,
4278 ) -> futures::future::LocalBoxFuture<'a, ()> {
4279 let file_name = "fs-event-sentinel";
4280
4281 let tree = self.clone();
4282 let (fs, root_path) = self.update(cx, |tree, _| {
4283 let tree = tree.as_local().unwrap();
4284 (tree.fs.clone(), tree.abs_path().clone())
4285 });
4286
4287 async move {
4288 fs.create_file(&root_path.join(file_name), Default::default())
4289 .await
4290 .unwrap();
4291
4292 cx.condition(&tree, |tree, _| tree.entry_for_path(file_name).is_some())
4293 .await;
4294
4295 fs.remove_file(&root_path.join(file_name), Default::default())
4296 .await
4297 .unwrap();
4298 cx.condition(&tree, |tree, _| tree.entry_for_path(file_name).is_none())
4299 .await;
4300
4301 cx.update(|cx| tree.read(cx).as_local().unwrap().scan_complete())
4302 .await;
4303 }
4304 .boxed_local()
4305 }
4306
4307 // This function is similar to flush_fs_events, except that it waits for events to be flushed in
4308 // the .git folder of the root repository.
4309 // The reason for its existence is that a repository's .git folder might live *outside* of the
4310 // worktree and thus its FS events might go through a different path.
4311 // In order to flush those, we need to create artificial events in the .git folder and wait
4312 // for the repository to be reloaded.
4313 #[cfg(any(test, feature = "test-support"))]
4314 fn flush_fs_events_in_root_git_repository<'a>(
4315 &self,
4316 cx: &'a mut gpui::TestAppContext,
4317 ) -> futures::future::LocalBoxFuture<'a, ()> {
4318 let file_name = "fs-event-sentinel";
4319
4320 let tree = self.clone();
4321 let (fs, root_path, mut git_dir_scan_id) = self.update(cx, |tree, _| {
4322 let tree = tree.as_local().unwrap();
4323 let root_entry = tree.root_git_entry().unwrap();
4324 let local_repo_entry = tree.get_local_repo(&root_entry).unwrap();
4325 (
4326 tree.fs.clone(),
4327 local_repo_entry.git_dir_path.clone(),
4328 local_repo_entry.git_dir_scan_id,
4329 )
4330 });
4331
4332 let scan_id_increased = |tree: &mut Worktree, git_dir_scan_id: &mut usize| {
4333 let root_entry = tree.root_git_entry().unwrap();
4334 let local_repo_entry = tree
4335 .as_local()
4336 .unwrap()
4337 .get_local_repo(&root_entry)
4338 .unwrap();
4339
4340 if local_repo_entry.git_dir_scan_id > *git_dir_scan_id {
4341 *git_dir_scan_id = local_repo_entry.git_dir_scan_id;
4342 true
4343 } else {
4344 false
4345 }
4346 };
4347
4348 async move {
4349 fs.create_file(&root_path.join(file_name), Default::default())
4350 .await
4351 .unwrap();
4352
4353 cx.condition(&tree, |tree, _| {
4354 scan_id_increased(tree, &mut git_dir_scan_id)
4355 })
4356 .await;
4357
4358 fs.remove_file(&root_path.join(file_name), Default::default())
4359 .await
4360 .unwrap();
4361
4362 cx.condition(&tree, |tree, _| {
4363 scan_id_increased(tree, &mut git_dir_scan_id)
4364 })
4365 .await;
4366
4367 cx.update(|cx| tree.read(cx).as_local().unwrap().scan_complete())
4368 .await;
4369 }
4370 .boxed_local()
4371 }
4372}
4373
4374#[derive(Clone, Debug)]
4375struct TraversalProgress<'a> {
4376 max_path: &'a Path,
4377 count: usize,
4378 non_ignored_count: usize,
4379 file_count: usize,
4380 non_ignored_file_count: usize,
4381}
4382
4383impl<'a> TraversalProgress<'a> {
4384 fn count(&self, include_files: bool, include_dirs: bool, include_ignored: bool) -> usize {
4385 match (include_files, include_dirs, include_ignored) {
4386 (true, true, true) => self.count,
4387 (true, true, false) => self.non_ignored_count,
4388 (true, false, true) => self.file_count,
4389 (true, false, false) => self.non_ignored_file_count,
4390 (false, true, true) => self.count - self.file_count,
4391 (false, true, false) => self.non_ignored_count - self.non_ignored_file_count,
4392 (false, false, _) => 0,
4393 }
4394 }
4395}
4396
4397impl<'a> sum_tree::Dimension<'a, EntrySummary> for TraversalProgress<'a> {
4398 fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
4399 self.max_path = summary.max_path.as_ref();
4400 self.count += summary.count;
4401 self.non_ignored_count += summary.non_ignored_count;
4402 self.file_count += summary.file_count;
4403 self.non_ignored_file_count += summary.non_ignored_file_count;
4404 }
4405}
4406
4407impl<'a> Default for TraversalProgress<'a> {
4408 fn default() -> Self {
4409 Self {
4410 max_path: Path::new(""),
4411 count: 0,
4412 non_ignored_count: 0,
4413 file_count: 0,
4414 non_ignored_file_count: 0,
4415 }
4416 }
4417}
4418
4419#[derive(Clone, Debug, Default, Copy)]
4420struct GitStatuses {
4421 added: usize,
4422 modified: usize,
4423 conflict: usize,
4424}
4425
4426impl AddAssign for GitStatuses {
4427 fn add_assign(&mut self, rhs: Self) {
4428 self.added += rhs.added;
4429 self.modified += rhs.modified;
4430 self.conflict += rhs.conflict;
4431 }
4432}
4433
4434impl Sub for GitStatuses {
4435 type Output = GitStatuses;
4436
4437 fn sub(self, rhs: Self) -> Self::Output {
4438 GitStatuses {
4439 added: self.added - rhs.added,
4440 modified: self.modified - rhs.modified,
4441 conflict: self.conflict - rhs.conflict,
4442 }
4443 }
4444}
4445
4446impl<'a> sum_tree::Dimension<'a, EntrySummary> for GitStatuses {
4447 fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
4448 *self += summary.statuses
4449 }
4450}
4451
4452pub struct Traversal<'a> {
4453 cursor: sum_tree::Cursor<'a, Entry, TraversalProgress<'a>>,
4454 include_ignored: bool,
4455 include_files: bool,
4456 include_dirs: bool,
4457}
4458
4459impl<'a> Traversal<'a> {
4460 fn new(
4461 entries: &'a SumTree<Entry>,
4462 include_files: bool,
4463 include_dirs: bool,
4464 include_ignored: bool,
4465 start_path: &Path,
4466 ) -> Self {
4467 let mut cursor = entries.cursor();
4468 cursor.seek(&TraversalTarget::Path(start_path), Bias::Left, &());
4469 let mut traversal = Self {
4470 cursor,
4471 include_files,
4472 include_dirs,
4473 include_ignored,
4474 };
4475 if traversal.end_offset() == traversal.start_offset() {
4476 traversal.next();
4477 }
4478 traversal
4479 }
4480 pub fn advance(&mut self) -> bool {
4481 self.advance_by(1)
4482 }
4483
4484 pub fn advance_by(&mut self, count: usize) -> bool {
4485 self.cursor.seek_forward(
4486 &TraversalTarget::Count {
4487 count: self.end_offset() + count,
4488 include_dirs: self.include_dirs,
4489 include_files: self.include_files,
4490 include_ignored: self.include_ignored,
4491 },
4492 Bias::Left,
4493 &(),
4494 )
4495 }
4496
4497 pub fn advance_to_sibling(&mut self) -> bool {
4498 while let Some(entry) = self.cursor.item() {
4499 self.cursor.seek_forward(
4500 &TraversalTarget::PathSuccessor(&entry.path),
4501 Bias::Left,
4502 &(),
4503 );
4504 if let Some(entry) = self.cursor.item() {
4505 if (self.include_files || !entry.is_file())
4506 && (self.include_dirs || !entry.is_dir())
4507 && (self.include_ignored || !entry.is_ignored)
4508 {
4509 return true;
4510 }
4511 }
4512 }
4513 false
4514 }
4515
4516 pub fn entry(&self) -> Option<&'a Entry> {
4517 self.cursor.item()
4518 }
4519
4520 pub fn start_offset(&self) -> usize {
4521 self.cursor
4522 .start()
4523 .count(self.include_files, self.include_dirs, self.include_ignored)
4524 }
4525
4526 pub fn end_offset(&self) -> usize {
4527 self.cursor
4528 .end(&())
4529 .count(self.include_files, self.include_dirs, self.include_ignored)
4530 }
4531}
4532
4533impl<'a> Iterator for Traversal<'a> {
4534 type Item = &'a Entry;
4535
4536 fn next(&mut self) -> Option<Self::Item> {
4537 if let Some(item) = self.entry() {
4538 self.advance();
4539 Some(item)
4540 } else {
4541 None
4542 }
4543 }
4544}
4545
4546#[derive(Debug)]
4547enum TraversalTarget<'a> {
4548 Path(&'a Path),
4549 PathSuccessor(&'a Path),
4550 Count {
4551 count: usize,
4552 include_files: bool,
4553 include_ignored: bool,
4554 include_dirs: bool,
4555 },
4556}
4557
4558impl<'a, 'b> SeekTarget<'a, EntrySummary, TraversalProgress<'a>> for TraversalTarget<'b> {
4559 fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: &()) -> Ordering {
4560 match self {
4561 TraversalTarget::Path(path) => path.cmp(&cursor_location.max_path),
4562 TraversalTarget::PathSuccessor(path) => {
4563 if cursor_location.max_path.starts_with(path) {
4564 Ordering::Greater
4565 } else {
4566 Ordering::Equal
4567 }
4568 }
4569 TraversalTarget::Count {
4570 count,
4571 include_files,
4572 include_dirs,
4573 include_ignored,
4574 } => Ord::cmp(
4575 count,
4576 &cursor_location.count(*include_files, *include_dirs, *include_ignored),
4577 ),
4578 }
4579 }
4580}
4581
4582impl<'a, 'b> SeekTarget<'a, EntrySummary, (TraversalProgress<'a>, GitStatuses)>
4583 for TraversalTarget<'b>
4584{
4585 fn cmp(&self, cursor_location: &(TraversalProgress<'a>, GitStatuses), _: &()) -> Ordering {
4586 self.cmp(&cursor_location.0, &())
4587 }
4588}
4589
4590pub struct ChildEntriesIter<'a> {
4591 parent_path: &'a Path,
4592 traversal: Traversal<'a>,
4593}
4594
4595impl<'a> Iterator for ChildEntriesIter<'a> {
4596 type Item = &'a Entry;
4597
4598 fn next(&mut self) -> Option<Self::Item> {
4599 if let Some(item) = self.traversal.entry() {
4600 if item.path.starts_with(&self.parent_path) {
4601 self.traversal.advance_to_sibling();
4602 return Some(item);
4603 }
4604 }
4605 None
4606 }
4607}
4608
4609impl<'a> From<&'a Entry> for proto::Entry {
4610 fn from(entry: &'a Entry) -> Self {
4611 Self {
4612 id: entry.id.to_proto(),
4613 is_dir: entry.is_dir(),
4614 path: entry.path.to_string_lossy().into(),
4615 inode: entry.inode,
4616 mtime: entry.mtime.map(|time| time.into()),
4617 is_symlink: entry.is_symlink,
4618 is_ignored: entry.is_ignored,
4619 is_external: entry.is_external,
4620 git_status: entry.git_status.map(git_status_to_proto),
4621 }
4622 }
4623}
4624
4625impl<'a> TryFrom<(&'a CharBag, proto::Entry)> for Entry {
4626 type Error = anyhow::Error;
4627
4628 fn try_from((root_char_bag, entry): (&'a CharBag, proto::Entry)) -> Result<Self> {
4629 let kind = if entry.is_dir {
4630 EntryKind::Dir
4631 } else {
4632 let mut char_bag = *root_char_bag;
4633 char_bag.extend(entry.path.chars().map(|c| c.to_ascii_lowercase()));
4634 EntryKind::File(char_bag)
4635 };
4636 let path: Arc<Path> = PathBuf::from(entry.path).into();
4637 Ok(Entry {
4638 id: ProjectEntryId::from_proto(entry.id),
4639 kind,
4640 path,
4641 inode: entry.inode,
4642 mtime: entry.mtime.map(|time| time.into()),
4643 canonical_path: None,
4644 is_ignored: entry.is_ignored,
4645 is_external: entry.is_external,
4646 git_status: git_status_from_proto(entry.git_status),
4647 is_private: false,
4648 is_symlink: entry.is_symlink,
4649 })
4650 }
4651}
4652
4653fn git_status_from_proto(git_status: Option<i32>) -> Option<GitFileStatus> {
4654 git_status.and_then(|status| {
4655 proto::GitStatus::from_i32(status).map(|status| match status {
4656 proto::GitStatus::Added => GitFileStatus::Added,
4657 proto::GitStatus::Modified => GitFileStatus::Modified,
4658 proto::GitStatus::Conflict => GitFileStatus::Conflict,
4659 })
4660 })
4661}
4662
4663fn git_status_to_proto(status: GitFileStatus) -> i32 {
4664 match status {
4665 GitFileStatus::Added => proto::GitStatus::Added as i32,
4666 GitFileStatus::Modified => proto::GitStatus::Modified as i32,
4667 GitFileStatus::Conflict => proto::GitStatus::Conflict as i32,
4668 }
4669}
4670
4671#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
4672pub struct ProjectEntryId(usize);
4673
4674impl ProjectEntryId {
4675 pub const MAX: Self = Self(usize::MAX);
4676 pub const MIN: Self = Self(usize::MIN);
4677
4678 pub fn new(counter: &AtomicUsize) -> Self {
4679 Self(counter.fetch_add(1, SeqCst))
4680 }
4681
4682 pub fn from_proto(id: u64) -> Self {
4683 Self(id as usize)
4684 }
4685
4686 pub fn to_proto(&self) -> u64 {
4687 self.0 as u64
4688 }
4689
4690 pub fn to_usize(&self) -> usize {
4691 self.0
4692 }
4693}
4694
4695#[cfg(any(test, feature = "test-support"))]
4696impl CreatedEntry {
4697 pub fn to_included(self) -> Option<Entry> {
4698 match self {
4699 CreatedEntry::Included(entry) => Some(entry),
4700 CreatedEntry::Excluded { .. } => None,
4701 }
4702 }
4703}