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