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