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 let Ok(ignore) =
4296 build_gitignore(&ancestor.join(*GITIGNORE), self.fs.as_ref()).await
4297 {
4298 self.state
4299 .lock()
4300 .snapshot
4301 .ignores_by_parent_abs_path
4302 .insert(ancestor.into(), (ignore.into(), false));
4303 }
4304 }
4305
4306 let ancestor_dot_git = ancestor.join(*DOT_GIT);
4307 log::debug!("considering ancestor: {ancestor_dot_git:?}");
4308 // Check whether the directory or file called `.git` exists (in the
4309 // case of worktrees it's a file.)
4310 if self
4311 .fs
4312 .metadata(&ancestor_dot_git)
4313 .await
4314 .is_ok_and(|metadata| metadata.is_some())
4315 {
4316 log::debug!(".git path exists");
4317 if index != 0 {
4318 // We canonicalize, since the FS events use the canonicalized path.
4319 if let Some(ancestor_dot_git) =
4320 self.fs.canonicalize(&ancestor_dot_git).await.log_err()
4321 {
4322 let location_in_repo = root_abs_path
4323 .as_path()
4324 .strip_prefix(ancestor)
4325 .unwrap()
4326 .into();
4327 log::debug!(
4328 "inserting parent git repo for this worktree: {location_in_repo:?}"
4329 );
4330 // We associate the external git repo with our root folder and
4331 // also mark where in the git repo the root folder is located.
4332 let local_repository = self.state.lock().insert_git_repository_for_path(
4333 WorkDirectory::AboveProject {
4334 absolute_path: ancestor.into(),
4335 location_in_repo,
4336 },
4337 ancestor_dot_git.clone().into(),
4338 self.fs.as_ref(),
4339 self.watcher.as_ref(),
4340 );
4341
4342 if local_repository.is_some() {
4343 containing_git_repository = Some(ancestor_dot_git)
4344 }
4345 };
4346 }
4347
4348 // Reached root of git repository.
4349 break;
4350 } else {
4351 log::debug!(".git path doesn't exist");
4352 }
4353 }
4354
4355 log::debug!("containing git repository: {containing_git_repository:?}");
4356
4357 let (scan_job_tx, scan_job_rx) = channel::unbounded();
4358 {
4359 let mut state = self.state.lock();
4360 state.snapshot.scan_id += 1;
4361 if let Some(mut root_entry) = state.snapshot.root_entry().cloned() {
4362 let ignore_stack = state
4363 .snapshot
4364 .ignore_stack_for_abs_path(root_abs_path.as_path(), true);
4365 if ignore_stack.is_abs_path_ignored(root_abs_path.as_path(), true) {
4366 root_entry.is_ignored = true;
4367 state.insert_entry(root_entry.clone(), self.fs.as_ref(), self.watcher.as_ref());
4368 }
4369 state.enqueue_scan_dir(root_abs_path.into(), &root_entry, &scan_job_tx);
4370 }
4371 };
4372
4373 // Perform an initial scan of the directory.
4374 drop(scan_job_tx);
4375 let scans_running = self.scan_dirs(true, scan_job_rx).await;
4376 {
4377 let mut state = self.state.lock();
4378 state.snapshot.completed_scan_id = state.snapshot.scan_id;
4379 }
4380
4381 let scanning = scans_running.status_scans.load(atomic::Ordering::Acquire) > 0;
4382 self.send_status_update(scanning, SmallVec::new());
4383
4384 // Process any any FS events that occurred while performing the initial scan.
4385 // For these events, update events cannot be as precise, because we didn't
4386 // have the previous state loaded yet.
4387 self.phase = BackgroundScannerPhase::EventsReceivedDuringInitialScan;
4388 if let Poll::Ready(Some(mut paths)) = futures::poll!(fs_events_rx.next()) {
4389 while let Poll::Ready(Some(more_paths)) = futures::poll!(fs_events_rx.next()) {
4390 paths.extend(more_paths);
4391 }
4392 self.process_events(paths.into_iter().map(Into::into).collect())
4393 .await;
4394 }
4395 if let Some(abs_path) = containing_git_repository {
4396 self.process_events(vec![abs_path]).await;
4397 }
4398
4399 // Continue processing events until the worktree is dropped.
4400 self.phase = BackgroundScannerPhase::Events;
4401
4402 loop {
4403 select_biased! {
4404 // Process any path refresh requests from the worktree. Prioritize
4405 // these before handling changes reported by the filesystem.
4406 request = self.next_scan_request().fuse() => {
4407 let Ok(request) = request else { break };
4408 let scanning = scans_running.status_scans.load(atomic::Ordering::Acquire) > 0;
4409 if !self.process_scan_request(request, scanning).await {
4410 return;
4411 }
4412 }
4413
4414 path_prefix_request = self.path_prefixes_to_scan_rx.recv().fuse() => {
4415 let Ok(request) = path_prefix_request else { break };
4416 log::trace!("adding path prefix {:?}", request.path);
4417
4418 let did_scan = self.forcibly_load_paths(&[request.path.clone()]).await;
4419 if did_scan {
4420 let abs_path =
4421 {
4422 let mut state = self.state.lock();
4423 state.path_prefixes_to_scan.insert(request.path.clone());
4424 state.snapshot.abs_path.as_path().join(&request.path)
4425 };
4426
4427 if let Some(abs_path) = self.fs.canonicalize(&abs_path).await.log_err() {
4428 self.process_events(vec![abs_path]).await;
4429 }
4430 }
4431 let scanning = scans_running.status_scans.load(atomic::Ordering::Acquire) > 0;
4432 self.send_status_update(scanning, request.done);
4433 }
4434
4435 paths = fs_events_rx.next().fuse() => {
4436 let Some(mut paths) = paths else { break };
4437 while let Poll::Ready(Some(more_paths)) = futures::poll!(fs_events_rx.next()) {
4438 paths.extend(more_paths);
4439 }
4440 self.process_events(paths.into_iter().map(Into::into).collect()).await;
4441 }
4442 }
4443 }
4444 }
4445
4446 async fn process_scan_request(&self, mut request: ScanRequest, scanning: bool) -> bool {
4447 log::debug!("rescanning paths {:?}", request.relative_paths);
4448
4449 request.relative_paths.sort_unstable();
4450 self.forcibly_load_paths(&request.relative_paths).await;
4451
4452 let root_path = self.state.lock().snapshot.abs_path.clone();
4453 let root_canonical_path = match self.fs.canonicalize(root_path.as_path()).await {
4454 Ok(path) => SanitizedPath::from(path),
4455 Err(err) => {
4456 log::error!("failed to canonicalize root path: {}", err);
4457 return true;
4458 }
4459 };
4460 let abs_paths = request
4461 .relative_paths
4462 .iter()
4463 .map(|path| {
4464 if path.file_name().is_some() {
4465 root_canonical_path.as_path().join(path).to_path_buf()
4466 } else {
4467 root_canonical_path.as_path().to_path_buf()
4468 }
4469 })
4470 .collect::<Vec<_>>();
4471
4472 {
4473 let mut state = self.state.lock();
4474 let is_idle = state.snapshot.completed_scan_id == state.snapshot.scan_id;
4475 state.snapshot.scan_id += 1;
4476 if is_idle {
4477 state.snapshot.completed_scan_id = state.snapshot.scan_id;
4478 }
4479 }
4480
4481 self.reload_entries_for_paths(
4482 root_path,
4483 root_canonical_path,
4484 &request.relative_paths,
4485 abs_paths,
4486 None,
4487 )
4488 .await;
4489
4490 self.send_status_update(scanning, request.done)
4491 }
4492
4493 async fn process_events(&self, mut abs_paths: Vec<PathBuf>) {
4494 let root_path = self.state.lock().snapshot.abs_path.clone();
4495 let root_canonical_path = match self.fs.canonicalize(root_path.as_path()).await {
4496 Ok(path) => SanitizedPath::from(path),
4497 Err(err) => {
4498 let new_path = self
4499 .state
4500 .lock()
4501 .snapshot
4502 .root_file_handle
4503 .clone()
4504 .and_then(|handle| handle.current_path(&self.fs).log_err())
4505 .map(SanitizedPath::from)
4506 .filter(|new_path| *new_path != root_path);
4507
4508 if let Some(new_path) = new_path.as_ref() {
4509 log::info!(
4510 "root renamed from {} to {}",
4511 root_path.as_path().display(),
4512 new_path.as_path().display()
4513 )
4514 } else {
4515 log::warn!("root path could not be canonicalized: {}", err);
4516 }
4517 self.status_updates_tx
4518 .unbounded_send(ScanState::RootUpdated { new_path })
4519 .ok();
4520 return;
4521 }
4522 };
4523
4524 // Certain directories may have FS changes, but do not lead to git data changes that Zed cares about.
4525 // Ignore these, to avoid Zed unnecessarily rescanning git metadata.
4526 let skipped_files_in_dot_git = HashSet::from_iter([*COMMIT_MESSAGE, *INDEX_LOCK]);
4527 let skipped_dirs_in_dot_git = [*FSMONITOR_DAEMON, *LFS_DIR];
4528
4529 let mut relative_paths = Vec::with_capacity(abs_paths.len());
4530 let mut dot_git_abs_paths = Vec::new();
4531 abs_paths.sort_unstable();
4532 abs_paths.dedup_by(|a, b| a.starts_with(b));
4533 abs_paths.retain(|abs_path| {
4534 let abs_path = SanitizedPath::from(abs_path);
4535
4536 let snapshot = &self.state.lock().snapshot;
4537 {
4538 let mut is_git_related = false;
4539
4540 let dot_git_paths = abs_path.as_path().ancestors().find_map(|ancestor| {
4541 if smol::block_on(is_git_dir(ancestor, self.fs.as_ref())) {
4542 let path_in_git_dir = abs_path.as_path().strip_prefix(ancestor).expect("stripping off the ancestor");
4543 Some((ancestor.to_owned(), path_in_git_dir.to_owned()))
4544 } else {
4545 None
4546 }
4547 });
4548
4549 if let Some((dot_git_abs_path, path_in_git_dir)) = dot_git_paths {
4550 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)) {
4551 log::debug!("ignoring event {abs_path:?} as it's in the .git directory among skipped files or directories");
4552 return false;
4553 }
4554
4555 is_git_related = true;
4556 if !dot_git_abs_paths.contains(&dot_git_abs_path) {
4557 dot_git_abs_paths.push(dot_git_abs_path);
4558 }
4559 }
4560
4561 let relative_path: Arc<Path> =
4562 if let Ok(path) = abs_path.strip_prefix(&root_canonical_path) {
4563 path.into()
4564 } else {
4565 if is_git_related {
4566 log::debug!(
4567 "ignoring event {abs_path:?}, since it's in git dir outside of root path {root_canonical_path:?}",
4568 );
4569 } else {
4570 log::error!(
4571 "ignoring event {abs_path:?} outside of root path {root_canonical_path:?}",
4572 );
4573 }
4574 return false;
4575 };
4576
4577 if abs_path.0.file_name() == Some(*GITIGNORE) {
4578 for (_, repo) in snapshot.git_repositories.iter().filter(|(_, repo)| repo.directory_contains(&relative_path)) {
4579 if !dot_git_abs_paths.iter().any(|dot_git_abs_path| dot_git_abs_path == repo.dot_git_dir_abs_path.as_ref()) {
4580 dot_git_abs_paths.push(repo.dot_git_dir_abs_path.to_path_buf());
4581 }
4582 }
4583 }
4584
4585 let parent_dir_is_loaded = relative_path.parent().map_or(true, |parent| {
4586 snapshot
4587 .entry_for_path(parent)
4588 .map_or(false, |entry| entry.kind == EntryKind::Dir)
4589 });
4590 if !parent_dir_is_loaded {
4591 log::debug!("ignoring event {relative_path:?} within unloaded directory");
4592 return false;
4593 }
4594
4595 if self.settings.is_path_excluded(&relative_path) {
4596 if !is_git_related {
4597 log::debug!("ignoring FS event for excluded path {relative_path:?}");
4598 }
4599 return false;
4600 }
4601
4602 relative_paths.push(relative_path);
4603 true
4604 }
4605 });
4606
4607 if relative_paths.is_empty() && dot_git_abs_paths.is_empty() {
4608 return;
4609 }
4610
4611 self.state.lock().snapshot.scan_id += 1;
4612
4613 let (scan_job_tx, scan_job_rx) = channel::unbounded();
4614 log::debug!("received fs events {:?}", relative_paths);
4615 self.reload_entries_for_paths(
4616 root_path,
4617 root_canonical_path,
4618 &relative_paths,
4619 abs_paths,
4620 Some(scan_job_tx.clone()),
4621 )
4622 .await;
4623
4624 self.update_ignore_statuses(scan_job_tx).await;
4625 let scans_running = self.scan_dirs(false, scan_job_rx).await;
4626
4627 let status_update = if !dot_git_abs_paths.is_empty() {
4628 Some(self.update_git_repositories(dot_git_abs_paths))
4629 } else {
4630 None
4631 };
4632
4633 let phase = self.phase;
4634 let status_update_tx = self.status_updates_tx.clone();
4635 let state = self.state.clone();
4636 self.executor
4637 .spawn(async move {
4638 if let Some(status_update) = status_update {
4639 status_update.await;
4640 }
4641
4642 {
4643 let mut state = state.lock();
4644 state.snapshot.completed_scan_id = state.snapshot.scan_id;
4645 for (_, entry) in mem::take(&mut state.removed_entries) {
4646 state.scanned_dirs.remove(&entry.id);
4647 }
4648 #[cfg(test)]
4649 state.snapshot.check_git_invariants();
4650 }
4651 let scanning = scans_running.status_scans.load(atomic::Ordering::Acquire) > 0;
4652 send_status_update_inner(phase, state, status_update_tx, scanning, SmallVec::new());
4653 })
4654 .detach();
4655 }
4656
4657 async fn forcibly_load_paths(&self, paths: &[Arc<Path>]) -> bool {
4658 let (scan_job_tx, scan_job_rx) = channel::unbounded();
4659 {
4660 let mut state = self.state.lock();
4661 let root_path = state.snapshot.abs_path.clone();
4662 for path in paths {
4663 for ancestor in path.ancestors() {
4664 if let Some(entry) = state.snapshot.entry_for_path(ancestor) {
4665 if entry.kind == EntryKind::UnloadedDir {
4666 let abs_path = root_path.as_path().join(ancestor);
4667 state.enqueue_scan_dir(abs_path.into(), entry, &scan_job_tx);
4668 state.paths_to_scan.insert(path.clone());
4669 break;
4670 }
4671 }
4672 }
4673 }
4674 drop(scan_job_tx);
4675 }
4676 let scans_running = Arc::new(AtomicU32::new(0));
4677 while let Ok(job) = scan_job_rx.recv().await {
4678 self.scan_dir(&scans_running, &job).await.log_err();
4679 }
4680
4681 !mem::take(&mut self.state.lock().paths_to_scan).is_empty()
4682 }
4683
4684 async fn scan_dirs(
4685 &self,
4686 enable_progress_updates: bool,
4687 scan_jobs_rx: channel::Receiver<ScanJob>,
4688 ) -> FsScanned {
4689 if self
4690 .status_updates_tx
4691 .unbounded_send(ScanState::Started)
4692 .is_err()
4693 {
4694 return FsScanned::default();
4695 }
4696
4697 let scans_running = Arc::new(AtomicU32::new(1));
4698 let progress_update_count = AtomicUsize::new(0);
4699 self.executor
4700 .scoped(|scope| {
4701 for _ in 0..self.executor.num_cpus() {
4702 scope.spawn(async {
4703 let mut last_progress_update_count = 0;
4704 let progress_update_timer = self.progress_timer(enable_progress_updates).fuse();
4705 futures::pin_mut!(progress_update_timer);
4706
4707 loop {
4708 select_biased! {
4709 // Process any path refresh requests before moving on to process
4710 // the scan queue, so that user operations are prioritized.
4711 request = self.next_scan_request().fuse() => {
4712 let Ok(request) = request else { break };
4713 if !self.process_scan_request(request, true).await {
4714 return;
4715 }
4716 }
4717
4718 // Send periodic progress updates to the worktree. Use an atomic counter
4719 // to ensure that only one of the workers sends a progress update after
4720 // the update interval elapses.
4721 _ = progress_update_timer => {
4722 match progress_update_count.compare_exchange(
4723 last_progress_update_count,
4724 last_progress_update_count + 1,
4725 SeqCst,
4726 SeqCst
4727 ) {
4728 Ok(_) => {
4729 last_progress_update_count += 1;
4730 self.send_status_update(true, SmallVec::new());
4731 }
4732 Err(count) => {
4733 last_progress_update_count = count;
4734 }
4735 }
4736 progress_update_timer.set(self.progress_timer(enable_progress_updates).fuse());
4737 }
4738
4739 // Recursively load directories from the file system.
4740 job = scan_jobs_rx.recv().fuse() => {
4741 let Ok(job) = job else { break };
4742 if let Err(err) = self.scan_dir(&scans_running, &job).await {
4743 if job.path.as_ref() != Path::new("") {
4744 log::error!("error scanning directory {:?}: {}", job.abs_path, err);
4745 }
4746 }
4747 }
4748 }
4749 }
4750 });
4751 }
4752 })
4753 .await;
4754
4755 scans_running.fetch_sub(1, atomic::Ordering::Release);
4756 FsScanned {
4757 status_scans: scans_running,
4758 }
4759 }
4760
4761 fn send_status_update(&self, scanning: bool, barrier: SmallVec<[barrier::Sender; 1]>) -> bool {
4762 send_status_update_inner(
4763 self.phase,
4764 self.state.clone(),
4765 self.status_updates_tx.clone(),
4766 scanning,
4767 barrier,
4768 )
4769 }
4770
4771 async fn scan_dir(&self, scans_running: &Arc<AtomicU32>, job: &ScanJob) -> Result<()> {
4772 let root_abs_path;
4773 let root_char_bag;
4774 {
4775 let snapshot = &self.state.lock().snapshot;
4776 if self.settings.is_path_excluded(&job.path) {
4777 log::error!("skipping excluded directory {:?}", job.path);
4778 return Ok(());
4779 }
4780 log::debug!("scanning directory {:?}", job.path);
4781 root_abs_path = snapshot.abs_path().clone();
4782 root_char_bag = snapshot.root_char_bag;
4783 }
4784
4785 let next_entry_id = self.next_entry_id.clone();
4786 let mut ignore_stack = job.ignore_stack.clone();
4787 let mut new_ignore = None;
4788 let mut root_canonical_path = None;
4789 let mut new_entries: Vec<Entry> = Vec::new();
4790 let mut new_jobs: Vec<Option<ScanJob>> = Vec::new();
4791 let mut child_paths = self
4792 .fs
4793 .read_dir(&job.abs_path)
4794 .await?
4795 .filter_map(|entry| async {
4796 match entry {
4797 Ok(entry) => Some(entry),
4798 Err(error) => {
4799 log::error!("error processing entry {:?}", error);
4800 None
4801 }
4802 }
4803 })
4804 .collect::<Vec<_>>()
4805 .await;
4806
4807 // Ensure that .git and .gitignore are processed first.
4808 swap_to_front(&mut child_paths, *GITIGNORE);
4809 swap_to_front(&mut child_paths, *DOT_GIT);
4810
4811 let mut git_status_update_jobs = Vec::new();
4812 for child_abs_path in child_paths {
4813 let child_abs_path: Arc<Path> = child_abs_path.into();
4814 let child_name = child_abs_path.file_name().unwrap();
4815 let child_path: Arc<Path> = job.path.join(child_name).into();
4816
4817 if child_name == *DOT_GIT {
4818 {
4819 let mut state = self.state.lock();
4820 let repo = state.insert_git_repository(
4821 child_path.clone(),
4822 self.fs.as_ref(),
4823 self.watcher.as_ref(),
4824 );
4825 if let Some(local_repo) = repo {
4826 scans_running.fetch_add(1, atomic::Ordering::Release);
4827 git_status_update_jobs
4828 .push(self.schedule_git_statuses_update(&mut state, local_repo));
4829 }
4830 }
4831 } else if child_name == *GITIGNORE {
4832 match build_gitignore(&child_abs_path, self.fs.as_ref()).await {
4833 Ok(ignore) => {
4834 let ignore = Arc::new(ignore);
4835 ignore_stack = ignore_stack.append(job.abs_path.clone(), ignore.clone());
4836 new_ignore = Some(ignore);
4837 }
4838 Err(error) => {
4839 log::error!(
4840 "error loading .gitignore file {:?} - {:?}",
4841 child_name,
4842 error
4843 );
4844 }
4845 }
4846 }
4847
4848 if self.settings.is_path_excluded(&child_path) {
4849 log::debug!("skipping excluded child entry {child_path:?}");
4850 self.state.lock().remove_path(&child_path);
4851 continue;
4852 }
4853
4854 let child_metadata = match self.fs.metadata(&child_abs_path).await {
4855 Ok(Some(metadata)) => metadata,
4856 Ok(None) => continue,
4857 Err(err) => {
4858 log::error!("error processing {child_abs_path:?}: {err:?}");
4859 continue;
4860 }
4861 };
4862
4863 let mut child_entry = Entry::new(
4864 child_path.clone(),
4865 &child_metadata,
4866 &next_entry_id,
4867 root_char_bag,
4868 None,
4869 );
4870
4871 if job.is_external {
4872 child_entry.is_external = true;
4873 } else if child_metadata.is_symlink {
4874 let canonical_path = match self.fs.canonicalize(&child_abs_path).await {
4875 Ok(path) => path,
4876 Err(err) => {
4877 log::error!(
4878 "error reading target of symlink {:?}: {:?}",
4879 child_abs_path,
4880 err
4881 );
4882 continue;
4883 }
4884 };
4885
4886 // lazily canonicalize the root path in order to determine if
4887 // symlinks point outside of the worktree.
4888 let root_canonical_path = match &root_canonical_path {
4889 Some(path) => path,
4890 None => match self.fs.canonicalize(&root_abs_path).await {
4891 Ok(path) => root_canonical_path.insert(path),
4892 Err(err) => {
4893 log::error!("error canonicalizing root {:?}: {:?}", root_abs_path, err);
4894 continue;
4895 }
4896 },
4897 };
4898
4899 if !canonical_path.starts_with(root_canonical_path) {
4900 child_entry.is_external = true;
4901 }
4902
4903 child_entry.canonical_path = Some(canonical_path.into());
4904 }
4905
4906 if child_entry.is_dir() {
4907 child_entry.is_ignored = ignore_stack.is_abs_path_ignored(&child_abs_path, true);
4908 child_entry.is_always_included = self.settings.is_path_always_included(&child_path);
4909
4910 // Avoid recursing until crash in the case of a recursive symlink
4911 if job.ancestor_inodes.contains(&child_entry.inode) {
4912 new_jobs.push(None);
4913 } else {
4914 let mut ancestor_inodes = job.ancestor_inodes.clone();
4915 ancestor_inodes.insert(child_entry.inode);
4916
4917 new_jobs.push(Some(ScanJob {
4918 abs_path: child_abs_path.clone(),
4919 path: child_path,
4920 is_external: child_entry.is_external,
4921 ignore_stack: if child_entry.is_ignored {
4922 IgnoreStack::all()
4923 } else {
4924 ignore_stack.clone()
4925 },
4926 ancestor_inodes,
4927 scan_queue: job.scan_queue.clone(),
4928 }));
4929 }
4930 } else {
4931 child_entry.is_ignored = ignore_stack.is_abs_path_ignored(&child_abs_path, false);
4932 child_entry.is_always_included = self.settings.is_path_always_included(&child_path);
4933 }
4934
4935 {
4936 let relative_path = job.path.join(child_name);
4937 if self.is_path_private(&relative_path) {
4938 log::debug!("detected private file: {relative_path:?}");
4939 child_entry.is_private = true;
4940 }
4941 }
4942
4943 new_entries.push(child_entry);
4944 }
4945
4946 let task_state = self.state.clone();
4947 let phase = self.phase;
4948 let status_updates_tx = self.status_updates_tx.clone();
4949 let scans_running = scans_running.clone();
4950 self.executor
4951 .spawn(async move {
4952 if !git_status_update_jobs.is_empty() {
4953 let status_updates = join_all(git_status_update_jobs).await;
4954 let status_updated = status_updates
4955 .iter()
4956 .any(|update_result| update_result.is_ok());
4957 scans_running.fetch_sub(status_updates.len() as u32, atomic::Ordering::Release);
4958 if status_updated {
4959 let scanning = scans_running.load(atomic::Ordering::Acquire) > 0;
4960 send_status_update_inner(
4961 phase,
4962 task_state,
4963 status_updates_tx,
4964 scanning,
4965 SmallVec::new(),
4966 );
4967 }
4968 }
4969 })
4970 .detach();
4971
4972 let mut state = self.state.lock();
4973
4974 // Identify any subdirectories that should not be scanned.
4975 let mut job_ix = 0;
4976 for entry in &mut new_entries {
4977 state.reuse_entry_id(entry);
4978 if entry.is_dir() {
4979 if state.should_scan_directory(entry) {
4980 job_ix += 1;
4981 } else {
4982 log::debug!("defer scanning directory {:?}", entry.path);
4983 entry.kind = EntryKind::UnloadedDir;
4984 new_jobs.remove(job_ix);
4985 }
4986 }
4987 if entry.is_always_included {
4988 state
4989 .snapshot
4990 .always_included_entries
4991 .push(entry.path.clone());
4992 }
4993 }
4994
4995 state.populate_dir(&job.path, new_entries, new_ignore);
4996 self.watcher.add(job.abs_path.as_ref()).log_err();
4997
4998 for new_job in new_jobs.into_iter().flatten() {
4999 job.scan_queue
5000 .try_send(new_job)
5001 .expect("channel is unbounded");
5002 }
5003
5004 Ok(())
5005 }
5006
5007 /// All list arguments should be sorted before calling this function
5008 async fn reload_entries_for_paths(
5009 &self,
5010 root_abs_path: SanitizedPath,
5011 root_canonical_path: SanitizedPath,
5012 relative_paths: &[Arc<Path>],
5013 abs_paths: Vec<PathBuf>,
5014 scan_queue_tx: Option<Sender<ScanJob>>,
5015 ) {
5016 // grab metadata for all requested paths
5017 let metadata = futures::future::join_all(
5018 abs_paths
5019 .iter()
5020 .map(|abs_path| async move {
5021 let metadata = self.fs.metadata(abs_path).await?;
5022 if let Some(metadata) = metadata {
5023 let canonical_path = self.fs.canonicalize(abs_path).await?;
5024
5025 // If we're on a case-insensitive filesystem (default on macOS), we want
5026 // to only ignore metadata for non-symlink files if their absolute-path matches
5027 // the canonical-path.
5028 // Because if not, this might be a case-only-renaming (`mv test.txt TEST.TXT`)
5029 // and we want to ignore the metadata for the old path (`test.txt`) so it's
5030 // treated as removed.
5031 if !self.fs_case_sensitive && !metadata.is_symlink {
5032 let canonical_file_name = canonical_path.file_name();
5033 let file_name = abs_path.file_name();
5034 if canonical_file_name != file_name {
5035 return Ok(None);
5036 }
5037 }
5038
5039 anyhow::Ok(Some((metadata, SanitizedPath::from(canonical_path))))
5040 } else {
5041 Ok(None)
5042 }
5043 })
5044 .collect::<Vec<_>>(),
5045 )
5046 .await;
5047
5048 let mut state = self.state.lock();
5049 let doing_recursive_update = scan_queue_tx.is_some();
5050
5051 // Remove any entries for paths that no longer exist or are being recursively
5052 // refreshed. Do this before adding any new entries, so that renames can be
5053 // detected regardless of the order of the paths.
5054 for (path, metadata) in relative_paths.iter().zip(metadata.iter()) {
5055 if matches!(metadata, Ok(None)) || doing_recursive_update {
5056 log::trace!("remove path {:?}", path);
5057 state.remove_path(path);
5058 }
5059 }
5060
5061 // Group all relative paths by their git repository.
5062 let mut paths_by_git_repo = HashMap::default();
5063 for relative_path in relative_paths.iter() {
5064 let repository_data = state
5065 .snapshot
5066 .local_repo_for_path(relative_path)
5067 .zip(state.snapshot.repository_for_path(relative_path));
5068 if let Some((local_repo, entry)) = repository_data {
5069 if let Ok(repo_path) = local_repo.relativize(relative_path) {
5070 paths_by_git_repo
5071 .entry(local_repo.work_directory.clone())
5072 .or_insert_with(|| RepoPaths {
5073 entry: entry.clone(),
5074 repo: local_repo.repo_ptr.clone(),
5075 repo_paths: Default::default(),
5076 })
5077 .add_path(repo_path);
5078 }
5079 }
5080 }
5081
5082 for (work_directory, mut paths) in paths_by_git_repo {
5083 if let Ok(status) = paths.repo.status(&paths.repo_paths) {
5084 let mut changed_path_statuses = Vec::new();
5085 let statuses = paths.entry.statuses_by_path.clone();
5086 let mut cursor = statuses.cursor::<PathProgress>(&());
5087
5088 for (repo_path, status) in &*status.entries {
5089 paths.remove_repo_path(repo_path);
5090 if cursor.seek_forward(&PathTarget::Path(repo_path), Bias::Left, &()) {
5091 if &cursor.item().unwrap().status == status {
5092 continue;
5093 }
5094 }
5095
5096 changed_path_statuses.push(Edit::Insert(StatusEntry {
5097 repo_path: repo_path.clone(),
5098 status: *status,
5099 }));
5100 }
5101
5102 let mut cursor = statuses.cursor::<PathProgress>(&());
5103 for path in paths.repo_paths {
5104 if cursor.seek_forward(&PathTarget::Path(&path), Bias::Left, &()) {
5105 changed_path_statuses.push(Edit::Remove(PathKey(path.0)));
5106 }
5107 }
5108
5109 if !changed_path_statuses.is_empty() {
5110 let work_directory_id = state.snapshot.repositories.update(
5111 &work_directory.path_key(),
5112 &(),
5113 move |repository_entry| {
5114 repository_entry
5115 .statuses_by_path
5116 .edit(changed_path_statuses, &());
5117
5118 repository_entry.work_directory_id
5119 },
5120 );
5121
5122 if let Some(work_directory_id) = work_directory_id {
5123 let scan_id = state.snapshot.scan_id;
5124 state.snapshot.git_repositories.update(
5125 &work_directory_id,
5126 |local_repository_entry| {
5127 local_repository_entry.status_scan_id = scan_id;
5128 },
5129 );
5130 }
5131 }
5132 }
5133 }
5134
5135 for (path, metadata) in relative_paths.iter().zip(metadata.into_iter()) {
5136 let abs_path: Arc<Path> = root_abs_path.as_path().join(path).into();
5137 match metadata {
5138 Ok(Some((metadata, canonical_path))) => {
5139 let ignore_stack = state
5140 .snapshot
5141 .ignore_stack_for_abs_path(&abs_path, metadata.is_dir);
5142 let is_external = !canonical_path.starts_with(&root_canonical_path);
5143 let mut fs_entry = Entry::new(
5144 path.clone(),
5145 &metadata,
5146 self.next_entry_id.as_ref(),
5147 state.snapshot.root_char_bag,
5148 if metadata.is_symlink {
5149 Some(canonical_path.as_path().to_path_buf().into())
5150 } else {
5151 None
5152 },
5153 );
5154
5155 let is_dir = fs_entry.is_dir();
5156 fs_entry.is_ignored = ignore_stack.is_abs_path_ignored(&abs_path, is_dir);
5157 fs_entry.is_external = is_external;
5158 fs_entry.is_private = self.is_path_private(path);
5159 fs_entry.is_always_included = self.settings.is_path_always_included(path);
5160
5161 if let (Some(scan_queue_tx), true) = (&scan_queue_tx, is_dir) {
5162 if state.should_scan_directory(&fs_entry)
5163 || (fs_entry.path.as_os_str().is_empty()
5164 && abs_path.file_name() == Some(*DOT_GIT))
5165 {
5166 state.enqueue_scan_dir(abs_path, &fs_entry, scan_queue_tx);
5167 } else {
5168 fs_entry.kind = EntryKind::UnloadedDir;
5169 }
5170 }
5171
5172 state.insert_entry(fs_entry.clone(), self.fs.as_ref(), self.watcher.as_ref());
5173 }
5174 Ok(None) => {
5175 self.remove_repo_path(path, &mut state.snapshot);
5176 }
5177 Err(err) => {
5178 log::error!("error reading file {abs_path:?} on event: {err:#}");
5179 }
5180 }
5181 }
5182
5183 util::extend_sorted(
5184 &mut state.changed_paths,
5185 relative_paths.iter().cloned(),
5186 usize::MAX,
5187 Ord::cmp,
5188 );
5189 }
5190
5191 fn remove_repo_path(&self, path: &Arc<Path>, snapshot: &mut LocalSnapshot) -> Option<()> {
5192 if !path
5193 .components()
5194 .any(|component| component.as_os_str() == *DOT_GIT)
5195 {
5196 if let Some(repository) = snapshot.repository(PathKey(path.clone())) {
5197 snapshot
5198 .git_repositories
5199 .remove(&repository.work_directory_id);
5200 snapshot
5201 .snapshot
5202 .repositories
5203 .remove(&repository.work_directory.path_key(), &());
5204 return Some(());
5205 }
5206 }
5207
5208 Some(())
5209 }
5210
5211 async fn update_ignore_statuses(&self, scan_job_tx: Sender<ScanJob>) {
5212 let mut ignores_to_update = Vec::new();
5213 let (ignore_queue_tx, ignore_queue_rx) = channel::unbounded();
5214 let prev_snapshot;
5215 {
5216 let snapshot = &mut self.state.lock().snapshot;
5217 let abs_path = snapshot.abs_path.clone();
5218 snapshot
5219 .ignores_by_parent_abs_path
5220 .retain(|parent_abs_path, (_, needs_update)| {
5221 if let Ok(parent_path) = parent_abs_path.strip_prefix(abs_path.as_path()) {
5222 if *needs_update {
5223 *needs_update = false;
5224 if snapshot.snapshot.entry_for_path(parent_path).is_some() {
5225 ignores_to_update.push(parent_abs_path.clone());
5226 }
5227 }
5228
5229 let ignore_path = parent_path.join(*GITIGNORE);
5230 if snapshot.snapshot.entry_for_path(ignore_path).is_none() {
5231 return false;
5232 }
5233 }
5234 true
5235 });
5236
5237 ignores_to_update.sort_unstable();
5238 let mut ignores_to_update = ignores_to_update.into_iter().peekable();
5239 while let Some(parent_abs_path) = ignores_to_update.next() {
5240 while ignores_to_update
5241 .peek()
5242 .map_or(false, |p| p.starts_with(&parent_abs_path))
5243 {
5244 ignores_to_update.next().unwrap();
5245 }
5246
5247 let ignore_stack = snapshot.ignore_stack_for_abs_path(&parent_abs_path, true);
5248 ignore_queue_tx
5249 .send_blocking(UpdateIgnoreStatusJob {
5250 abs_path: parent_abs_path,
5251 ignore_stack,
5252 ignore_queue: ignore_queue_tx.clone(),
5253 scan_queue: scan_job_tx.clone(),
5254 })
5255 .unwrap();
5256 }
5257
5258 prev_snapshot = snapshot.clone();
5259 }
5260 drop(ignore_queue_tx);
5261
5262 self.executor
5263 .scoped(|scope| {
5264 for _ in 0..self.executor.num_cpus() {
5265 scope.spawn(async {
5266 loop {
5267 select_biased! {
5268 // Process any path refresh requests before moving on to process
5269 // the queue of ignore statuses.
5270 request = self.next_scan_request().fuse() => {
5271 let Ok(request) = request else { break };
5272 if !self.process_scan_request(request, true).await {
5273 return;
5274 }
5275 }
5276
5277 // Recursively process directories whose ignores have changed.
5278 job = ignore_queue_rx.recv().fuse() => {
5279 let Ok(job) = job else { break };
5280 self.update_ignore_status(job, &prev_snapshot).await;
5281 }
5282 }
5283 }
5284 });
5285 }
5286 })
5287 .await;
5288 }
5289
5290 async fn update_ignore_status(&self, job: UpdateIgnoreStatusJob, snapshot: &LocalSnapshot) {
5291 log::trace!("update ignore status {:?}", job.abs_path);
5292
5293 let mut ignore_stack = job.ignore_stack;
5294 if let Some((ignore, _)) = snapshot.ignores_by_parent_abs_path.get(&job.abs_path) {
5295 ignore_stack = ignore_stack.append(job.abs_path.clone(), ignore.clone());
5296 }
5297
5298 let mut entries_by_id_edits = Vec::new();
5299 let mut entries_by_path_edits = Vec::new();
5300 let path = job
5301 .abs_path
5302 .strip_prefix(snapshot.abs_path.as_path())
5303 .unwrap();
5304
5305 for mut entry in snapshot.child_entries(path).cloned() {
5306 let was_ignored = entry.is_ignored;
5307 let abs_path: Arc<Path> = snapshot.abs_path().join(&entry.path).into();
5308 entry.is_ignored = ignore_stack.is_abs_path_ignored(&abs_path, entry.is_dir());
5309
5310 if entry.is_dir() {
5311 let child_ignore_stack = if entry.is_ignored {
5312 IgnoreStack::all()
5313 } else {
5314 ignore_stack.clone()
5315 };
5316
5317 // Scan any directories that were previously ignored and weren't previously scanned.
5318 if was_ignored && !entry.is_ignored && entry.kind.is_unloaded() {
5319 let state = self.state.lock();
5320 if state.should_scan_directory(&entry) {
5321 state.enqueue_scan_dir(abs_path.clone(), &entry, &job.scan_queue);
5322 }
5323 }
5324
5325 job.ignore_queue
5326 .send(UpdateIgnoreStatusJob {
5327 abs_path: abs_path.clone(),
5328 ignore_stack: child_ignore_stack,
5329 ignore_queue: job.ignore_queue.clone(),
5330 scan_queue: job.scan_queue.clone(),
5331 })
5332 .await
5333 .unwrap();
5334 }
5335
5336 if entry.is_ignored != was_ignored {
5337 let mut path_entry = snapshot.entries_by_id.get(&entry.id, &()).unwrap().clone();
5338 path_entry.scan_id = snapshot.scan_id;
5339 path_entry.is_ignored = entry.is_ignored;
5340 entries_by_id_edits.push(Edit::Insert(path_entry));
5341 entries_by_path_edits.push(Edit::Insert(entry));
5342 }
5343 }
5344
5345 let state = &mut self.state.lock();
5346 for edit in &entries_by_path_edits {
5347 if let Edit::Insert(entry) = edit {
5348 if let Err(ix) = state.changed_paths.binary_search(&entry.path) {
5349 state.changed_paths.insert(ix, entry.path.clone());
5350 }
5351 }
5352 }
5353
5354 state
5355 .snapshot
5356 .entries_by_path
5357 .edit(entries_by_path_edits, &());
5358 state.snapshot.entries_by_id.edit(entries_by_id_edits, &());
5359 }
5360
5361 fn update_git_repositories(&self, dot_git_paths: Vec<PathBuf>) -> Task<()> {
5362 log::debug!("reloading repositories: {dot_git_paths:?}");
5363
5364 let mut status_updates = Vec::new();
5365 {
5366 let mut state = self.state.lock();
5367 let scan_id = state.snapshot.scan_id;
5368 for dot_git_dir in dot_git_paths {
5369 let existing_repository_entry =
5370 state
5371 .snapshot
5372 .git_repositories
5373 .iter()
5374 .find_map(|(_, repo)| {
5375 if repo.dot_git_dir_abs_path.as_ref() == &dot_git_dir
5376 || repo.dot_git_worktree_abs_path.as_deref() == Some(&dot_git_dir)
5377 {
5378 Some(repo.clone())
5379 } else {
5380 None
5381 }
5382 });
5383
5384 let local_repository = match existing_repository_entry {
5385 None => {
5386 let Ok(relative) = dot_git_dir.strip_prefix(state.snapshot.abs_path())
5387 else {
5388 return Task::ready(());
5389 };
5390 match state.insert_git_repository(
5391 relative.into(),
5392 self.fs.as_ref(),
5393 self.watcher.as_ref(),
5394 ) {
5395 Some(output) => output,
5396 None => continue,
5397 }
5398 }
5399 Some(local_repository) => {
5400 if local_repository.git_dir_scan_id == scan_id {
5401 continue;
5402 }
5403 local_repository.repo_ptr.reload_index();
5404
5405 state.snapshot.git_repositories.update(
5406 &local_repository.work_directory_id,
5407 |entry| {
5408 entry.git_dir_scan_id = scan_id;
5409 entry.status_scan_id = scan_id;
5410 },
5411 );
5412
5413 local_repository
5414 }
5415 };
5416
5417 status_updates
5418 .push(self.schedule_git_statuses_update(&mut state, local_repository));
5419 }
5420
5421 // Remove any git repositories whose .git entry no longer exists.
5422 let snapshot = &mut state.snapshot;
5423 let mut ids_to_preserve = HashSet::default();
5424 for (&work_directory_id, entry) in snapshot.git_repositories.iter() {
5425 let exists_in_snapshot = snapshot
5426 .entry_for_id(work_directory_id)
5427 .map_or(false, |entry| {
5428 snapshot.entry_for_path(entry.path.join(*DOT_GIT)).is_some()
5429 });
5430
5431 if exists_in_snapshot
5432 || matches!(
5433 smol::block_on(self.fs.metadata(&entry.dot_git_dir_abs_path)),
5434 Ok(Some(_))
5435 )
5436 {
5437 ids_to_preserve.insert(work_directory_id);
5438 }
5439 }
5440
5441 snapshot
5442 .git_repositories
5443 .retain(|work_directory_id, _| ids_to_preserve.contains(work_directory_id));
5444 snapshot.repositories.retain(&(), |entry| {
5445 ids_to_preserve.contains(&entry.work_directory_id)
5446 });
5447 }
5448
5449 self.executor.spawn(async move {
5450 let _updates_finished: Vec<Result<(), oneshot::Canceled>> =
5451 join_all(status_updates).await;
5452 })
5453 }
5454
5455 /// Update the git statuses for a given batch of entries.
5456 fn schedule_git_statuses_update(
5457 &self,
5458 state: &mut BackgroundScannerState,
5459 mut local_repository: LocalRepositoryEntry,
5460 ) -> oneshot::Receiver<()> {
5461 let repository_name = local_repository.work_directory.display_name();
5462 let path_key = local_repository.work_directory.path_key();
5463
5464 let job_state = self.state.clone();
5465 let (tx, rx) = oneshot::channel();
5466
5467 state.repository_scans.insert(
5468 path_key.clone(),
5469 self.executor.spawn(async move {
5470 update_branches(&job_state, &mut local_repository).log_err();
5471 log::trace!("updating git statuses for repo {repository_name}",);
5472 let t0 = Instant::now();
5473
5474 let Some(statuses) = local_repository
5475 .repo()
5476 .status(&[git::WORK_DIRECTORY_REPO_PATH.clone()])
5477 .log_err()
5478 else {
5479 return;
5480 };
5481 log::trace!(
5482 "computed git statuses for repo {repository_name} in {:?}",
5483 t0.elapsed()
5484 );
5485
5486 let t0 = Instant::now();
5487 let mut changed_paths = Vec::new();
5488 let snapshot = job_state.lock().snapshot.snapshot.clone();
5489
5490 let Some(mut repository) = snapshot
5491 .repository(path_key)
5492 .context(
5493 "Tried to update git statuses for a repository that isn't in the snapshot",
5494 )
5495 .log_err()
5496 else {
5497 return;
5498 };
5499
5500 let merge_head_shas = local_repository.repo().merge_head_shas();
5501 if merge_head_shas != local_repository.current_merge_head_shas {
5502 mem::take(&mut repository.current_merge_conflicts);
5503 }
5504
5505 let mut new_entries_by_path = SumTree::new(&());
5506 for (repo_path, status) in statuses.entries.iter() {
5507 let project_path = repository.work_directory.unrelativize(repo_path);
5508
5509 new_entries_by_path.insert_or_replace(
5510 StatusEntry {
5511 repo_path: repo_path.clone(),
5512 status: *status,
5513 },
5514 &(),
5515 );
5516 if status.is_conflicted() {
5517 repository.current_merge_conflicts.insert(repo_path.clone());
5518 }
5519
5520 if let Some(path) = project_path {
5521 changed_paths.push(path);
5522 }
5523 }
5524
5525 repository.statuses_by_path = new_entries_by_path;
5526 let mut state = job_state.lock();
5527 state
5528 .snapshot
5529 .repositories
5530 .insert_or_replace(repository, &());
5531 state.snapshot.git_repositories.update(
5532 &local_repository.work_directory_id,
5533 |entry| {
5534 entry.current_merge_head_shas = merge_head_shas;
5535 entry.merge_message = std::fs::read_to_string(
5536 local_repository.dot_git_dir_abs_path.join("MERGE_MSG"),
5537 )
5538 .ok()
5539 .and_then(|merge_msg| Some(merge_msg.lines().next()?.to_owned()));
5540 entry.status_scan_id += 1;
5541 },
5542 );
5543
5544 util::extend_sorted(
5545 &mut state.changed_paths,
5546 changed_paths,
5547 usize::MAX,
5548 Ord::cmp,
5549 );
5550
5551 log::trace!(
5552 "applied git status updates for repo {repository_name} in {:?}",
5553 t0.elapsed(),
5554 );
5555 tx.send(()).ok();
5556 }),
5557 );
5558 rx
5559 }
5560
5561 async fn progress_timer(&self, running: bool) {
5562 if !running {
5563 return futures::future::pending().await;
5564 }
5565
5566 #[cfg(any(test, feature = "test-support"))]
5567 if self.fs.is_fake() {
5568 return self.executor.simulate_random_delay().await;
5569 }
5570
5571 smol::Timer::after(FS_WATCH_LATENCY).await;
5572 }
5573
5574 fn is_path_private(&self, path: &Path) -> bool {
5575 !self.share_private_files && self.settings.is_path_private(path)
5576 }
5577
5578 async fn next_scan_request(&self) -> Result<ScanRequest> {
5579 let mut request = self.scan_requests_rx.recv().await?;
5580 while let Ok(next_request) = self.scan_requests_rx.try_recv() {
5581 request.relative_paths.extend(next_request.relative_paths);
5582 request.done.extend(next_request.done);
5583 }
5584 Ok(request)
5585 }
5586}
5587
5588fn send_status_update_inner(
5589 phase: BackgroundScannerPhase,
5590 state: Arc<Mutex<BackgroundScannerState>>,
5591 status_updates_tx: UnboundedSender<ScanState>,
5592 scanning: bool,
5593 barrier: SmallVec<[barrier::Sender; 1]>,
5594) -> bool {
5595 let mut state = state.lock();
5596 if state.changed_paths.is_empty() && scanning {
5597 return true;
5598 }
5599
5600 let new_snapshot = state.snapshot.clone();
5601 let old_snapshot = mem::replace(&mut state.prev_snapshot, new_snapshot.snapshot.clone());
5602 let changes = build_diff(phase, &old_snapshot, &new_snapshot, &state.changed_paths);
5603 state.changed_paths.clear();
5604
5605 status_updates_tx
5606 .unbounded_send(ScanState::Updated {
5607 snapshot: new_snapshot,
5608 changes,
5609 scanning,
5610 barrier,
5611 })
5612 .is_ok()
5613}
5614
5615fn update_branches(
5616 state: &Mutex<BackgroundScannerState>,
5617 repository: &mut LocalRepositoryEntry,
5618) -> Result<()> {
5619 let branches = repository.repo().branches()?;
5620 let snapshot = state.lock().snapshot.snapshot.clone();
5621 let mut repository = snapshot
5622 .repository(repository.work_directory.path_key())
5623 .context("Missing repository")?;
5624 repository.current_branch = branches.into_iter().find(|branch| branch.is_head);
5625
5626 let mut state = state.lock();
5627 state
5628 .snapshot
5629 .repositories
5630 .insert_or_replace(repository, &());
5631
5632 Ok(())
5633}
5634
5635fn build_diff(
5636 phase: BackgroundScannerPhase,
5637 old_snapshot: &Snapshot,
5638 new_snapshot: &Snapshot,
5639 event_paths: &[Arc<Path>],
5640) -> UpdatedEntriesSet {
5641 use BackgroundScannerPhase::*;
5642 use PathChange::{Added, AddedOrUpdated, Loaded, Removed, Updated};
5643
5644 // Identify which paths have changed. Use the known set of changed
5645 // parent paths to optimize the search.
5646 let mut changes = Vec::new();
5647 let mut old_paths = old_snapshot.entries_by_path.cursor::<PathKey>(&());
5648 let mut new_paths = new_snapshot.entries_by_path.cursor::<PathKey>(&());
5649 let mut last_newly_loaded_dir_path = None;
5650 old_paths.next(&());
5651 new_paths.next(&());
5652 for path in event_paths {
5653 let path = PathKey(path.clone());
5654 if old_paths.item().map_or(false, |e| e.path < path.0) {
5655 old_paths.seek_forward(&path, Bias::Left, &());
5656 }
5657 if new_paths.item().map_or(false, |e| e.path < path.0) {
5658 new_paths.seek_forward(&path, Bias::Left, &());
5659 }
5660 loop {
5661 match (old_paths.item(), new_paths.item()) {
5662 (Some(old_entry), Some(new_entry)) => {
5663 if old_entry.path > path.0
5664 && new_entry.path > path.0
5665 && !old_entry.path.starts_with(&path.0)
5666 && !new_entry.path.starts_with(&path.0)
5667 {
5668 break;
5669 }
5670
5671 match Ord::cmp(&old_entry.path, &new_entry.path) {
5672 Ordering::Less => {
5673 changes.push((old_entry.path.clone(), old_entry.id, Removed));
5674 old_paths.next(&());
5675 }
5676 Ordering::Equal => {
5677 if phase == EventsReceivedDuringInitialScan {
5678 if old_entry.id != new_entry.id {
5679 changes.push((old_entry.path.clone(), old_entry.id, Removed));
5680 }
5681 // If the worktree was not fully initialized when this event was generated,
5682 // we can't know whether this entry was added during the scan or whether
5683 // it was merely updated.
5684 changes.push((
5685 new_entry.path.clone(),
5686 new_entry.id,
5687 AddedOrUpdated,
5688 ));
5689 } else if old_entry.id != new_entry.id {
5690 changes.push((old_entry.path.clone(), old_entry.id, Removed));
5691 changes.push((new_entry.path.clone(), new_entry.id, Added));
5692 } else if old_entry != new_entry {
5693 if old_entry.kind.is_unloaded() {
5694 last_newly_loaded_dir_path = Some(&new_entry.path);
5695 changes.push((new_entry.path.clone(), new_entry.id, Loaded));
5696 } else {
5697 changes.push((new_entry.path.clone(), new_entry.id, Updated));
5698 }
5699 }
5700 old_paths.next(&());
5701 new_paths.next(&());
5702 }
5703 Ordering::Greater => {
5704 let is_newly_loaded = phase == InitialScan
5705 || last_newly_loaded_dir_path
5706 .as_ref()
5707 .map_or(false, |dir| new_entry.path.starts_with(dir));
5708 changes.push((
5709 new_entry.path.clone(),
5710 new_entry.id,
5711 if is_newly_loaded { Loaded } else { Added },
5712 ));
5713 new_paths.next(&());
5714 }
5715 }
5716 }
5717 (Some(old_entry), None) => {
5718 changes.push((old_entry.path.clone(), old_entry.id, Removed));
5719 old_paths.next(&());
5720 }
5721 (None, Some(new_entry)) => {
5722 let is_newly_loaded = phase == InitialScan
5723 || last_newly_loaded_dir_path
5724 .as_ref()
5725 .map_or(false, |dir| new_entry.path.starts_with(dir));
5726 changes.push((
5727 new_entry.path.clone(),
5728 new_entry.id,
5729 if is_newly_loaded { Loaded } else { Added },
5730 ));
5731 new_paths.next(&());
5732 }
5733 (None, None) => break,
5734 }
5735 }
5736 }
5737
5738 changes.into()
5739}
5740
5741fn swap_to_front(child_paths: &mut Vec<PathBuf>, file: &OsStr) {
5742 let position = child_paths
5743 .iter()
5744 .position(|path| path.file_name().unwrap() == file);
5745 if let Some(position) = position {
5746 let temp = child_paths.remove(position);
5747 child_paths.insert(0, temp);
5748 }
5749}
5750
5751fn char_bag_for_path(root_char_bag: CharBag, path: &Path) -> CharBag {
5752 let mut result = root_char_bag;
5753 result.extend(
5754 path.to_string_lossy()
5755 .chars()
5756 .map(|c| c.to_ascii_lowercase()),
5757 );
5758 result
5759}
5760
5761#[derive(Debug)]
5762struct RepoPaths {
5763 repo: Arc<dyn GitRepository>,
5764 entry: RepositoryEntry,
5765 // sorted
5766 repo_paths: Vec<RepoPath>,
5767}
5768
5769impl RepoPaths {
5770 fn add_path(&mut self, repo_path: RepoPath) {
5771 match self.repo_paths.binary_search(&repo_path) {
5772 Ok(_) => {}
5773 Err(ix) => self.repo_paths.insert(ix, repo_path),
5774 }
5775 }
5776
5777 fn remove_repo_path(&mut self, repo_path: &RepoPath) {
5778 match self.repo_paths.binary_search(&repo_path) {
5779 Ok(ix) => {
5780 self.repo_paths.remove(ix);
5781 }
5782 Err(_) => {}
5783 }
5784 }
5785}
5786
5787#[derive(Debug)]
5788struct ScanJob {
5789 abs_path: Arc<Path>,
5790 path: Arc<Path>,
5791 ignore_stack: Arc<IgnoreStack>,
5792 scan_queue: Sender<ScanJob>,
5793 ancestor_inodes: TreeSet<u64>,
5794 is_external: bool,
5795}
5796
5797struct UpdateIgnoreStatusJob {
5798 abs_path: Arc<Path>,
5799 ignore_stack: Arc<IgnoreStack>,
5800 ignore_queue: Sender<UpdateIgnoreStatusJob>,
5801 scan_queue: Sender<ScanJob>,
5802}
5803
5804pub trait WorktreeModelHandle {
5805 #[cfg(any(test, feature = "test-support"))]
5806 fn flush_fs_events<'a>(
5807 &self,
5808 cx: &'a mut gpui::TestAppContext,
5809 ) -> futures::future::LocalBoxFuture<'a, ()>;
5810
5811 #[cfg(any(test, feature = "test-support"))]
5812 fn flush_fs_events_in_root_git_repository<'a>(
5813 &self,
5814 cx: &'a mut gpui::TestAppContext,
5815 ) -> futures::future::LocalBoxFuture<'a, ()>;
5816}
5817
5818impl WorktreeModelHandle for Entity<Worktree> {
5819 // When the worktree's FS event stream sometimes delivers "redundant" events for FS changes that
5820 // occurred before the worktree was constructed. These events can cause the worktree to perform
5821 // extra directory scans, and emit extra scan-state notifications.
5822 //
5823 // This function mutates the worktree's directory and waits for those mutations to be picked up,
5824 // to ensure that all redundant FS events have already been processed.
5825 #[cfg(any(test, feature = "test-support"))]
5826 fn flush_fs_events<'a>(
5827 &self,
5828 cx: &'a mut gpui::TestAppContext,
5829 ) -> futures::future::LocalBoxFuture<'a, ()> {
5830 let file_name = "fs-event-sentinel";
5831
5832 let tree = self.clone();
5833 let (fs, root_path) = self.update(cx, |tree, _| {
5834 let tree = tree.as_local().unwrap();
5835 (tree.fs.clone(), tree.abs_path().clone())
5836 });
5837
5838 async move {
5839 fs.create_file(&root_path.join(file_name), Default::default())
5840 .await
5841 .unwrap();
5842
5843 cx.condition(&tree, |tree, _| tree.entry_for_path(file_name).is_some())
5844 .await;
5845
5846 fs.remove_file(&root_path.join(file_name), Default::default())
5847 .await
5848 .unwrap();
5849 cx.condition(&tree, |tree, _| tree.entry_for_path(file_name).is_none())
5850 .await;
5851
5852 cx.update(|cx| tree.read(cx).as_local().unwrap().scan_complete())
5853 .await;
5854 }
5855 .boxed_local()
5856 }
5857
5858 // This function is similar to flush_fs_events, except that it waits for events to be flushed in
5859 // the .git folder of the root repository.
5860 // The reason for its existence is that a repository's .git folder might live *outside* of the
5861 // worktree and thus its FS events might go through a different path.
5862 // In order to flush those, we need to create artificial events in the .git folder and wait
5863 // for the repository to be reloaded.
5864 #[cfg(any(test, feature = "test-support"))]
5865 fn flush_fs_events_in_root_git_repository<'a>(
5866 &self,
5867 cx: &'a mut gpui::TestAppContext,
5868 ) -> futures::future::LocalBoxFuture<'a, ()> {
5869 let file_name = "fs-event-sentinel";
5870
5871 let tree = self.clone();
5872 let (fs, root_path, mut git_dir_scan_id) = self.update(cx, |tree, _| {
5873 let tree = tree.as_local().unwrap();
5874 let root_entry = tree.root_git_entry().unwrap();
5875 let local_repo_entry = tree.get_local_repo(&root_entry).unwrap();
5876 (
5877 tree.fs.clone(),
5878 local_repo_entry.dot_git_dir_abs_path.clone(),
5879 local_repo_entry.git_dir_scan_id,
5880 )
5881 });
5882
5883 let scan_id_increased = |tree: &mut Worktree, git_dir_scan_id: &mut usize| {
5884 let root_entry = tree.root_git_entry().unwrap();
5885 let local_repo_entry = tree
5886 .as_local()
5887 .unwrap()
5888 .get_local_repo(&root_entry)
5889 .unwrap();
5890
5891 if local_repo_entry.git_dir_scan_id > *git_dir_scan_id {
5892 *git_dir_scan_id = local_repo_entry.git_dir_scan_id;
5893 true
5894 } else {
5895 false
5896 }
5897 };
5898
5899 async move {
5900 fs.create_file(&root_path.join(file_name), Default::default())
5901 .await
5902 .unwrap();
5903
5904 cx.condition(&tree, |tree, _| {
5905 scan_id_increased(tree, &mut git_dir_scan_id)
5906 })
5907 .await;
5908
5909 fs.remove_file(&root_path.join(file_name), Default::default())
5910 .await
5911 .unwrap();
5912
5913 cx.condition(&tree, |tree, _| {
5914 scan_id_increased(tree, &mut git_dir_scan_id)
5915 })
5916 .await;
5917
5918 cx.update(|cx| tree.read(cx).as_local().unwrap().scan_complete())
5919 .await;
5920 }
5921 .boxed_local()
5922 }
5923}
5924
5925#[derive(Clone, Debug)]
5926struct TraversalProgress<'a> {
5927 max_path: &'a Path,
5928 count: usize,
5929 non_ignored_count: usize,
5930 file_count: usize,
5931 non_ignored_file_count: usize,
5932}
5933
5934impl TraversalProgress<'_> {
5935 fn count(&self, include_files: bool, include_dirs: bool, include_ignored: bool) -> usize {
5936 match (include_files, include_dirs, include_ignored) {
5937 (true, true, true) => self.count,
5938 (true, true, false) => self.non_ignored_count,
5939 (true, false, true) => self.file_count,
5940 (true, false, false) => self.non_ignored_file_count,
5941 (false, true, true) => self.count - self.file_count,
5942 (false, true, false) => self.non_ignored_count - self.non_ignored_file_count,
5943 (false, false, _) => 0,
5944 }
5945 }
5946}
5947
5948impl<'a> sum_tree::Dimension<'a, EntrySummary> for TraversalProgress<'a> {
5949 fn zero(_cx: &()) -> Self {
5950 Default::default()
5951 }
5952
5953 fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
5954 self.max_path = summary.max_path.as_ref();
5955 self.count += summary.count;
5956 self.non_ignored_count += summary.non_ignored_count;
5957 self.file_count += summary.file_count;
5958 self.non_ignored_file_count += summary.non_ignored_file_count;
5959 }
5960}
5961
5962impl Default for TraversalProgress<'_> {
5963 fn default() -> Self {
5964 Self {
5965 max_path: Path::new(""),
5966 count: 0,
5967 non_ignored_count: 0,
5968 file_count: 0,
5969 non_ignored_file_count: 0,
5970 }
5971 }
5972}
5973
5974#[derive(Debug, Clone, Copy)]
5975pub struct GitEntryRef<'a> {
5976 pub entry: &'a Entry,
5977 pub git_summary: GitSummary,
5978}
5979
5980impl GitEntryRef<'_> {
5981 pub fn to_owned(&self) -> GitEntry {
5982 GitEntry {
5983 entry: self.entry.clone(),
5984 git_summary: self.git_summary,
5985 }
5986 }
5987}
5988
5989impl Deref for GitEntryRef<'_> {
5990 type Target = Entry;
5991
5992 fn deref(&self) -> &Self::Target {
5993 &self.entry
5994 }
5995}
5996
5997impl AsRef<Entry> for GitEntryRef<'_> {
5998 fn as_ref(&self) -> &Entry {
5999 self.entry
6000 }
6001}
6002
6003#[derive(Debug, Clone, PartialEq, Eq)]
6004pub struct GitEntry {
6005 pub entry: Entry,
6006 pub git_summary: GitSummary,
6007}
6008
6009impl GitEntry {
6010 pub fn to_ref(&self) -> GitEntryRef {
6011 GitEntryRef {
6012 entry: &self.entry,
6013 git_summary: self.git_summary,
6014 }
6015 }
6016}
6017
6018impl Deref for GitEntry {
6019 type Target = Entry;
6020
6021 fn deref(&self) -> &Self::Target {
6022 &self.entry
6023 }
6024}
6025
6026impl AsRef<Entry> for GitEntry {
6027 fn as_ref(&self) -> &Entry {
6028 &self.entry
6029 }
6030}
6031
6032/// Walks the worktree entries and their associated git statuses.
6033pub struct GitTraversal<'a> {
6034 traversal: Traversal<'a>,
6035 current_entry_summary: Option<GitSummary>,
6036 repo_location: Option<(
6037 &'a RepositoryEntry,
6038 Cursor<'a, StatusEntry, PathProgress<'a>>,
6039 )>,
6040}
6041
6042impl<'a> GitTraversal<'a> {
6043 fn synchronize_statuses(&mut self, reset: bool) {
6044 self.current_entry_summary = None;
6045
6046 let Some(entry) = self.traversal.cursor.item() else {
6047 return;
6048 };
6049
6050 let Some(repo) = self.traversal.snapshot.repository_for_path(&entry.path) else {
6051 self.repo_location = None;
6052 return;
6053 };
6054
6055 // Update our state if we changed repositories.
6056 if reset
6057 || self
6058 .repo_location
6059 .as_ref()
6060 .map(|(prev_repo, _)| &prev_repo.work_directory)
6061 != Some(&repo.work_directory)
6062 {
6063 self.repo_location = Some((repo, repo.statuses_by_path.cursor::<PathProgress>(&())));
6064 }
6065
6066 let Some((repo, statuses)) = &mut self.repo_location else {
6067 return;
6068 };
6069
6070 let repo_path = repo.relativize(&entry.path).unwrap();
6071
6072 if entry.is_dir() {
6073 let mut statuses = statuses.clone();
6074 statuses.seek_forward(&PathTarget::Path(repo_path.as_ref()), Bias::Left, &());
6075 let summary =
6076 statuses.summary(&PathTarget::Successor(repo_path.as_ref()), Bias::Left, &());
6077
6078 self.current_entry_summary = Some(summary);
6079 } else if entry.is_file() {
6080 // For a file entry, park the cursor on the corresponding status
6081 if statuses.seek_forward(&PathTarget::Path(repo_path.as_ref()), Bias::Left, &()) {
6082 // TODO: Investigate statuses.item() being None here.
6083 self.current_entry_summary = statuses.item().map(|item| item.status.into());
6084 } else {
6085 self.current_entry_summary = Some(GitSummary::UNCHANGED);
6086 }
6087 }
6088 }
6089
6090 pub fn advance(&mut self) -> bool {
6091 self.advance_by(1)
6092 }
6093
6094 pub fn advance_by(&mut self, count: usize) -> bool {
6095 let found = self.traversal.advance_by(count);
6096 self.synchronize_statuses(false);
6097 found
6098 }
6099
6100 pub fn advance_to_sibling(&mut self) -> bool {
6101 let found = self.traversal.advance_to_sibling();
6102 self.synchronize_statuses(false);
6103 found
6104 }
6105
6106 pub fn back_to_parent(&mut self) -> bool {
6107 let found = self.traversal.back_to_parent();
6108 self.synchronize_statuses(true);
6109 found
6110 }
6111
6112 pub fn start_offset(&self) -> usize {
6113 self.traversal.start_offset()
6114 }
6115
6116 pub fn end_offset(&self) -> usize {
6117 self.traversal.end_offset()
6118 }
6119
6120 pub fn entry(&self) -> Option<GitEntryRef<'a>> {
6121 let entry = self.traversal.cursor.item()?;
6122 let git_summary = self.current_entry_summary.unwrap_or(GitSummary::UNCHANGED);
6123 Some(GitEntryRef { entry, git_summary })
6124 }
6125}
6126
6127impl<'a> Iterator for GitTraversal<'a> {
6128 type Item = GitEntryRef<'a>;
6129 fn next(&mut self) -> Option<Self::Item> {
6130 if let Some(item) = self.entry() {
6131 self.advance();
6132 Some(item)
6133 } else {
6134 None
6135 }
6136 }
6137}
6138
6139#[derive(Debug)]
6140pub struct Traversal<'a> {
6141 snapshot: &'a Snapshot,
6142 cursor: sum_tree::Cursor<'a, Entry, TraversalProgress<'a>>,
6143 include_ignored: bool,
6144 include_files: bool,
6145 include_dirs: bool,
6146}
6147
6148impl<'a> Traversal<'a> {
6149 fn new(
6150 snapshot: &'a Snapshot,
6151 include_files: bool,
6152 include_dirs: bool,
6153 include_ignored: bool,
6154 start_path: &Path,
6155 ) -> Self {
6156 let mut cursor = snapshot.entries_by_path.cursor(&());
6157 cursor.seek(&TraversalTarget::path(start_path), Bias::Left, &());
6158 let mut traversal = Self {
6159 snapshot,
6160 cursor,
6161 include_files,
6162 include_dirs,
6163 include_ignored,
6164 };
6165 if traversal.end_offset() == traversal.start_offset() {
6166 traversal.next();
6167 }
6168 traversal
6169 }
6170
6171 pub fn with_git_statuses(self) -> GitTraversal<'a> {
6172 let mut this = GitTraversal {
6173 traversal: self,
6174 current_entry_summary: None,
6175 repo_location: None,
6176 };
6177 this.synchronize_statuses(true);
6178 this
6179 }
6180
6181 pub fn advance(&mut self) -> bool {
6182 self.advance_by(1)
6183 }
6184
6185 pub fn advance_by(&mut self, count: usize) -> bool {
6186 self.cursor.seek_forward(
6187 &TraversalTarget::Count {
6188 count: self.end_offset() + count,
6189 include_dirs: self.include_dirs,
6190 include_files: self.include_files,
6191 include_ignored: self.include_ignored,
6192 },
6193 Bias::Left,
6194 &(),
6195 )
6196 }
6197
6198 pub fn advance_to_sibling(&mut self) -> bool {
6199 while let Some(entry) = self.cursor.item() {
6200 self.cursor
6201 .seek_forward(&TraversalTarget::successor(&entry.path), Bias::Left, &());
6202 if let Some(entry) = self.cursor.item() {
6203 if (self.include_files || !entry.is_file())
6204 && (self.include_dirs || !entry.is_dir())
6205 && (self.include_ignored || !entry.is_ignored || entry.is_always_included)
6206 {
6207 return true;
6208 }
6209 }
6210 }
6211 false
6212 }
6213
6214 pub fn back_to_parent(&mut self) -> bool {
6215 let Some(parent_path) = self.cursor.item().and_then(|entry| entry.path.parent()) else {
6216 return false;
6217 };
6218 self.cursor
6219 .seek(&TraversalTarget::path(parent_path), Bias::Left, &())
6220 }
6221
6222 pub fn entry(&self) -> Option<&'a Entry> {
6223 self.cursor.item()
6224 }
6225
6226 pub fn start_offset(&self) -> usize {
6227 self.cursor
6228 .start()
6229 .count(self.include_files, self.include_dirs, self.include_ignored)
6230 }
6231
6232 pub fn end_offset(&self) -> usize {
6233 self.cursor
6234 .end(&())
6235 .count(self.include_files, self.include_dirs, self.include_ignored)
6236 }
6237}
6238
6239impl<'a> Iterator for Traversal<'a> {
6240 type Item = &'a Entry;
6241
6242 fn next(&mut self) -> Option<Self::Item> {
6243 if let Some(item) = self.entry() {
6244 self.advance();
6245 Some(item)
6246 } else {
6247 None
6248 }
6249 }
6250}
6251
6252#[derive(Debug, Clone, Copy)]
6253enum PathTarget<'a> {
6254 Path(&'a Path),
6255 Successor(&'a Path),
6256}
6257
6258impl PathTarget<'_> {
6259 fn cmp_path(&self, other: &Path) -> Ordering {
6260 match self {
6261 PathTarget::Path(path) => path.cmp(&other),
6262 PathTarget::Successor(path) => {
6263 if other.starts_with(path) {
6264 Ordering::Greater
6265 } else {
6266 Ordering::Equal
6267 }
6268 }
6269 }
6270 }
6271}
6272
6273impl<'a, S: Summary> SeekTarget<'a, PathSummary<S>, PathProgress<'a>> for PathTarget<'_> {
6274 fn cmp(&self, cursor_location: &PathProgress<'a>, _: &S::Context) -> Ordering {
6275 self.cmp_path(&cursor_location.max_path)
6276 }
6277}
6278
6279impl<'a, S: Summary> SeekTarget<'a, PathSummary<S>, TraversalProgress<'a>> for PathTarget<'_> {
6280 fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: &S::Context) -> Ordering {
6281 self.cmp_path(&cursor_location.max_path)
6282 }
6283}
6284
6285impl<'a> SeekTarget<'a, PathSummary<GitSummary>, (TraversalProgress<'a>, GitSummary)>
6286 for PathTarget<'_>
6287{
6288 fn cmp(&self, cursor_location: &(TraversalProgress<'a>, GitSummary), _: &()) -> Ordering {
6289 self.cmp_path(&cursor_location.0.max_path)
6290 }
6291}
6292
6293#[derive(Debug)]
6294enum TraversalTarget<'a> {
6295 Path(PathTarget<'a>),
6296 Count {
6297 count: usize,
6298 include_files: bool,
6299 include_ignored: bool,
6300 include_dirs: bool,
6301 },
6302}
6303
6304impl<'a> TraversalTarget<'a> {
6305 fn path(path: &'a Path) -> Self {
6306 Self::Path(PathTarget::Path(path))
6307 }
6308
6309 fn successor(path: &'a Path) -> Self {
6310 Self::Path(PathTarget::Successor(path))
6311 }
6312
6313 fn cmp_progress(&self, progress: &TraversalProgress) -> Ordering {
6314 match self {
6315 TraversalTarget::Path(path) => path.cmp_path(&progress.max_path),
6316 TraversalTarget::Count {
6317 count,
6318 include_files,
6319 include_dirs,
6320 include_ignored,
6321 } => Ord::cmp(
6322 count,
6323 &progress.count(*include_files, *include_dirs, *include_ignored),
6324 ),
6325 }
6326 }
6327}
6328
6329impl<'a> SeekTarget<'a, EntrySummary, TraversalProgress<'a>> for TraversalTarget<'_> {
6330 fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: &()) -> Ordering {
6331 self.cmp_progress(cursor_location)
6332 }
6333}
6334
6335impl<'a> SeekTarget<'a, PathSummary<Unit>, TraversalProgress<'a>> for TraversalTarget<'_> {
6336 fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: &()) -> Ordering {
6337 self.cmp_progress(cursor_location)
6338 }
6339}
6340
6341pub struct ChildEntriesOptions {
6342 pub include_files: bool,
6343 pub include_dirs: bool,
6344 pub include_ignored: bool,
6345}
6346
6347pub struct ChildEntriesIter<'a> {
6348 parent_path: &'a Path,
6349 traversal: Traversal<'a>,
6350}
6351
6352impl<'a> ChildEntriesIter<'a> {
6353 pub fn with_git_statuses(self) -> ChildEntriesGitIter<'a> {
6354 ChildEntriesGitIter {
6355 parent_path: self.parent_path,
6356 traversal: self.traversal.with_git_statuses(),
6357 }
6358 }
6359}
6360
6361pub struct ChildEntriesGitIter<'a> {
6362 parent_path: &'a Path,
6363 traversal: GitTraversal<'a>,
6364}
6365
6366impl<'a> Iterator for ChildEntriesIter<'a> {
6367 type Item = &'a Entry;
6368
6369 fn next(&mut self) -> Option<Self::Item> {
6370 if let Some(item) = self.traversal.entry() {
6371 if item.path.starts_with(self.parent_path) {
6372 self.traversal.advance_to_sibling();
6373 return Some(item);
6374 }
6375 }
6376 None
6377 }
6378}
6379
6380impl<'a> Iterator for ChildEntriesGitIter<'a> {
6381 type Item = GitEntryRef<'a>;
6382
6383 fn next(&mut self) -> Option<Self::Item> {
6384 if let Some(item) = self.traversal.entry() {
6385 if item.path.starts_with(self.parent_path) {
6386 self.traversal.advance_to_sibling();
6387 return Some(item);
6388 }
6389 }
6390 None
6391 }
6392}
6393
6394impl<'a> From<&'a Entry> for proto::Entry {
6395 fn from(entry: &'a Entry) -> Self {
6396 Self {
6397 id: entry.id.to_proto(),
6398 is_dir: entry.is_dir(),
6399 path: entry.path.as_ref().to_proto(),
6400 inode: entry.inode,
6401 mtime: entry.mtime.map(|time| time.into()),
6402 is_ignored: entry.is_ignored,
6403 is_external: entry.is_external,
6404 is_fifo: entry.is_fifo,
6405 size: Some(entry.size),
6406 canonical_path: entry
6407 .canonical_path
6408 .as_ref()
6409 .map(|path| path.as_ref().to_proto()),
6410 }
6411 }
6412}
6413
6414impl<'a> TryFrom<(&'a CharBag, &PathMatcher, proto::Entry)> for Entry {
6415 type Error = anyhow::Error;
6416
6417 fn try_from(
6418 (root_char_bag, always_included, entry): (&'a CharBag, &PathMatcher, proto::Entry),
6419 ) -> Result<Self> {
6420 let kind = if entry.is_dir {
6421 EntryKind::Dir
6422 } else {
6423 EntryKind::File
6424 };
6425
6426 let path = Arc::<Path>::from_proto(entry.path);
6427 let char_bag = char_bag_for_path(*root_char_bag, &path);
6428 let is_always_included = always_included.is_match(path.as_ref());
6429 Ok(Entry {
6430 id: ProjectEntryId::from_proto(entry.id),
6431 kind,
6432 path,
6433 inode: entry.inode,
6434 mtime: entry.mtime.map(|time| time.into()),
6435 size: entry.size.unwrap_or(0),
6436 canonical_path: entry
6437 .canonical_path
6438 .map(|path_string| Box::from(PathBuf::from_proto(path_string))),
6439 is_ignored: entry.is_ignored,
6440 is_always_included,
6441 is_external: entry.is_external,
6442 is_private: false,
6443 char_bag,
6444 is_fifo: entry.is_fifo,
6445 })
6446 }
6447}
6448
6449fn status_from_proto(
6450 simple_status: i32,
6451 status: Option<proto::GitFileStatus>,
6452) -> anyhow::Result<FileStatus> {
6453 use proto::git_file_status::Variant;
6454
6455 let Some(variant) = status.and_then(|status| status.variant) else {
6456 let code = proto::GitStatus::from_i32(simple_status)
6457 .ok_or_else(|| anyhow!("Invalid git status code: {simple_status}"))?;
6458 let result = match code {
6459 proto::GitStatus::Added => TrackedStatus {
6460 worktree_status: StatusCode::Added,
6461 index_status: StatusCode::Unmodified,
6462 }
6463 .into(),
6464 proto::GitStatus::Modified => TrackedStatus {
6465 worktree_status: StatusCode::Modified,
6466 index_status: StatusCode::Unmodified,
6467 }
6468 .into(),
6469 proto::GitStatus::Conflict => UnmergedStatus {
6470 first_head: UnmergedStatusCode::Updated,
6471 second_head: UnmergedStatusCode::Updated,
6472 }
6473 .into(),
6474 proto::GitStatus::Deleted => TrackedStatus {
6475 worktree_status: StatusCode::Deleted,
6476 index_status: StatusCode::Unmodified,
6477 }
6478 .into(),
6479 _ => return Err(anyhow!("Invalid code for simple status: {simple_status}")),
6480 };
6481 return Ok(result);
6482 };
6483
6484 let result = match variant {
6485 Variant::Untracked(_) => FileStatus::Untracked,
6486 Variant::Ignored(_) => FileStatus::Ignored,
6487 Variant::Unmerged(unmerged) => {
6488 let [first_head, second_head] =
6489 [unmerged.first_head, unmerged.second_head].map(|head| {
6490 let code = proto::GitStatus::from_i32(head)
6491 .ok_or_else(|| anyhow!("Invalid git status code: {head}"))?;
6492 let result = match code {
6493 proto::GitStatus::Added => UnmergedStatusCode::Added,
6494 proto::GitStatus::Updated => UnmergedStatusCode::Updated,
6495 proto::GitStatus::Deleted => UnmergedStatusCode::Deleted,
6496 _ => return Err(anyhow!("Invalid code for unmerged status: {code:?}")),
6497 };
6498 Ok(result)
6499 });
6500 let [first_head, second_head] = [first_head?, second_head?];
6501 UnmergedStatus {
6502 first_head,
6503 second_head,
6504 }
6505 .into()
6506 }
6507 Variant::Tracked(tracked) => {
6508 let [index_status, worktree_status] = [tracked.index_status, tracked.worktree_status]
6509 .map(|status| {
6510 let code = proto::GitStatus::from_i32(status)
6511 .ok_or_else(|| anyhow!("Invalid git status code: {status}"))?;
6512 let result = match code {
6513 proto::GitStatus::Modified => StatusCode::Modified,
6514 proto::GitStatus::TypeChanged => StatusCode::TypeChanged,
6515 proto::GitStatus::Added => StatusCode::Added,
6516 proto::GitStatus::Deleted => StatusCode::Deleted,
6517 proto::GitStatus::Renamed => StatusCode::Renamed,
6518 proto::GitStatus::Copied => StatusCode::Copied,
6519 proto::GitStatus::Unmodified => StatusCode::Unmodified,
6520 _ => return Err(anyhow!("Invalid code for tracked status: {code:?}")),
6521 };
6522 Ok(result)
6523 });
6524 let [index_status, worktree_status] = [index_status?, worktree_status?];
6525 TrackedStatus {
6526 index_status,
6527 worktree_status,
6528 }
6529 .into()
6530 }
6531 };
6532 Ok(result)
6533}
6534
6535fn status_to_proto(status: FileStatus) -> proto::GitFileStatus {
6536 use proto::git_file_status::{Tracked, Unmerged, Variant};
6537
6538 let variant = match status {
6539 FileStatus::Untracked => Variant::Untracked(Default::default()),
6540 FileStatus::Ignored => Variant::Ignored(Default::default()),
6541 FileStatus::Unmerged(UnmergedStatus {
6542 first_head,
6543 second_head,
6544 }) => Variant::Unmerged(Unmerged {
6545 first_head: unmerged_status_to_proto(first_head),
6546 second_head: unmerged_status_to_proto(second_head),
6547 }),
6548 FileStatus::Tracked(TrackedStatus {
6549 index_status,
6550 worktree_status,
6551 }) => Variant::Tracked(Tracked {
6552 index_status: tracked_status_to_proto(index_status),
6553 worktree_status: tracked_status_to_proto(worktree_status),
6554 }),
6555 };
6556 proto::GitFileStatus {
6557 variant: Some(variant),
6558 }
6559}
6560
6561fn unmerged_status_to_proto(code: UnmergedStatusCode) -> i32 {
6562 match code {
6563 UnmergedStatusCode::Added => proto::GitStatus::Added as _,
6564 UnmergedStatusCode::Deleted => proto::GitStatus::Deleted as _,
6565 UnmergedStatusCode::Updated => proto::GitStatus::Updated as _,
6566 }
6567}
6568
6569fn tracked_status_to_proto(code: StatusCode) -> i32 {
6570 match code {
6571 StatusCode::Added => proto::GitStatus::Added as _,
6572 StatusCode::Deleted => proto::GitStatus::Deleted as _,
6573 StatusCode::Modified => proto::GitStatus::Modified as _,
6574 StatusCode::Renamed => proto::GitStatus::Renamed as _,
6575 StatusCode::TypeChanged => proto::GitStatus::TypeChanged as _,
6576 StatusCode::Copied => proto::GitStatus::Copied as _,
6577 StatusCode::Unmodified => proto::GitStatus::Unmodified as _,
6578 }
6579}
6580
6581#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
6582pub struct ProjectEntryId(usize);
6583
6584impl ProjectEntryId {
6585 pub const MAX: Self = Self(usize::MAX);
6586 pub const MIN: Self = Self(usize::MIN);
6587
6588 pub fn new(counter: &AtomicUsize) -> Self {
6589 Self(counter.fetch_add(1, SeqCst))
6590 }
6591
6592 pub fn from_proto(id: u64) -> Self {
6593 Self(id as usize)
6594 }
6595
6596 pub fn to_proto(&self) -> u64 {
6597 self.0 as u64
6598 }
6599
6600 pub fn to_usize(&self) -> usize {
6601 self.0
6602 }
6603}
6604
6605#[cfg(any(test, feature = "test-support"))]
6606impl CreatedEntry {
6607 pub fn to_included(self) -> Option<Entry> {
6608 match self {
6609 CreatedEntry::Included(entry) => Some(entry),
6610 CreatedEntry::Excluded { .. } => None,
6611 }
6612 }
6613}