1mod ignore;
2mod worktree_settings;
3#[cfg(test)]
4mod worktree_tests;
5
6use ::ignore::gitignore::{Gitignore, GitignoreBuilder};
7use anyhow::{anyhow, Context as _, Result};
8use clock::ReplicaId;
9use collections::{HashMap, HashSet, VecDeque};
10use fs::{copy_recursive, Fs, MTime, PathEvent, RemoveOptions, Watcher};
11use futures::{
12 channel::{
13 mpsc::{self, UnboundedSender},
14 oneshot,
15 },
16 future::join_all,
17 select_biased,
18 task::Poll,
19 FutureExt as _, Stream, StreamExt,
20};
21use fuzzy::CharBag;
22use git::{
23 repository::{Branch, GitRepository, RepoPath, UpstreamTrackingStatus},
24 status::{
25 FileStatus, GitSummary, StatusCode, TrackedStatus, UnmergedStatus, UnmergedStatusCode,
26 },
27 GitHostingProviderRegistry, COMMIT_MESSAGE, DOT_GIT, FSMONITOR_DAEMON, GITIGNORE, INDEX_LOCK,
28 LFS_DIR,
29};
30use gpui::{
31 App, AppContext as _, AsyncApp, BackgroundExecutor, Context, Entity, EventEmitter, Task,
32};
33use ignore::IgnoreStack;
34use language::DiskState;
35
36use parking_lot::Mutex;
37use paths::local_settings_folder_relative_path;
38use postage::{
39 barrier,
40 prelude::{Sink as _, Stream as _},
41 watch,
42};
43use rpc::{
44 proto::{self, split_worktree_update, FromProto, ToProto},
45 AnyProtoClient,
46};
47pub use settings::WorktreeId;
48use settings::{Settings, SettingsLocation, SettingsStore};
49use smallvec::{smallvec, SmallVec};
50use smol::channel::{self, Sender};
51use std::{
52 any::Any,
53 cmp::Ordering,
54 collections::hash_map,
55 convert::TryFrom,
56 ffi::OsStr,
57 fmt,
58 future::Future,
59 mem::{self},
60 ops::{Deref, DerefMut},
61 path::{Component, Path, PathBuf},
62 pin::Pin,
63 sync::{
64 atomic::{self, AtomicI32, AtomicUsize, Ordering::SeqCst},
65 Arc,
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 paths::{home_dir, PathMatcher, SanitizedPath},
73 ResultExt,
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
1045 .repo_ptr
1046 .load_index_text(None, repo_path)
1047 .await);
1048 }
1049 }
1050 }
1051 Err(anyhow!("No repository found for {path:?}"))
1052 })
1053 }
1054 Worktree::Remote(_) => {
1055 Task::ready(Err(anyhow!("remote worktrees can't yet load staged files")))
1056 }
1057 }
1058 }
1059
1060 pub fn load_committed_file(&self, path: &Path, cx: &App) -> Task<Result<Option<String>>> {
1061 match self {
1062 Worktree::Local(this) => {
1063 let path = Arc::from(path);
1064 let snapshot = this.snapshot();
1065 cx.spawn(async move |_cx| {
1066 if let Some(repo) = snapshot.local_repo_containing_path(&path) {
1067 if let Some(repo_path) = repo.relativize(&path).log_err() {
1068 if let Some(git_repo) =
1069 snapshot.git_repositories.get(&repo.work_directory_id)
1070 {
1071 return Ok(git_repo.repo_ptr.load_committed_text(repo_path).await);
1072 }
1073 }
1074 }
1075 Err(anyhow!("No repository found for {path:?}"))
1076 })
1077 }
1078 Worktree::Remote(_) => Task::ready(Err(anyhow!(
1079 "remote worktrees can't yet load committed files"
1080 ))),
1081 }
1082 }
1083
1084 pub fn load_binary_file(
1085 &self,
1086 path: &Path,
1087 cx: &Context<Worktree>,
1088 ) -> Task<Result<LoadedBinaryFile>> {
1089 match self {
1090 Worktree::Local(this) => this.load_binary_file(path, cx),
1091 Worktree::Remote(_) => {
1092 Task::ready(Err(anyhow!("remote worktrees can't yet load binary files")))
1093 }
1094 }
1095 }
1096
1097 pub fn write_file(
1098 &self,
1099 path: &Path,
1100 text: Rope,
1101 line_ending: LineEnding,
1102 cx: &Context<Worktree>,
1103 ) -> Task<Result<Arc<File>>> {
1104 match self {
1105 Worktree::Local(this) => this.write_file(path, text, line_ending, cx),
1106 Worktree::Remote(_) => {
1107 Task::ready(Err(anyhow!("remote worktree can't yet write files")))
1108 }
1109 }
1110 }
1111
1112 pub fn create_entry(
1113 &mut self,
1114 path: impl Into<Arc<Path>>,
1115 is_directory: bool,
1116 cx: &Context<Worktree>,
1117 ) -> Task<Result<CreatedEntry>> {
1118 let path: Arc<Path> = path.into();
1119 let worktree_id = self.id();
1120 match self {
1121 Worktree::Local(this) => this.create_entry(path, is_directory, cx),
1122 Worktree::Remote(this) => {
1123 let project_id = this.project_id;
1124 let request = this.client.request(proto::CreateProjectEntry {
1125 worktree_id: worktree_id.to_proto(),
1126 project_id,
1127 path: path.as_ref().to_proto(),
1128 is_directory,
1129 });
1130 cx.spawn(async move |this, cx| {
1131 let response = request.await?;
1132 match response.entry {
1133 Some(entry) => this
1134 .update(cx, |worktree, cx| {
1135 worktree.as_remote_mut().unwrap().insert_entry(
1136 entry,
1137 response.worktree_scan_id as usize,
1138 cx,
1139 )
1140 })?
1141 .await
1142 .map(CreatedEntry::Included),
1143 None => {
1144 let abs_path = this.update(cx, |worktree, _| {
1145 worktree
1146 .absolutize(&path)
1147 .with_context(|| format!("absolutizing {path:?}"))
1148 })??;
1149 Ok(CreatedEntry::Excluded { abs_path })
1150 }
1151 }
1152 })
1153 }
1154 }
1155 }
1156
1157 pub fn delete_entry(
1158 &mut self,
1159 entry_id: ProjectEntryId,
1160 trash: bool,
1161 cx: &mut Context<Worktree>,
1162 ) -> Option<Task<Result<()>>> {
1163 let task = match self {
1164 Worktree::Local(this) => this.delete_entry(entry_id, trash, cx),
1165 Worktree::Remote(this) => this.delete_entry(entry_id, trash, cx),
1166 }?;
1167
1168 let entry = match self {
1169 Worktree::Local(ref this) => this.entry_for_id(entry_id),
1170 Worktree::Remote(ref this) => this.entry_for_id(entry_id),
1171 }?;
1172
1173 let mut ids = vec![entry_id];
1174 let path = &*entry.path;
1175
1176 self.get_children_ids_recursive(path, &mut ids);
1177
1178 for id in ids {
1179 cx.emit(Event::DeletedEntry(id));
1180 }
1181 Some(task)
1182 }
1183
1184 fn get_children_ids_recursive(&self, path: &Path, ids: &mut Vec<ProjectEntryId>) {
1185 let children_iter = self.child_entries(path);
1186 for child in children_iter {
1187 ids.push(child.id);
1188 self.get_children_ids_recursive(&child.path, ids);
1189 }
1190 }
1191
1192 pub fn rename_entry(
1193 &mut self,
1194 entry_id: ProjectEntryId,
1195 new_path: impl Into<Arc<Path>>,
1196 cx: &Context<Self>,
1197 ) -> Task<Result<CreatedEntry>> {
1198 let new_path = new_path.into();
1199 match self {
1200 Worktree::Local(this) => this.rename_entry(entry_id, new_path, cx),
1201 Worktree::Remote(this) => this.rename_entry(entry_id, new_path, cx),
1202 }
1203 }
1204
1205 pub fn copy_entry(
1206 &mut self,
1207 entry_id: ProjectEntryId,
1208 relative_worktree_source_path: Option<PathBuf>,
1209 new_path: impl Into<Arc<Path>>,
1210 cx: &Context<Self>,
1211 ) -> Task<Result<Option<Entry>>> {
1212 let new_path: Arc<Path> = new_path.into();
1213 match self {
1214 Worktree::Local(this) => {
1215 this.copy_entry(entry_id, relative_worktree_source_path, new_path, cx)
1216 }
1217 Worktree::Remote(this) => {
1218 let relative_worktree_source_path = relative_worktree_source_path
1219 .map(|relative_worktree_source_path| relative_worktree_source_path.to_proto());
1220 let response = this.client.request(proto::CopyProjectEntry {
1221 project_id: this.project_id,
1222 entry_id: entry_id.to_proto(),
1223 relative_worktree_source_path,
1224 new_path: new_path.to_proto(),
1225 });
1226 cx.spawn(async move |this, cx| {
1227 let response = response.await?;
1228 match response.entry {
1229 Some(entry) => this
1230 .update(cx, |worktree, cx| {
1231 worktree.as_remote_mut().unwrap().insert_entry(
1232 entry,
1233 response.worktree_scan_id as usize,
1234 cx,
1235 )
1236 })?
1237 .await
1238 .map(Some),
1239 None => Ok(None),
1240 }
1241 })
1242 }
1243 }
1244 }
1245
1246 pub fn copy_external_entries(
1247 &mut self,
1248 target_directory: PathBuf,
1249 paths: Vec<Arc<Path>>,
1250 overwrite_existing_files: bool,
1251 cx: &Context<Worktree>,
1252 ) -> Task<Result<Vec<ProjectEntryId>>> {
1253 match self {
1254 Worktree::Local(this) => {
1255 this.copy_external_entries(target_directory, paths, overwrite_existing_files, cx)
1256 }
1257 _ => Task::ready(Err(anyhow!(
1258 "Copying external entries is not supported for remote worktrees"
1259 ))),
1260 }
1261 }
1262
1263 pub fn expand_entry(
1264 &mut self,
1265 entry_id: ProjectEntryId,
1266 cx: &Context<Worktree>,
1267 ) -> Option<Task<Result<()>>> {
1268 match self {
1269 Worktree::Local(this) => this.expand_entry(entry_id, cx),
1270 Worktree::Remote(this) => {
1271 let response = this.client.request(proto::ExpandProjectEntry {
1272 project_id: this.project_id,
1273 entry_id: entry_id.to_proto(),
1274 });
1275 Some(cx.spawn(async move |this, cx| {
1276 let response = response.await?;
1277 this.update(cx, |this, _| {
1278 this.as_remote_mut()
1279 .unwrap()
1280 .wait_for_snapshot(response.worktree_scan_id as usize)
1281 })?
1282 .await?;
1283 Ok(())
1284 }))
1285 }
1286 }
1287 }
1288
1289 pub fn expand_all_for_entry(
1290 &mut self,
1291 entry_id: ProjectEntryId,
1292 cx: &Context<Worktree>,
1293 ) -> Option<Task<Result<()>>> {
1294 match self {
1295 Worktree::Local(this) => this.expand_all_for_entry(entry_id, cx),
1296 Worktree::Remote(this) => {
1297 let response = this.client.request(proto::ExpandAllForProjectEntry {
1298 project_id: this.project_id,
1299 entry_id: entry_id.to_proto(),
1300 });
1301 Some(cx.spawn(async move |this, cx| {
1302 let response = response.await?;
1303 this.update(cx, |this, _| {
1304 this.as_remote_mut()
1305 .unwrap()
1306 .wait_for_snapshot(response.worktree_scan_id as usize)
1307 })?
1308 .await?;
1309 Ok(())
1310 }))
1311 }
1312 }
1313 }
1314
1315 pub async fn handle_create_entry(
1316 this: Entity<Self>,
1317 request: proto::CreateProjectEntry,
1318 mut cx: AsyncApp,
1319 ) -> Result<proto::ProjectEntryResponse> {
1320 let (scan_id, entry) = this.update(&mut cx, |this, cx| {
1321 (
1322 this.scan_id(),
1323 this.create_entry(
1324 Arc::<Path>::from_proto(request.path),
1325 request.is_directory,
1326 cx,
1327 ),
1328 )
1329 })?;
1330 Ok(proto::ProjectEntryResponse {
1331 entry: match &entry.await? {
1332 CreatedEntry::Included(entry) => Some(entry.into()),
1333 CreatedEntry::Excluded { .. } => None,
1334 },
1335 worktree_scan_id: scan_id as u64,
1336 })
1337 }
1338
1339 pub async fn handle_delete_entry(
1340 this: Entity<Self>,
1341 request: proto::DeleteProjectEntry,
1342 mut cx: AsyncApp,
1343 ) -> Result<proto::ProjectEntryResponse> {
1344 let (scan_id, task) = this.update(&mut cx, |this, cx| {
1345 (
1346 this.scan_id(),
1347 this.delete_entry(
1348 ProjectEntryId::from_proto(request.entry_id),
1349 request.use_trash,
1350 cx,
1351 ),
1352 )
1353 })?;
1354 task.ok_or_else(|| anyhow!("invalid entry"))?.await?;
1355 Ok(proto::ProjectEntryResponse {
1356 entry: None,
1357 worktree_scan_id: scan_id as u64,
1358 })
1359 }
1360
1361 pub async fn handle_expand_entry(
1362 this: Entity<Self>,
1363 request: proto::ExpandProjectEntry,
1364 mut cx: AsyncApp,
1365 ) -> Result<proto::ExpandProjectEntryResponse> {
1366 let task = this.update(&mut cx, |this, cx| {
1367 this.expand_entry(ProjectEntryId::from_proto(request.entry_id), cx)
1368 })?;
1369 task.ok_or_else(|| anyhow!("no such entry"))?.await?;
1370 let scan_id = this.read_with(&cx, |this, _| this.scan_id())?;
1371 Ok(proto::ExpandProjectEntryResponse {
1372 worktree_scan_id: scan_id as u64,
1373 })
1374 }
1375
1376 pub async fn handle_expand_all_for_entry(
1377 this: Entity<Self>,
1378 request: proto::ExpandAllForProjectEntry,
1379 mut cx: AsyncApp,
1380 ) -> Result<proto::ExpandAllForProjectEntryResponse> {
1381 let task = this.update(&mut cx, |this, cx| {
1382 this.expand_all_for_entry(ProjectEntryId::from_proto(request.entry_id), cx)
1383 })?;
1384 task.ok_or_else(|| anyhow!("no such entry"))?.await?;
1385 let scan_id = this.read_with(&cx, |this, _| this.scan_id())?;
1386 Ok(proto::ExpandAllForProjectEntryResponse {
1387 worktree_scan_id: scan_id as u64,
1388 })
1389 }
1390
1391 pub async fn handle_rename_entry(
1392 this: Entity<Self>,
1393 request: proto::RenameProjectEntry,
1394 mut cx: AsyncApp,
1395 ) -> Result<proto::ProjectEntryResponse> {
1396 let (scan_id, task) = this.update(&mut cx, |this, cx| {
1397 (
1398 this.scan_id(),
1399 this.rename_entry(
1400 ProjectEntryId::from_proto(request.entry_id),
1401 Arc::<Path>::from_proto(request.new_path),
1402 cx,
1403 ),
1404 )
1405 })?;
1406 Ok(proto::ProjectEntryResponse {
1407 entry: match &task.await? {
1408 CreatedEntry::Included(entry) => Some(entry.into()),
1409 CreatedEntry::Excluded { .. } => None,
1410 },
1411 worktree_scan_id: scan_id as u64,
1412 })
1413 }
1414
1415 pub async fn handle_copy_entry(
1416 this: Entity<Self>,
1417 request: proto::CopyProjectEntry,
1418 mut cx: AsyncApp,
1419 ) -> Result<proto::ProjectEntryResponse> {
1420 let (scan_id, task) = this.update(&mut cx, |this, cx| {
1421 let relative_worktree_source_path = request
1422 .relative_worktree_source_path
1423 .map(PathBuf::from_proto);
1424 (
1425 this.scan_id(),
1426 this.copy_entry(
1427 ProjectEntryId::from_proto(request.entry_id),
1428 relative_worktree_source_path,
1429 PathBuf::from_proto(request.new_path),
1430 cx,
1431 ),
1432 )
1433 })?;
1434 Ok(proto::ProjectEntryResponse {
1435 entry: task.await?.as_ref().map(|e| e.into()),
1436 worktree_scan_id: scan_id as u64,
1437 })
1438 }
1439
1440 pub fn dot_git_abs_path(&self, work_directory: &WorkDirectory) -> PathBuf {
1441 let mut path = match work_directory {
1442 WorkDirectory::InProject { relative_path } => self.abs_path().join(relative_path),
1443 WorkDirectory::AboveProject { absolute_path, .. } => absolute_path.as_ref().to_owned(),
1444 };
1445 path.push(".git");
1446 path
1447 }
1448
1449 pub fn is_single_file(&self) -> bool {
1450 self.root_dir().is_none()
1451 }
1452}
1453
1454impl LocalWorktree {
1455 pub fn fs(&self) -> &Arc<dyn Fs> {
1456 &self.fs
1457 }
1458
1459 pub fn is_path_private(&self, path: &Path) -> bool {
1460 !self.share_private_files && self.settings.is_path_private(path)
1461 }
1462
1463 fn restart_background_scanners(&mut self, cx: &Context<Worktree>) {
1464 let (scan_requests_tx, scan_requests_rx) = channel::unbounded();
1465 let (path_prefixes_to_scan_tx, path_prefixes_to_scan_rx) = channel::unbounded();
1466 self.scan_requests_tx = scan_requests_tx;
1467 self.path_prefixes_to_scan_tx = path_prefixes_to_scan_tx;
1468
1469 self.start_background_scanner(scan_requests_rx, path_prefixes_to_scan_rx, cx);
1470 let always_included_entries = mem::take(&mut self.snapshot.always_included_entries);
1471 log::debug!(
1472 "refreshing entries for the following always included paths: {:?}",
1473 always_included_entries
1474 );
1475
1476 // Cleans up old always included entries to ensure they get updated properly. Otherwise,
1477 // nested always included entries may not get updated and will result in out-of-date info.
1478 self.refresh_entries_for_paths(always_included_entries);
1479 }
1480
1481 fn start_background_scanner(
1482 &mut self,
1483 scan_requests_rx: channel::Receiver<ScanRequest>,
1484 path_prefixes_to_scan_rx: channel::Receiver<PathPrefixScanRequest>,
1485 cx: &Context<Worktree>,
1486 ) {
1487 let snapshot = self.snapshot();
1488 let share_private_files = self.share_private_files;
1489 let next_entry_id = self.next_entry_id.clone();
1490 let fs = self.fs.clone();
1491 let git_hosting_provider_registry = GitHostingProviderRegistry::try_global(cx);
1492 let settings = self.settings.clone();
1493 let (scan_states_tx, mut scan_states_rx) = mpsc::unbounded();
1494 let background_scanner = cx.background_spawn({
1495 let abs_path = snapshot.abs_path.as_path().to_path_buf();
1496 let background = cx.background_executor().clone();
1497 async move {
1498 let (events, watcher) = fs.watch(&abs_path, FS_WATCH_LATENCY).await;
1499 let fs_case_sensitive = fs.is_case_sensitive().await.unwrap_or_else(|e| {
1500 log::error!("Failed to determine whether filesystem is case sensitive: {e:#}");
1501 true
1502 });
1503
1504 let mut scanner = BackgroundScanner {
1505 fs,
1506 fs_case_sensitive,
1507 status_updates_tx: scan_states_tx,
1508 scans_running: Arc::new(AtomicI32::new(0)),
1509 executor: background,
1510 scan_requests_rx,
1511 path_prefixes_to_scan_rx,
1512 next_entry_id,
1513 state: Arc::new(Mutex::new(BackgroundScannerState {
1514 prev_snapshot: snapshot.snapshot.clone(),
1515 snapshot,
1516 scanned_dirs: Default::default(),
1517 path_prefixes_to_scan: Default::default(),
1518 paths_to_scan: Default::default(),
1519 removed_entries: Default::default(),
1520 changed_paths: Default::default(),
1521 repository_scans: HashMap::default(),
1522 git_hosting_provider_registry,
1523 })),
1524 phase: BackgroundScannerPhase::InitialScan,
1525 share_private_files,
1526 settings,
1527 watcher,
1528 };
1529
1530 scanner
1531 .run(Box::pin(events.map(|events| events.into_iter().collect())))
1532 .await;
1533 }
1534 });
1535 let scan_state_updater = cx.spawn(async move |this, cx| {
1536 while let Some((state, this)) = scan_states_rx.next().await.zip(this.upgrade()) {
1537 this.update(cx, |this, cx| {
1538 let this = this.as_local_mut().unwrap();
1539 match state {
1540 ScanState::Started => {
1541 *this.is_scanning.0.borrow_mut() = true;
1542 }
1543 ScanState::Updated {
1544 snapshot,
1545 changes,
1546 barrier,
1547 scanning,
1548 } => {
1549 *this.is_scanning.0.borrow_mut() = scanning;
1550 this.set_snapshot(snapshot, changes, cx);
1551 drop(barrier);
1552 }
1553 ScanState::RootUpdated { new_path } => {
1554 this.update_abs_path_and_refresh(new_path, cx);
1555 }
1556 }
1557 })
1558 .ok();
1559 }
1560 });
1561 self._background_scanner_tasks = vec![background_scanner, scan_state_updater];
1562 self.is_scanning = watch::channel_with(true);
1563 }
1564
1565 fn set_snapshot(
1566 &mut self,
1567 new_snapshot: LocalSnapshot,
1568 entry_changes: UpdatedEntriesSet,
1569 cx: &mut Context<Worktree>,
1570 ) {
1571 let repo_changes = self.changed_repos(&self.snapshot, &new_snapshot);
1572 self.snapshot = new_snapshot;
1573
1574 if let Some(share) = self.update_observer.as_mut() {
1575 share
1576 .snapshots_tx
1577 .unbounded_send((self.snapshot.clone(), entry_changes.clone()))
1578 .ok();
1579 }
1580
1581 if !entry_changes.is_empty() {
1582 cx.emit(Event::UpdatedEntries(entry_changes));
1583 }
1584 if !repo_changes.is_empty() {
1585 cx.emit(Event::UpdatedGitRepositories(repo_changes));
1586 }
1587 }
1588
1589 fn changed_repos(
1590 &self,
1591 old_snapshot: &LocalSnapshot,
1592 new_snapshot: &LocalSnapshot,
1593 ) -> UpdatedGitRepositoriesSet {
1594 let mut changes = Vec::new();
1595 let mut old_repos = old_snapshot.git_repositories.iter().peekable();
1596 let mut new_repos = new_snapshot.git_repositories.iter().peekable();
1597
1598 loop {
1599 match (new_repos.peek().map(clone), old_repos.peek().map(clone)) {
1600 (Some((new_entry_id, new_repo)), Some((old_entry_id, old_repo))) => {
1601 match Ord::cmp(&new_entry_id, &old_entry_id) {
1602 Ordering::Less => {
1603 if let Some(entry) = new_snapshot.entry_for_id(new_entry_id) {
1604 changes.push((
1605 entry.clone(),
1606 GitRepositoryChange {
1607 old_repository: None,
1608 },
1609 ));
1610 }
1611 new_repos.next();
1612 }
1613 Ordering::Equal => {
1614 if new_repo.git_dir_scan_id != old_repo.git_dir_scan_id
1615 || new_repo.status_scan_id != old_repo.status_scan_id
1616 {
1617 if let Some(entry) = new_snapshot.entry_for_id(new_entry_id) {
1618 let old_repo =
1619 old_snapshot.repository_for_id(old_entry_id).cloned();
1620 changes.push((
1621 entry.clone(),
1622 GitRepositoryChange {
1623 old_repository: old_repo,
1624 },
1625 ));
1626 }
1627 }
1628 new_repos.next();
1629 old_repos.next();
1630 }
1631 Ordering::Greater => {
1632 if let Some(entry) = old_snapshot.entry_for_id(old_entry_id) {
1633 let old_repo =
1634 old_snapshot.repository_for_id(old_entry_id).cloned();
1635 changes.push((
1636 entry.clone(),
1637 GitRepositoryChange {
1638 old_repository: old_repo,
1639 },
1640 ));
1641 }
1642 old_repos.next();
1643 }
1644 }
1645 }
1646 (Some((entry_id, _)), None) => {
1647 if let Some(entry) = new_snapshot.entry_for_id(entry_id) {
1648 changes.push((
1649 entry.clone(),
1650 GitRepositoryChange {
1651 old_repository: None,
1652 },
1653 ));
1654 }
1655 new_repos.next();
1656 }
1657 (None, Some((entry_id, _))) => {
1658 if let Some(entry) = old_snapshot.entry_for_id(entry_id) {
1659 let old_repo = old_snapshot.repository_for_id(entry_id).cloned();
1660 changes.push((
1661 entry.clone(),
1662 GitRepositoryChange {
1663 old_repository: old_repo,
1664 },
1665 ));
1666 }
1667 old_repos.next();
1668 }
1669 (None, None) => break,
1670 }
1671 }
1672
1673 fn clone<T: Clone, U: Clone>(value: &(&T, &U)) -> (T, U) {
1674 (value.0.clone(), value.1.clone())
1675 }
1676
1677 changes.into()
1678 }
1679
1680 pub fn scan_complete(&self) -> impl Future<Output = ()> {
1681 let mut is_scanning_rx = self.is_scanning.1.clone();
1682 async move {
1683 let mut is_scanning = *is_scanning_rx.borrow();
1684 while is_scanning {
1685 if let Some(value) = is_scanning_rx.recv().await {
1686 is_scanning = value;
1687 } else {
1688 break;
1689 }
1690 }
1691 }
1692 }
1693
1694 pub fn snapshot(&self) -> LocalSnapshot {
1695 self.snapshot.clone()
1696 }
1697
1698 pub fn settings(&self) -> WorktreeSettings {
1699 self.settings.clone()
1700 }
1701
1702 pub fn get_local_repo(&self, repo: &RepositoryEntry) -> Option<&LocalRepositoryEntry> {
1703 self.git_repositories.get(&repo.work_directory_id)
1704 }
1705
1706 fn load_binary_file(
1707 &self,
1708 path: &Path,
1709 cx: &Context<Worktree>,
1710 ) -> Task<Result<LoadedBinaryFile>> {
1711 let path = Arc::from(path);
1712 let abs_path = self.absolutize(&path);
1713 let fs = self.fs.clone();
1714 let entry = self.refresh_entry(path.clone(), None, cx);
1715 let is_private = self.is_path_private(path.as_ref());
1716
1717 let worktree = cx.weak_entity();
1718 cx.background_spawn(async move {
1719 let abs_path = abs_path?;
1720 let content = fs.load_bytes(&abs_path).await?;
1721
1722 let worktree = worktree
1723 .upgrade()
1724 .ok_or_else(|| anyhow!("worktree was dropped"))?;
1725 let file = match entry.await? {
1726 Some(entry) => File::for_entry(entry, worktree),
1727 None => {
1728 let metadata = fs
1729 .metadata(&abs_path)
1730 .await
1731 .with_context(|| {
1732 format!("Loading metadata for excluded file {abs_path:?}")
1733 })?
1734 .with_context(|| {
1735 format!("Excluded file {abs_path:?} got removed during loading")
1736 })?;
1737 Arc::new(File {
1738 entry_id: None,
1739 worktree,
1740 path,
1741 disk_state: DiskState::Present {
1742 mtime: metadata.mtime,
1743 },
1744 is_local: true,
1745 is_private,
1746 })
1747 }
1748 };
1749
1750 Ok(LoadedBinaryFile { file, content })
1751 })
1752 }
1753
1754 fn load_file(&self, path: &Path, cx: &Context<Worktree>) -> Task<Result<LoadedFile>> {
1755 let path = Arc::from(path);
1756 let abs_path = self.absolutize(&path);
1757 let fs = self.fs.clone();
1758 let entry = self.refresh_entry(path.clone(), None, cx);
1759 let is_private = self.is_path_private(path.as_ref());
1760
1761 cx.spawn(async move |this, _cx| {
1762 let abs_path = abs_path?;
1763 // WARN: Temporary workaround for #27283.
1764 // We are not efficient with our memory usage per file, and use in excess of 64GB for a 10GB file
1765 // Therefore, as a temporary workaround to prevent system freezes, we just bail before opening a file
1766 // if it is too large
1767 // 5GB seems to be more reasonable, peaking at ~16GB, while 6GB jumps up to >24GB which seems like a
1768 // reasonable limit
1769 {
1770 const FILE_SIZE_MAX: u64 = 6 * 1024 * 1024 * 1024; // 6GB
1771 if let Ok(Some(metadata)) = fs.metadata(&abs_path).await {
1772 if metadata.len >= FILE_SIZE_MAX {
1773 anyhow::bail!("File is too large to load");
1774 }
1775 }
1776 }
1777 let text = fs.load(&abs_path).await?;
1778
1779 let worktree = this
1780 .upgrade()
1781 .ok_or_else(|| anyhow!("worktree was dropped"))?;
1782 let file = match entry.await? {
1783 Some(entry) => File::for_entry(entry, worktree),
1784 None => {
1785 let metadata = fs
1786 .metadata(&abs_path)
1787 .await
1788 .with_context(|| {
1789 format!("Loading metadata for excluded file {abs_path:?}")
1790 })?
1791 .with_context(|| {
1792 format!("Excluded file {abs_path:?} got removed during loading")
1793 })?;
1794 Arc::new(File {
1795 entry_id: None,
1796 worktree,
1797 path,
1798 disk_state: DiskState::Present {
1799 mtime: metadata.mtime,
1800 },
1801 is_local: true,
1802 is_private,
1803 })
1804 }
1805 };
1806
1807 Ok(LoadedFile { file, text })
1808 })
1809 }
1810
1811 /// Find the lowest path in the worktree's datastructures that is an ancestor
1812 fn lowest_ancestor(&self, path: &Path) -> PathBuf {
1813 let mut lowest_ancestor = None;
1814 for path in path.ancestors() {
1815 if self.entry_for_path(path).is_some() {
1816 lowest_ancestor = Some(path.to_path_buf());
1817 break;
1818 }
1819 }
1820
1821 lowest_ancestor.unwrap_or_else(|| PathBuf::from(""))
1822 }
1823
1824 fn create_entry(
1825 &self,
1826 path: impl Into<Arc<Path>>,
1827 is_dir: bool,
1828 cx: &Context<Worktree>,
1829 ) -> Task<Result<CreatedEntry>> {
1830 let path = path.into();
1831 let abs_path = match self.absolutize(&path) {
1832 Ok(path) => path,
1833 Err(e) => return Task::ready(Err(e.context(format!("absolutizing path {path:?}")))),
1834 };
1835 let path_excluded = self.settings.is_path_excluded(&abs_path);
1836 let fs = self.fs.clone();
1837 let task_abs_path = abs_path.clone();
1838 let write = cx.background_spawn(async move {
1839 if is_dir {
1840 fs.create_dir(&task_abs_path)
1841 .await
1842 .with_context(|| format!("creating directory {task_abs_path:?}"))
1843 } else {
1844 fs.save(&task_abs_path, &Rope::default(), LineEnding::default())
1845 .await
1846 .with_context(|| format!("creating file {task_abs_path:?}"))
1847 }
1848 });
1849
1850 let lowest_ancestor = self.lowest_ancestor(&path);
1851 cx.spawn(async move |this, cx| {
1852 write.await?;
1853 if path_excluded {
1854 return Ok(CreatedEntry::Excluded { abs_path });
1855 }
1856
1857 let (result, refreshes) = this.update(cx, |this, cx| {
1858 let mut refreshes = Vec::new();
1859 let refresh_paths = path.strip_prefix(&lowest_ancestor).unwrap();
1860 for refresh_path in refresh_paths.ancestors() {
1861 if refresh_path == Path::new("") {
1862 continue;
1863 }
1864 let refresh_full_path = lowest_ancestor.join(refresh_path);
1865
1866 refreshes.push(this.as_local_mut().unwrap().refresh_entry(
1867 refresh_full_path.into(),
1868 None,
1869 cx,
1870 ));
1871 }
1872 (
1873 this.as_local_mut().unwrap().refresh_entry(path, None, cx),
1874 refreshes,
1875 )
1876 })?;
1877 for refresh in refreshes {
1878 refresh.await.log_err();
1879 }
1880
1881 Ok(result
1882 .await?
1883 .map(CreatedEntry::Included)
1884 .unwrap_or_else(|| CreatedEntry::Excluded { abs_path }))
1885 })
1886 }
1887
1888 fn write_file(
1889 &self,
1890 path: impl Into<Arc<Path>>,
1891 text: Rope,
1892 line_ending: LineEnding,
1893 cx: &Context<Worktree>,
1894 ) -> Task<Result<Arc<File>>> {
1895 let path = path.into();
1896 let fs = self.fs.clone();
1897 let is_private = self.is_path_private(&path);
1898 let Ok(abs_path) = self.absolutize(&path) else {
1899 return Task::ready(Err(anyhow!("invalid path {path:?}")));
1900 };
1901
1902 let write = cx.background_spawn({
1903 let fs = fs.clone();
1904 let abs_path = abs_path.clone();
1905 async move { fs.save(&abs_path, &text, line_ending).await }
1906 });
1907
1908 cx.spawn(async move |this, cx| {
1909 write.await?;
1910 let entry = this
1911 .update(cx, |this, cx| {
1912 this.as_local_mut()
1913 .unwrap()
1914 .refresh_entry(path.clone(), None, cx)
1915 })?
1916 .await?;
1917 let worktree = this.upgrade().ok_or_else(|| anyhow!("worktree dropped"))?;
1918 if let Some(entry) = entry {
1919 Ok(File::for_entry(entry, worktree))
1920 } else {
1921 let metadata = fs
1922 .metadata(&abs_path)
1923 .await
1924 .with_context(|| {
1925 format!("Fetching metadata after saving the excluded buffer {abs_path:?}")
1926 })?
1927 .with_context(|| {
1928 format!("Excluded buffer {path:?} got removed during saving")
1929 })?;
1930 Ok(Arc::new(File {
1931 worktree,
1932 path,
1933 disk_state: DiskState::Present {
1934 mtime: metadata.mtime,
1935 },
1936 entry_id: None,
1937 is_local: true,
1938 is_private,
1939 }))
1940 }
1941 })
1942 }
1943
1944 fn delete_entry(
1945 &self,
1946 entry_id: ProjectEntryId,
1947 trash: bool,
1948 cx: &Context<Worktree>,
1949 ) -> Option<Task<Result<()>>> {
1950 let entry = self.entry_for_id(entry_id)?.clone();
1951 let abs_path = self.absolutize(&entry.path);
1952 let fs = self.fs.clone();
1953
1954 let delete = cx.background_spawn(async move {
1955 if entry.is_file() {
1956 if trash {
1957 fs.trash_file(&abs_path?, Default::default()).await?;
1958 } else {
1959 fs.remove_file(&abs_path?, Default::default()).await?;
1960 }
1961 } else if trash {
1962 fs.trash_dir(
1963 &abs_path?,
1964 RemoveOptions {
1965 recursive: true,
1966 ignore_if_not_exists: false,
1967 },
1968 )
1969 .await?;
1970 } else {
1971 fs.remove_dir(
1972 &abs_path?,
1973 RemoveOptions {
1974 recursive: true,
1975 ignore_if_not_exists: false,
1976 },
1977 )
1978 .await?;
1979 }
1980 anyhow::Ok(entry.path)
1981 });
1982
1983 Some(cx.spawn(async move |this, cx| {
1984 let path = delete.await?;
1985 this.update(cx, |this, _| {
1986 this.as_local_mut()
1987 .unwrap()
1988 .refresh_entries_for_paths(vec![path])
1989 })?
1990 .recv()
1991 .await;
1992 Ok(())
1993 }))
1994 }
1995
1996 /// Rename an entry.
1997 ///
1998 /// `new_path` is the new relative path to the worktree root.
1999 /// If the root entry is renamed then `new_path` is the new root name instead.
2000 fn rename_entry(
2001 &self,
2002 entry_id: ProjectEntryId,
2003 new_path: impl Into<Arc<Path>>,
2004 cx: &Context<Worktree>,
2005 ) -> Task<Result<CreatedEntry>> {
2006 let old_path = match self.entry_for_id(entry_id) {
2007 Some(entry) => entry.path.clone(),
2008 None => return Task::ready(Err(anyhow!("no entry to rename for id {entry_id:?}"))),
2009 };
2010 let new_path = new_path.into();
2011 let abs_old_path = self.absolutize(&old_path);
2012
2013 let is_root_entry = self.root_entry().is_some_and(|e| e.id == entry_id);
2014 let abs_new_path = if is_root_entry {
2015 let Some(root_parent_path) = self.abs_path().parent() else {
2016 return Task::ready(Err(anyhow!("no parent for path {:?}", self.abs_path)));
2017 };
2018 root_parent_path.join(&new_path)
2019 } else {
2020 let Ok(absolutize_path) = self.absolutize(&new_path) else {
2021 return Task::ready(Err(anyhow!("absolutizing path {new_path:?}")));
2022 };
2023 absolutize_path
2024 };
2025 let abs_path = abs_new_path.clone();
2026 let fs = self.fs.clone();
2027 let case_sensitive = self.fs_case_sensitive;
2028 let rename = cx.background_spawn(async move {
2029 let abs_old_path = abs_old_path?;
2030 let abs_new_path = abs_new_path;
2031
2032 let abs_old_path_lower = abs_old_path.to_str().map(|p| p.to_lowercase());
2033 let abs_new_path_lower = abs_new_path.to_str().map(|p| p.to_lowercase());
2034
2035 // If we're on a case-insensitive FS and we're doing a case-only rename (i.e. `foobar` to `FOOBAR`)
2036 // we want to overwrite, because otherwise we run into a file-already-exists error.
2037 let overwrite = !case_sensitive
2038 && abs_old_path != abs_new_path
2039 && abs_old_path_lower == abs_new_path_lower;
2040
2041 fs.rename(
2042 &abs_old_path,
2043 &abs_new_path,
2044 fs::RenameOptions {
2045 overwrite,
2046 ..Default::default()
2047 },
2048 )
2049 .await
2050 .with_context(|| format!("Renaming {abs_old_path:?} into {abs_new_path:?}"))
2051 });
2052
2053 cx.spawn(async move |this, cx| {
2054 rename.await?;
2055 Ok(this
2056 .update(cx, |this, cx| {
2057 let local = this.as_local_mut().unwrap();
2058 if is_root_entry {
2059 // We eagerly update `abs_path` and refresh this worktree.
2060 // Otherwise, the FS watcher would do it on the `RootUpdated` event,
2061 // but with a noticeable delay, so we handle it proactively.
2062 local.update_abs_path_and_refresh(
2063 Some(SanitizedPath::from(abs_path.clone())),
2064 cx,
2065 );
2066 Task::ready(Ok(this.root_entry().cloned()))
2067 } else {
2068 local.refresh_entry(new_path.clone(), Some(old_path), cx)
2069 }
2070 })?
2071 .await?
2072 .map(CreatedEntry::Included)
2073 .unwrap_or_else(|| CreatedEntry::Excluded { abs_path }))
2074 })
2075 }
2076
2077 fn copy_entry(
2078 &self,
2079 entry_id: ProjectEntryId,
2080 relative_worktree_source_path: Option<PathBuf>,
2081 new_path: impl Into<Arc<Path>>,
2082 cx: &Context<Worktree>,
2083 ) -> Task<Result<Option<Entry>>> {
2084 let old_path = match self.entry_for_id(entry_id) {
2085 Some(entry) => entry.path.clone(),
2086 None => return Task::ready(Ok(None)),
2087 };
2088 let new_path = new_path.into();
2089 let abs_old_path =
2090 if let Some(relative_worktree_source_path) = relative_worktree_source_path {
2091 Ok(self.abs_path().join(relative_worktree_source_path))
2092 } else {
2093 self.absolutize(&old_path)
2094 };
2095 let abs_new_path = self.absolutize(&new_path);
2096 let fs = self.fs.clone();
2097 let copy = cx.background_spawn(async move {
2098 copy_recursive(
2099 fs.as_ref(),
2100 &abs_old_path?,
2101 &abs_new_path?,
2102 Default::default(),
2103 )
2104 .await
2105 });
2106
2107 cx.spawn(async move |this, cx| {
2108 copy.await?;
2109 this.update(cx, |this, cx| {
2110 this.as_local_mut()
2111 .unwrap()
2112 .refresh_entry(new_path.clone(), None, cx)
2113 })?
2114 .await
2115 })
2116 }
2117
2118 pub fn copy_external_entries(
2119 &self,
2120 target_directory: PathBuf,
2121 paths: Vec<Arc<Path>>,
2122 overwrite_existing_files: bool,
2123 cx: &Context<Worktree>,
2124 ) -> Task<Result<Vec<ProjectEntryId>>> {
2125 let worktree_path = self.abs_path().clone();
2126 let fs = self.fs.clone();
2127 let paths = paths
2128 .into_iter()
2129 .filter_map(|source| {
2130 let file_name = source.file_name()?;
2131 let mut target = target_directory.clone();
2132 target.push(file_name);
2133
2134 // Do not allow copying the same file to itself.
2135 if source.as_ref() != target.as_path() {
2136 Some((source, target))
2137 } else {
2138 None
2139 }
2140 })
2141 .collect::<Vec<_>>();
2142
2143 let paths_to_refresh = paths
2144 .iter()
2145 .filter_map(|(_, target)| Some(target.strip_prefix(&worktree_path).ok()?.into()))
2146 .collect::<Vec<_>>();
2147
2148 cx.spawn(async move |this, cx| {
2149 cx.background_spawn(async move {
2150 for (source, target) in paths {
2151 copy_recursive(
2152 fs.as_ref(),
2153 &source,
2154 &target,
2155 fs::CopyOptions {
2156 overwrite: overwrite_existing_files,
2157 ..Default::default()
2158 },
2159 )
2160 .await
2161 .with_context(|| {
2162 anyhow!("Failed to copy file from {source:?} to {target:?}")
2163 })?;
2164 }
2165 Ok::<(), anyhow::Error>(())
2166 })
2167 .await
2168 .log_err();
2169 let mut refresh = cx.read_entity(
2170 &this.upgrade().with_context(|| "Dropped worktree")?,
2171 |this, _| {
2172 Ok::<postage::barrier::Receiver, anyhow::Error>(
2173 this.as_local()
2174 .with_context(|| "Worktree is not local")?
2175 .refresh_entries_for_paths(paths_to_refresh.clone()),
2176 )
2177 },
2178 )??;
2179
2180 cx.background_spawn(async move {
2181 refresh.next().await;
2182 Ok::<(), anyhow::Error>(())
2183 })
2184 .await
2185 .log_err();
2186
2187 let this = this.upgrade().with_context(|| "Dropped worktree")?;
2188 cx.read_entity(&this, |this, _| {
2189 paths_to_refresh
2190 .iter()
2191 .filter_map(|path| Some(this.entry_for_path(path)?.id))
2192 .collect()
2193 })
2194 })
2195 }
2196
2197 fn expand_entry(
2198 &self,
2199 entry_id: ProjectEntryId,
2200 cx: &Context<Worktree>,
2201 ) -> Option<Task<Result<()>>> {
2202 let path = self.entry_for_id(entry_id)?.path.clone();
2203 let mut refresh = self.refresh_entries_for_paths(vec![path]);
2204 Some(cx.background_spawn(async move {
2205 refresh.next().await;
2206 Ok(())
2207 }))
2208 }
2209
2210 fn expand_all_for_entry(
2211 &self,
2212 entry_id: ProjectEntryId,
2213 cx: &Context<Worktree>,
2214 ) -> Option<Task<Result<()>>> {
2215 let path = self.entry_for_id(entry_id).unwrap().path.clone();
2216 let mut rx = self.add_path_prefix_to_scan(path.clone());
2217 Some(cx.background_spawn(async move {
2218 rx.next().await;
2219 Ok(())
2220 }))
2221 }
2222
2223 fn refresh_entries_for_paths(&self, paths: Vec<Arc<Path>>) -> barrier::Receiver {
2224 let (tx, rx) = barrier::channel();
2225 self.scan_requests_tx
2226 .try_send(ScanRequest {
2227 relative_paths: paths,
2228 done: smallvec![tx],
2229 })
2230 .ok();
2231 rx
2232 }
2233
2234 pub fn add_path_prefix_to_scan(&self, path_prefix: Arc<Path>) -> barrier::Receiver {
2235 let (tx, rx) = barrier::channel();
2236 self.path_prefixes_to_scan_tx
2237 .try_send(PathPrefixScanRequest {
2238 path: path_prefix,
2239 done: smallvec![tx],
2240 })
2241 .ok();
2242 rx
2243 }
2244
2245 fn refresh_entry(
2246 &self,
2247 path: Arc<Path>,
2248 old_path: Option<Arc<Path>>,
2249 cx: &Context<Worktree>,
2250 ) -> Task<Result<Option<Entry>>> {
2251 if self.settings.is_path_excluded(&path) {
2252 return Task::ready(Ok(None));
2253 }
2254 let paths = if let Some(old_path) = old_path.as_ref() {
2255 vec![old_path.clone(), path.clone()]
2256 } else {
2257 vec![path.clone()]
2258 };
2259 let t0 = Instant::now();
2260 let mut refresh = self.refresh_entries_for_paths(paths);
2261 cx.spawn(async move |this, cx| {
2262 refresh.recv().await;
2263 log::trace!("refreshed entry {path:?} in {:?}", t0.elapsed());
2264 let new_entry = this.update(cx, |this, _| {
2265 this.entry_for_path(path)
2266 .cloned()
2267 .ok_or_else(|| anyhow!("failed to read path after update"))
2268 })??;
2269 Ok(Some(new_entry))
2270 })
2271 }
2272
2273 fn observe_updates<F, Fut>(&mut self, project_id: u64, cx: &Context<Worktree>, callback: F)
2274 where
2275 F: 'static + Send + Fn(proto::UpdateWorktree) -> Fut,
2276 Fut: 'static + Send + Future<Output = bool>,
2277 {
2278 if let Some(observer) = self.update_observer.as_mut() {
2279 *observer.resume_updates.borrow_mut() = ();
2280 return;
2281 }
2282
2283 let (resume_updates_tx, mut resume_updates_rx) = watch::channel::<()>();
2284 let (snapshots_tx, mut snapshots_rx) =
2285 mpsc::unbounded::<(LocalSnapshot, UpdatedEntriesSet)>();
2286 snapshots_tx
2287 .unbounded_send((self.snapshot(), Arc::default()))
2288 .ok();
2289
2290 let worktree_id = cx.entity_id().as_u64();
2291 let _maintain_remote_snapshot = cx.background_spawn(async move {
2292 let mut is_first = true;
2293 while let Some((snapshot, entry_changes)) = snapshots_rx.next().await {
2294 let update = if is_first {
2295 is_first = false;
2296 snapshot.build_initial_update(project_id, worktree_id)
2297 } else {
2298 snapshot.build_update(project_id, worktree_id, entry_changes)
2299 };
2300
2301 for update in proto::split_worktree_update(update) {
2302 let _ = resume_updates_rx.try_recv();
2303 loop {
2304 let result = callback(update.clone());
2305 if result.await {
2306 break;
2307 } else {
2308 log::info!("waiting to resume updates");
2309 if resume_updates_rx.next().await.is_none() {
2310 return Some(());
2311 }
2312 }
2313 }
2314 }
2315 }
2316 Some(())
2317 });
2318
2319 self.update_observer = Some(UpdateObservationState {
2320 snapshots_tx,
2321 resume_updates: resume_updates_tx,
2322 _maintain_remote_snapshot,
2323 });
2324 }
2325
2326 pub fn share_private_files(&mut self, cx: &Context<Worktree>) {
2327 self.share_private_files = true;
2328 self.restart_background_scanners(cx);
2329 }
2330
2331 fn update_abs_path_and_refresh(
2332 &mut self,
2333 new_path: Option<SanitizedPath>,
2334 cx: &Context<Worktree>,
2335 ) {
2336 if let Some(new_path) = new_path {
2337 self.snapshot.git_repositories = Default::default();
2338 self.snapshot.ignores_by_parent_abs_path = Default::default();
2339 let root_name = new_path
2340 .as_path()
2341 .file_name()
2342 .map_or(String::new(), |f| f.to_string_lossy().to_string());
2343 self.snapshot.update_abs_path(new_path, root_name);
2344 }
2345 self.restart_background_scanners(cx);
2346 }
2347}
2348
2349impl RemoteWorktree {
2350 pub fn project_id(&self) -> u64 {
2351 self.project_id
2352 }
2353
2354 pub fn client(&self) -> AnyProtoClient {
2355 self.client.clone()
2356 }
2357
2358 pub fn disconnected_from_host(&mut self) {
2359 self.updates_tx.take();
2360 self.snapshot_subscriptions.clear();
2361 self.disconnected = true;
2362 }
2363
2364 pub fn update_from_remote(&self, update: proto::UpdateWorktree) {
2365 if let Some(updates_tx) = &self.updates_tx {
2366 updates_tx
2367 .unbounded_send(update)
2368 .expect("consumer runs to completion");
2369 }
2370 }
2371
2372 fn observe_updates<F, Fut>(&mut self, project_id: u64, cx: &Context<Worktree>, callback: F)
2373 where
2374 F: 'static + Send + Fn(proto::UpdateWorktree) -> Fut,
2375 Fut: 'static + Send + Future<Output = bool>,
2376 {
2377 let (tx, mut rx) = mpsc::unbounded();
2378 let initial_update = self
2379 .snapshot
2380 .build_initial_update(project_id, self.id().to_proto());
2381 self.update_observer = Some(tx);
2382 cx.spawn(async move |this, cx| {
2383 let mut update = initial_update;
2384 'outer: loop {
2385 // SSH projects use a special project ID of 0, and we need to
2386 // remap it to the correct one here.
2387 update.project_id = project_id;
2388
2389 for chunk in split_worktree_update(update) {
2390 if !callback(chunk).await {
2391 break 'outer;
2392 }
2393 }
2394
2395 if let Some(next_update) = rx.next().await {
2396 update = next_update;
2397 } else {
2398 break;
2399 }
2400 }
2401 this.update(cx, |this, _| {
2402 let this = this.as_remote_mut().unwrap();
2403 this.update_observer.take();
2404 })
2405 })
2406 .detach();
2407 }
2408
2409 fn observed_snapshot(&self, scan_id: usize) -> bool {
2410 self.completed_scan_id >= scan_id
2411 }
2412
2413 pub fn wait_for_snapshot(&mut self, scan_id: usize) -> impl Future<Output = Result<()>> {
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!(self
3121 .entry_for_path(ignore_parent_path.join(*GITIGNORE))
3122 .is_some());
3123 }
3124 }
3125 }
3126
3127 #[cfg(test)]
3128 fn check_git_invariants(&self) {
3129 let dotgit_paths = self
3130 .git_repositories
3131 .iter()
3132 .map(|repo| repo.1.dot_git_dir_abs_path.clone())
3133 .collect::<HashSet<_>>();
3134 let work_dir_paths = self
3135 .repositories
3136 .iter()
3137 .map(|repo| repo.work_directory_abs_path.clone())
3138 .collect::<HashSet<_>>();
3139 assert_eq!(dotgit_paths.len(), work_dir_paths.len());
3140 assert_eq!(self.repositories.iter().count(), work_dir_paths.len());
3141 assert_eq!(self.git_repositories.iter().count(), work_dir_paths.len());
3142 for entry in self.repositories.iter() {
3143 self.git_repositories.get(&entry.work_directory_id).unwrap();
3144 }
3145 }
3146
3147 #[cfg(test)]
3148 pub fn entries_without_ids(&self, include_ignored: bool) -> Vec<(&Path, u64, bool)> {
3149 let mut paths = Vec::new();
3150 for entry in self.entries_by_path.cursor::<()>(&()) {
3151 if include_ignored || !entry.is_ignored {
3152 paths.push((entry.path.as_ref(), entry.inode, entry.is_ignored));
3153 }
3154 }
3155 paths.sort_by(|a, b| a.0.cmp(b.0));
3156 paths
3157 }
3158}
3159
3160impl BackgroundScannerState {
3161 fn should_scan_directory(&self, entry: &Entry) -> bool {
3162 (!entry.is_external && (!entry.is_ignored || entry.is_always_included))
3163 || entry.path.file_name() == Some(*DOT_GIT)
3164 || entry.path.file_name() == Some(local_settings_folder_relative_path().as_os_str())
3165 || self.scanned_dirs.contains(&entry.id) // If we've ever scanned it, keep scanning
3166 || self
3167 .paths_to_scan
3168 .iter()
3169 .any(|p| p.starts_with(&entry.path))
3170 || self
3171 .path_prefixes_to_scan
3172 .iter()
3173 .any(|p| entry.path.starts_with(p))
3174 }
3175
3176 fn enqueue_scan_dir(&self, abs_path: Arc<Path>, entry: &Entry, scan_job_tx: &Sender<ScanJob>) {
3177 let path = entry.path.clone();
3178 let ignore_stack = self.snapshot.ignore_stack_for_abs_path(&abs_path, true);
3179 let mut ancestor_inodes = self.snapshot.ancestor_inodes_for_path(&path);
3180
3181 if !ancestor_inodes.contains(&entry.inode) {
3182 ancestor_inodes.insert(entry.inode);
3183 scan_job_tx
3184 .try_send(ScanJob {
3185 abs_path,
3186 path,
3187 ignore_stack,
3188 scan_queue: scan_job_tx.clone(),
3189 ancestor_inodes,
3190 is_external: entry.is_external,
3191 })
3192 .unwrap();
3193 }
3194 }
3195
3196 fn reuse_entry_id(&mut self, entry: &mut Entry) {
3197 if let Some(mtime) = entry.mtime {
3198 // If an entry with the same inode was removed from the worktree during this scan,
3199 // then it *might* represent the same file or directory. But the OS might also have
3200 // re-used the inode for a completely different file or directory.
3201 //
3202 // Conditionally reuse the old entry's id:
3203 // * if the mtime is the same, the file was probably been renamed.
3204 // * if the path is the same, the file may just have been updated
3205 if let Some(removed_entry) = self.removed_entries.remove(&entry.inode) {
3206 if removed_entry.mtime == Some(mtime) || removed_entry.path == entry.path {
3207 entry.id = removed_entry.id;
3208 }
3209 } else if let Some(existing_entry) = self.snapshot.entry_for_path(&entry.path) {
3210 entry.id = existing_entry.id;
3211 }
3212 }
3213 }
3214
3215 fn insert_entry(&mut self, mut entry: Entry, fs: &dyn Fs, watcher: &dyn Watcher) -> Entry {
3216 self.reuse_entry_id(&mut entry);
3217 let entry = self.snapshot.insert_entry(entry, fs);
3218 if entry.path.file_name() == Some(&DOT_GIT) {
3219 self.insert_git_repository(entry.path.clone(), fs, watcher);
3220 }
3221
3222 #[cfg(test)]
3223 self.snapshot.check_invariants(false);
3224
3225 entry
3226 }
3227
3228 fn populate_dir(
3229 &mut self,
3230 parent_path: &Arc<Path>,
3231 entries: impl IntoIterator<Item = Entry>,
3232 ignore: Option<Arc<Gitignore>>,
3233 ) {
3234 let mut parent_entry = if let Some(parent_entry) = self
3235 .snapshot
3236 .entries_by_path
3237 .get(&PathKey(parent_path.clone()), &())
3238 {
3239 parent_entry.clone()
3240 } else {
3241 log::warn!(
3242 "populating a directory {:?} that has been removed",
3243 parent_path
3244 );
3245 return;
3246 };
3247
3248 match parent_entry.kind {
3249 EntryKind::PendingDir | EntryKind::UnloadedDir => parent_entry.kind = EntryKind::Dir,
3250 EntryKind::Dir => {}
3251 _ => return,
3252 }
3253
3254 if let Some(ignore) = ignore {
3255 let abs_parent_path = self.snapshot.abs_path.as_path().join(parent_path).into();
3256 self.snapshot
3257 .ignores_by_parent_abs_path
3258 .insert(abs_parent_path, (ignore, false));
3259 }
3260
3261 let parent_entry_id = parent_entry.id;
3262 self.scanned_dirs.insert(parent_entry_id);
3263 let mut entries_by_path_edits = vec![Edit::Insert(parent_entry)];
3264 let mut entries_by_id_edits = Vec::new();
3265
3266 for entry in entries {
3267 entries_by_id_edits.push(Edit::Insert(PathEntry {
3268 id: entry.id,
3269 path: entry.path.clone(),
3270 is_ignored: entry.is_ignored,
3271 scan_id: self.snapshot.scan_id,
3272 }));
3273 entries_by_path_edits.push(Edit::Insert(entry));
3274 }
3275
3276 self.snapshot
3277 .entries_by_path
3278 .edit(entries_by_path_edits, &());
3279 self.snapshot.entries_by_id.edit(entries_by_id_edits, &());
3280
3281 if let Err(ix) = self.changed_paths.binary_search(parent_path) {
3282 self.changed_paths.insert(ix, parent_path.clone());
3283 }
3284
3285 #[cfg(test)]
3286 self.snapshot.check_invariants(false);
3287 }
3288
3289 fn remove_path(&mut self, path: &Path) {
3290 log::info!("background scanner removing path {path:?}");
3291 let mut new_entries;
3292 let removed_entries;
3293 {
3294 let mut cursor = self
3295 .snapshot
3296 .entries_by_path
3297 .cursor::<TraversalProgress>(&());
3298 new_entries = cursor.slice(&TraversalTarget::path(path), Bias::Left, &());
3299 removed_entries = cursor.slice(&TraversalTarget::successor(path), Bias::Left, &());
3300 new_entries.append(cursor.suffix(&()), &());
3301 }
3302 self.snapshot.entries_by_path = new_entries;
3303
3304 let mut removed_ids = Vec::with_capacity(removed_entries.summary().count);
3305 for entry in removed_entries.cursor::<()>(&()) {
3306 match self.removed_entries.entry(entry.inode) {
3307 hash_map::Entry::Occupied(mut e) => {
3308 let prev_removed_entry = e.get_mut();
3309 if entry.id > prev_removed_entry.id {
3310 *prev_removed_entry = entry.clone();
3311 }
3312 }
3313 hash_map::Entry::Vacant(e) => {
3314 e.insert(entry.clone());
3315 }
3316 }
3317
3318 if entry.path.file_name() == Some(&GITIGNORE) {
3319 let abs_parent_path = self
3320 .snapshot
3321 .abs_path
3322 .as_path()
3323 .join(entry.path.parent().unwrap());
3324 if let Some((_, needs_update)) = self
3325 .snapshot
3326 .ignores_by_parent_abs_path
3327 .get_mut(abs_parent_path.as_path())
3328 {
3329 *needs_update = true;
3330 }
3331 }
3332
3333 if let Err(ix) = removed_ids.binary_search(&entry.id) {
3334 removed_ids.insert(ix, entry.id);
3335 }
3336 }
3337
3338 self.snapshot.entries_by_id.edit(
3339 removed_ids.iter().map(|&id| Edit::Remove(id)).collect(),
3340 &(),
3341 );
3342 self.snapshot
3343 .git_repositories
3344 .retain(|id, _| removed_ids.binary_search(id).is_err());
3345 self.snapshot.repositories.retain(&(), |repository| {
3346 removed_ids
3347 .binary_search(&repository.work_directory_id)
3348 .is_err()
3349 });
3350
3351 #[cfg(test)]
3352 self.snapshot.check_invariants(false);
3353 }
3354
3355 fn insert_git_repository(
3356 &mut self,
3357 dot_git_path: Arc<Path>,
3358 fs: &dyn Fs,
3359 watcher: &dyn Watcher,
3360 ) -> Option<LocalRepositoryEntry> {
3361 let work_dir_path: Arc<Path> = match dot_git_path.parent() {
3362 Some(parent_dir) => {
3363 // Guard against repositories inside the repository metadata
3364 if parent_dir.iter().any(|component| component == *DOT_GIT) {
3365 log::info!(
3366 "not building git repository for nested `.git` directory, `.git` path in the worktree: {dot_git_path:?}"
3367 );
3368 return None;
3369 };
3370 log::info!(
3371 "building git repository, `.git` path in the worktree: {dot_git_path:?}"
3372 );
3373
3374 parent_dir.into()
3375 }
3376 None => {
3377 // `dot_git_path.parent().is_none()` means `.git` directory is the opened worktree itself,
3378 // no files inside that directory are tracked by git, so no need to build the repo around it
3379 log::info!(
3380 "not building git repository for the worktree itself, `.git` path in the worktree: {dot_git_path:?}"
3381 );
3382 return None;
3383 }
3384 };
3385
3386 self.insert_git_repository_for_path(
3387 WorkDirectory::InProject {
3388 relative_path: work_dir_path,
3389 },
3390 dot_git_path,
3391 fs,
3392 watcher,
3393 )
3394 }
3395
3396 fn insert_git_repository_for_path(
3397 &mut self,
3398 work_directory: WorkDirectory,
3399 dot_git_path: Arc<Path>,
3400 fs: &dyn Fs,
3401 watcher: &dyn Watcher,
3402 ) -> Option<LocalRepositoryEntry> {
3403 // TODO canonicalize here
3404 log::info!("insert git repository for {dot_git_path:?}");
3405 let work_dir_entry = self.snapshot.entry_for_path(work_directory.path_key().0)?;
3406 let work_directory_abs_path = self
3407 .snapshot
3408 .work_directory_abs_path(&work_directory)
3409 .log_err()?;
3410
3411 if self
3412 .snapshot
3413 .git_repositories
3414 .get(&work_dir_entry.id)
3415 .is_some()
3416 {
3417 log::info!("existing git repository for {work_directory:?}");
3418 return None;
3419 }
3420
3421 let dot_git_abs_path = self.snapshot.abs_path.as_path().join(&dot_git_path);
3422
3423 let t0 = Instant::now();
3424 let repository = fs.open_repo(&dot_git_abs_path)?;
3425 log::info!("opened git repo for {dot_git_abs_path:?}");
3426
3427 let repository_path = repository.path();
3428 watcher.add(&repository_path).log_err()?;
3429
3430 let actual_dot_git_dir_abs_path = repository.main_repository_path();
3431 let dot_git_worktree_abs_path = if actual_dot_git_dir_abs_path == dot_git_abs_path {
3432 None
3433 } else {
3434 // The two paths could be different because we opened a git worktree.
3435 // When that happens:
3436 //
3437 // * `dot_git_abs_path` is a file that points to the worktree-subdirectory in the actual
3438 // .git directory.
3439 //
3440 // * `repository_path` is the worktree-subdirectory.
3441 //
3442 // * `actual_dot_git_dir_abs_path` is the path to the actual .git directory. In git
3443 // documentation this is called the "commondir".
3444 watcher.add(&dot_git_abs_path).log_err()?;
3445 Some(Arc::from(dot_git_abs_path))
3446 };
3447
3448 log::trace!("constructed libgit2 repo in {:?}", t0.elapsed());
3449
3450 if let Some(git_hosting_provider_registry) = self.git_hosting_provider_registry.clone() {
3451 git_hosting_providers::register_additional_providers(
3452 git_hosting_provider_registry,
3453 repository.clone(),
3454 );
3455 }
3456
3457 let work_directory_id = work_dir_entry.id;
3458 self.snapshot.repositories.insert_or_replace(
3459 RepositoryEntry {
3460 work_directory_id,
3461 work_directory_abs_path,
3462 current_branch: None,
3463 statuses_by_path: Default::default(),
3464 current_merge_conflicts: Default::default(),
3465 worktree_scan_id: 0,
3466 },
3467 &(),
3468 );
3469
3470 let local_repository = LocalRepositoryEntry {
3471 work_directory_id,
3472 work_directory,
3473 git_dir_scan_id: 0,
3474 status_scan_id: 0,
3475 repo_ptr: repository.clone(),
3476 dot_git_dir_abs_path: actual_dot_git_dir_abs_path.into(),
3477 dot_git_worktree_abs_path,
3478 current_merge_head_shas: Default::default(),
3479 merge_message: None,
3480 };
3481
3482 self.snapshot
3483 .git_repositories
3484 .insert(work_directory_id, local_repository.clone());
3485
3486 log::info!("inserting new local git repository");
3487 Some(local_repository)
3488 }
3489}
3490
3491async fn is_git_dir(path: &Path, fs: &dyn Fs) -> bool {
3492 if path.file_name() == Some(&*DOT_GIT) {
3493 return true;
3494 }
3495
3496 // If we're in a bare repository, we are not inside a `.git` folder. In a
3497 // bare repository, the root folder contains what would normally be in the
3498 // `.git` folder.
3499 let head_metadata = fs.metadata(&path.join("HEAD")).await;
3500 if !matches!(head_metadata, Ok(Some(_))) {
3501 return false;
3502 }
3503 let config_metadata = fs.metadata(&path.join("config")).await;
3504 matches!(config_metadata, Ok(Some(_)))
3505}
3506
3507async fn build_gitignore(abs_path: &Path, fs: &dyn Fs) -> Result<Gitignore> {
3508 let contents = fs.load(abs_path).await?;
3509 let parent = abs_path.parent().unwrap_or_else(|| Path::new("/"));
3510 let mut builder = GitignoreBuilder::new(parent);
3511 for line in contents.lines() {
3512 builder.add_line(Some(abs_path.into()), line)?;
3513 }
3514 Ok(builder.build()?)
3515}
3516
3517impl Deref for Worktree {
3518 type Target = Snapshot;
3519
3520 fn deref(&self) -> &Self::Target {
3521 match self {
3522 Worktree::Local(worktree) => &worktree.snapshot,
3523 Worktree::Remote(worktree) => &worktree.snapshot,
3524 }
3525 }
3526}
3527
3528impl Deref for LocalWorktree {
3529 type Target = LocalSnapshot;
3530
3531 fn deref(&self) -> &Self::Target {
3532 &self.snapshot
3533 }
3534}
3535
3536impl Deref for RemoteWorktree {
3537 type Target = Snapshot;
3538
3539 fn deref(&self) -> &Self::Target {
3540 &self.snapshot
3541 }
3542}
3543
3544impl fmt::Debug for LocalWorktree {
3545 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3546 self.snapshot.fmt(f)
3547 }
3548}
3549
3550impl fmt::Debug for Snapshot {
3551 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3552 struct EntriesById<'a>(&'a SumTree<PathEntry>);
3553 struct EntriesByPath<'a>(&'a SumTree<Entry>);
3554
3555 impl fmt::Debug for EntriesByPath<'_> {
3556 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3557 f.debug_map()
3558 .entries(self.0.iter().map(|entry| (&entry.path, entry.id)))
3559 .finish()
3560 }
3561 }
3562
3563 impl fmt::Debug for EntriesById<'_> {
3564 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3565 f.debug_list().entries(self.0.iter()).finish()
3566 }
3567 }
3568
3569 f.debug_struct("Snapshot")
3570 .field("id", &self.id)
3571 .field("root_name", &self.root_name)
3572 .field("entries_by_path", &EntriesByPath(&self.entries_by_path))
3573 .field("entries_by_id", &EntriesById(&self.entries_by_id))
3574 .finish()
3575 }
3576}
3577
3578#[derive(Clone, PartialEq)]
3579pub struct File {
3580 pub worktree: Entity<Worktree>,
3581 pub path: Arc<Path>,
3582 pub disk_state: DiskState,
3583 pub entry_id: Option<ProjectEntryId>,
3584 pub is_local: bool,
3585 pub is_private: bool,
3586}
3587
3588impl language::File for File {
3589 fn as_local(&self) -> Option<&dyn language::LocalFile> {
3590 if self.is_local {
3591 Some(self)
3592 } else {
3593 None
3594 }
3595 }
3596
3597 fn disk_state(&self) -> DiskState {
3598 self.disk_state
3599 }
3600
3601 fn path(&self) -> &Arc<Path> {
3602 &self.path
3603 }
3604
3605 fn full_path(&self, cx: &App) -> PathBuf {
3606 let mut full_path = PathBuf::new();
3607 let worktree = self.worktree.read(cx);
3608
3609 if worktree.is_visible() {
3610 full_path.push(worktree.root_name());
3611 } else {
3612 let path = worktree.abs_path();
3613
3614 if worktree.is_local() && path.starts_with(home_dir().as_path()) {
3615 full_path.push("~");
3616 full_path.push(path.strip_prefix(home_dir().as_path()).unwrap());
3617 } else {
3618 full_path.push(path)
3619 }
3620 }
3621
3622 if self.path.components().next().is_some() {
3623 full_path.push(&self.path);
3624 }
3625
3626 full_path
3627 }
3628
3629 /// Returns the last component of this handle's absolute path. If this handle refers to the root
3630 /// of its worktree, then this method will return the name of the worktree itself.
3631 fn file_name<'a>(&'a self, cx: &'a App) -> &'a OsStr {
3632 self.path
3633 .file_name()
3634 .unwrap_or_else(|| OsStr::new(&self.worktree.read(cx).root_name))
3635 }
3636
3637 fn worktree_id(&self, cx: &App) -> WorktreeId {
3638 self.worktree.read(cx).id()
3639 }
3640
3641 fn as_any(&self) -> &dyn Any {
3642 self
3643 }
3644
3645 fn to_proto(&self, cx: &App) -> rpc::proto::File {
3646 rpc::proto::File {
3647 worktree_id: self.worktree.read(cx).id().to_proto(),
3648 entry_id: self.entry_id.map(|id| id.to_proto()),
3649 path: self.path.as_ref().to_proto(),
3650 mtime: self.disk_state.mtime().map(|time| time.into()),
3651 is_deleted: self.disk_state == DiskState::Deleted,
3652 }
3653 }
3654
3655 fn is_private(&self) -> bool {
3656 self.is_private
3657 }
3658}
3659
3660impl language::LocalFile for File {
3661 fn abs_path(&self, cx: &App) -> PathBuf {
3662 let worktree_path = &self.worktree.read(cx).as_local().unwrap().abs_path;
3663 if self.path.as_ref() == Path::new("") {
3664 worktree_path.as_path().to_path_buf()
3665 } else {
3666 worktree_path.as_path().join(&self.path)
3667 }
3668 }
3669
3670 fn load(&self, cx: &App) -> Task<Result<String>> {
3671 let worktree = self.worktree.read(cx).as_local().unwrap();
3672 let abs_path = worktree.absolutize(&self.path);
3673 let fs = worktree.fs.clone();
3674 cx.background_spawn(async move { fs.load(&abs_path?).await })
3675 }
3676
3677 fn load_bytes(&self, cx: &App) -> Task<Result<Vec<u8>>> {
3678 let worktree = self.worktree.read(cx).as_local().unwrap();
3679 let abs_path = worktree.absolutize(&self.path);
3680 let fs = worktree.fs.clone();
3681 cx.background_spawn(async move { fs.load_bytes(&abs_path?).await })
3682 }
3683}
3684
3685impl File {
3686 pub fn for_entry(entry: Entry, worktree: Entity<Worktree>) -> Arc<Self> {
3687 Arc::new(Self {
3688 worktree,
3689 path: entry.path.clone(),
3690 disk_state: if let Some(mtime) = entry.mtime {
3691 DiskState::Present { mtime }
3692 } else {
3693 DiskState::New
3694 },
3695 entry_id: Some(entry.id),
3696 is_local: true,
3697 is_private: entry.is_private,
3698 })
3699 }
3700
3701 pub fn from_proto(
3702 proto: rpc::proto::File,
3703 worktree: Entity<Worktree>,
3704 cx: &App,
3705 ) -> Result<Self> {
3706 let worktree_id = worktree
3707 .read(cx)
3708 .as_remote()
3709 .ok_or_else(|| anyhow!("not remote"))?
3710 .id();
3711
3712 if worktree_id.to_proto() != proto.worktree_id {
3713 return Err(anyhow!("worktree id does not match file"));
3714 }
3715
3716 let disk_state = if proto.is_deleted {
3717 DiskState::Deleted
3718 } else {
3719 if let Some(mtime) = proto.mtime.map(&Into::into) {
3720 DiskState::Present { mtime }
3721 } else {
3722 DiskState::New
3723 }
3724 };
3725
3726 Ok(Self {
3727 worktree,
3728 path: Arc::<Path>::from_proto(proto.path),
3729 disk_state,
3730 entry_id: proto.entry_id.map(ProjectEntryId::from_proto),
3731 is_local: false,
3732 is_private: false,
3733 })
3734 }
3735
3736 pub fn from_dyn(file: Option<&Arc<dyn language::File>>) -> Option<&Self> {
3737 file.and_then(|f| f.as_any().downcast_ref())
3738 }
3739
3740 pub fn worktree_id(&self, cx: &App) -> WorktreeId {
3741 self.worktree.read(cx).id()
3742 }
3743
3744 pub fn project_entry_id(&self, _: &App) -> Option<ProjectEntryId> {
3745 match self.disk_state {
3746 DiskState::Deleted => None,
3747 _ => self.entry_id,
3748 }
3749 }
3750}
3751
3752#[derive(Clone, Debug, PartialEq, Eq)]
3753pub struct Entry {
3754 pub id: ProjectEntryId,
3755 pub kind: EntryKind,
3756 pub path: Arc<Path>,
3757 pub inode: u64,
3758 pub mtime: Option<MTime>,
3759
3760 pub canonical_path: Option<Arc<Path>>,
3761 /// Whether this entry is ignored by Git.
3762 ///
3763 /// We only scan ignored entries once the directory is expanded and
3764 /// exclude them from searches.
3765 pub is_ignored: bool,
3766
3767 /// Whether this entry is always included in searches.
3768 ///
3769 /// This is used for entries that are always included in searches, even
3770 /// if they are ignored by git. Overridden by file_scan_exclusions.
3771 pub is_always_included: bool,
3772
3773 /// Whether this entry's canonical path is outside of the worktree.
3774 /// This means the entry is only accessible from the worktree root via a
3775 /// symlink.
3776 ///
3777 /// We only scan entries outside of the worktree once the symlinked
3778 /// directory is expanded. External entries are treated like gitignored
3779 /// entries in that they are not included in searches.
3780 pub is_external: bool,
3781
3782 /// Whether this entry is considered to be a `.env` file.
3783 pub is_private: bool,
3784 /// The entry's size on disk, in bytes.
3785 pub size: u64,
3786 pub char_bag: CharBag,
3787 pub is_fifo: bool,
3788}
3789
3790#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3791pub enum EntryKind {
3792 UnloadedDir,
3793 PendingDir,
3794 Dir,
3795 File,
3796}
3797
3798#[derive(Clone, Copy, Debug, PartialEq)]
3799pub enum PathChange {
3800 /// A filesystem entry was was created.
3801 Added,
3802 /// A filesystem entry was removed.
3803 Removed,
3804 /// A filesystem entry was updated.
3805 Updated,
3806 /// A filesystem entry was either updated or added. We don't know
3807 /// whether or not it already existed, because the path had not
3808 /// been loaded before the event.
3809 AddedOrUpdated,
3810 /// A filesystem entry was found during the initial scan of the worktree.
3811 Loaded,
3812}
3813
3814#[derive(Debug)]
3815pub struct GitRepositoryChange {
3816 /// The previous state of the repository, if it already existed.
3817 pub old_repository: Option<RepositoryEntry>,
3818}
3819
3820pub type UpdatedEntriesSet = Arc<[(Arc<Path>, ProjectEntryId, PathChange)]>;
3821pub type UpdatedGitRepositoriesSet = Arc<[(Entry, GitRepositoryChange)]>;
3822
3823#[derive(Clone, Debug, PartialEq, Eq)]
3824pub struct StatusEntry {
3825 pub repo_path: RepoPath,
3826 pub status: FileStatus,
3827}
3828
3829impl StatusEntry {
3830 fn to_proto(&self) -> proto::StatusEntry {
3831 let simple_status = match self.status {
3832 FileStatus::Ignored | FileStatus::Untracked => proto::GitStatus::Added as i32,
3833 FileStatus::Unmerged { .. } => proto::GitStatus::Conflict as i32,
3834 FileStatus::Tracked(TrackedStatus {
3835 index_status,
3836 worktree_status,
3837 }) => tracked_status_to_proto(if worktree_status != StatusCode::Unmodified {
3838 worktree_status
3839 } else {
3840 index_status
3841 }),
3842 };
3843
3844 proto::StatusEntry {
3845 repo_path: self.repo_path.as_ref().to_proto(),
3846 simple_status,
3847 status: Some(status_to_proto(self.status)),
3848 }
3849 }
3850}
3851
3852impl TryFrom<proto::StatusEntry> for StatusEntry {
3853 type Error = anyhow::Error;
3854
3855 fn try_from(value: proto::StatusEntry) -> Result<Self, Self::Error> {
3856 let repo_path = RepoPath(Arc::<Path>::from_proto(value.repo_path));
3857 let status = status_from_proto(value.simple_status, value.status)?;
3858 Ok(Self { repo_path, status })
3859 }
3860}
3861
3862#[derive(Clone, Debug)]
3863pub struct PathProgress<'a> {
3864 pub max_path: &'a Path,
3865}
3866
3867#[derive(Clone, Debug)]
3868pub struct PathSummary<S> {
3869 max_path: Arc<Path>,
3870 item_summary: S,
3871}
3872
3873impl<S: Summary> Summary for PathSummary<S> {
3874 type Context = S::Context;
3875
3876 fn zero(cx: &Self::Context) -> Self {
3877 Self {
3878 max_path: Path::new("").into(),
3879 item_summary: S::zero(cx),
3880 }
3881 }
3882
3883 fn add_summary(&mut self, rhs: &Self, cx: &Self::Context) {
3884 self.max_path = rhs.max_path.clone();
3885 self.item_summary.add_summary(&rhs.item_summary, cx);
3886 }
3887}
3888
3889impl<'a, S: Summary> sum_tree::Dimension<'a, PathSummary<S>> for PathProgress<'a> {
3890 fn zero(_: &<PathSummary<S> as Summary>::Context) -> Self {
3891 Self {
3892 max_path: Path::new(""),
3893 }
3894 }
3895
3896 fn add_summary(
3897 &mut self,
3898 summary: &'a PathSummary<S>,
3899 _: &<PathSummary<S> as Summary>::Context,
3900 ) {
3901 self.max_path = summary.max_path.as_ref()
3902 }
3903}
3904
3905#[derive(Clone, Debug)]
3906pub struct AbsPathSummary {
3907 max_path: Arc<Path>,
3908}
3909
3910impl Summary for AbsPathSummary {
3911 type Context = ();
3912
3913 fn zero(_: &Self::Context) -> Self {
3914 Self {
3915 max_path: Path::new("").into(),
3916 }
3917 }
3918
3919 fn add_summary(&mut self, rhs: &Self, _: &Self::Context) {
3920 self.max_path = rhs.max_path.clone();
3921 }
3922}
3923
3924impl sum_tree::Item for RepositoryEntry {
3925 type Summary = AbsPathSummary;
3926
3927 fn summary(&self, _: &<Self::Summary as Summary>::Context) -> Self::Summary {
3928 AbsPathSummary {
3929 max_path: self.work_directory_abs_path.as_path().into(),
3930 }
3931 }
3932}
3933
3934#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
3935pub struct AbsPathKey(pub Arc<Path>);
3936
3937impl<'a> sum_tree::Dimension<'a, AbsPathSummary> for AbsPathKey {
3938 fn zero(_: &()) -> Self {
3939 Self(Path::new("").into())
3940 }
3941
3942 fn add_summary(&mut self, summary: &'a AbsPathSummary, _: &()) {
3943 self.0 = summary.max_path.clone();
3944 }
3945}
3946
3947impl sum_tree::KeyedItem for RepositoryEntry {
3948 type Key = AbsPathKey;
3949
3950 fn key(&self) -> Self::Key {
3951 AbsPathKey(self.work_directory_abs_path.as_path().into())
3952 }
3953}
3954
3955impl sum_tree::Item for StatusEntry {
3956 type Summary = PathSummary<GitSummary>;
3957
3958 fn summary(&self, _: &<Self::Summary as Summary>::Context) -> Self::Summary {
3959 PathSummary {
3960 max_path: self.repo_path.0.clone(),
3961 item_summary: self.status.summary(),
3962 }
3963 }
3964}
3965
3966impl sum_tree::KeyedItem for StatusEntry {
3967 type Key = PathKey;
3968
3969 fn key(&self) -> Self::Key {
3970 PathKey(self.repo_path.0.clone())
3971 }
3972}
3973
3974impl<'a> sum_tree::Dimension<'a, PathSummary<GitSummary>> for GitSummary {
3975 fn zero(_cx: &()) -> Self {
3976 Default::default()
3977 }
3978
3979 fn add_summary(&mut self, summary: &'a PathSummary<GitSummary>, _: &()) {
3980 *self += summary.item_summary
3981 }
3982}
3983
3984impl<'a, S: Summary> sum_tree::Dimension<'a, PathSummary<S>> for PathKey {
3985 fn zero(_: &S::Context) -> Self {
3986 Default::default()
3987 }
3988
3989 fn add_summary(&mut self, summary: &'a PathSummary<S>, _: &S::Context) {
3990 self.0 = summary.max_path.clone();
3991 }
3992}
3993
3994impl<'a, S: Summary> sum_tree::Dimension<'a, PathSummary<S>> for TraversalProgress<'a> {
3995 fn zero(_cx: &S::Context) -> Self {
3996 Default::default()
3997 }
3998
3999 fn add_summary(&mut self, summary: &'a PathSummary<S>, _: &S::Context) {
4000 self.max_path = summary.max_path.as_ref();
4001 }
4002}
4003
4004impl Entry {
4005 fn new(
4006 path: Arc<Path>,
4007 metadata: &fs::Metadata,
4008 next_entry_id: &AtomicUsize,
4009 root_char_bag: CharBag,
4010 canonical_path: Option<Arc<Path>>,
4011 ) -> Self {
4012 let char_bag = char_bag_for_path(root_char_bag, &path);
4013 Self {
4014 id: ProjectEntryId::new(next_entry_id),
4015 kind: if metadata.is_dir {
4016 EntryKind::PendingDir
4017 } else {
4018 EntryKind::File
4019 },
4020 path,
4021 inode: metadata.inode,
4022 mtime: Some(metadata.mtime),
4023 size: metadata.len,
4024 canonical_path,
4025 is_ignored: false,
4026 is_always_included: false,
4027 is_external: false,
4028 is_private: false,
4029 char_bag,
4030 is_fifo: metadata.is_fifo,
4031 }
4032 }
4033
4034 pub fn is_created(&self) -> bool {
4035 self.mtime.is_some()
4036 }
4037
4038 pub fn is_dir(&self) -> bool {
4039 self.kind.is_dir()
4040 }
4041
4042 pub fn is_file(&self) -> bool {
4043 self.kind.is_file()
4044 }
4045}
4046
4047impl EntryKind {
4048 pub fn is_dir(&self) -> bool {
4049 matches!(
4050 self,
4051 EntryKind::Dir | EntryKind::PendingDir | EntryKind::UnloadedDir
4052 )
4053 }
4054
4055 pub fn is_unloaded(&self) -> bool {
4056 matches!(self, EntryKind::UnloadedDir)
4057 }
4058
4059 pub fn is_file(&self) -> bool {
4060 matches!(self, EntryKind::File)
4061 }
4062}
4063
4064impl sum_tree::Item for Entry {
4065 type Summary = EntrySummary;
4066
4067 fn summary(&self, _cx: &()) -> Self::Summary {
4068 let non_ignored_count = if (self.is_ignored || self.is_external) && !self.is_always_included
4069 {
4070 0
4071 } else {
4072 1
4073 };
4074 let file_count;
4075 let non_ignored_file_count;
4076 if self.is_file() {
4077 file_count = 1;
4078 non_ignored_file_count = non_ignored_count;
4079 } else {
4080 file_count = 0;
4081 non_ignored_file_count = 0;
4082 }
4083
4084 EntrySummary {
4085 max_path: self.path.clone(),
4086 count: 1,
4087 non_ignored_count,
4088 file_count,
4089 non_ignored_file_count,
4090 }
4091 }
4092}
4093
4094impl sum_tree::KeyedItem for Entry {
4095 type Key = PathKey;
4096
4097 fn key(&self) -> Self::Key {
4098 PathKey(self.path.clone())
4099 }
4100}
4101
4102#[derive(Clone, Debug)]
4103pub struct EntrySummary {
4104 max_path: Arc<Path>,
4105 count: usize,
4106 non_ignored_count: usize,
4107 file_count: usize,
4108 non_ignored_file_count: usize,
4109}
4110
4111impl Default for EntrySummary {
4112 fn default() -> Self {
4113 Self {
4114 max_path: Arc::from(Path::new("")),
4115 count: 0,
4116 non_ignored_count: 0,
4117 file_count: 0,
4118 non_ignored_file_count: 0,
4119 }
4120 }
4121}
4122
4123impl sum_tree::Summary for EntrySummary {
4124 type Context = ();
4125
4126 fn zero(_cx: &()) -> Self {
4127 Default::default()
4128 }
4129
4130 fn add_summary(&mut self, rhs: &Self, _: &()) {
4131 self.max_path = rhs.max_path.clone();
4132 self.count += rhs.count;
4133 self.non_ignored_count += rhs.non_ignored_count;
4134 self.file_count += rhs.file_count;
4135 self.non_ignored_file_count += rhs.non_ignored_file_count;
4136 }
4137}
4138
4139#[derive(Clone, Debug)]
4140struct PathEntry {
4141 id: ProjectEntryId,
4142 path: Arc<Path>,
4143 is_ignored: bool,
4144 scan_id: usize,
4145}
4146
4147impl sum_tree::Item for PathEntry {
4148 type Summary = PathEntrySummary;
4149
4150 fn summary(&self, _cx: &()) -> Self::Summary {
4151 PathEntrySummary { max_id: self.id }
4152 }
4153}
4154
4155impl sum_tree::KeyedItem for PathEntry {
4156 type Key = ProjectEntryId;
4157
4158 fn key(&self) -> Self::Key {
4159 self.id
4160 }
4161}
4162
4163#[derive(Clone, Debug, Default)]
4164struct PathEntrySummary {
4165 max_id: ProjectEntryId,
4166}
4167
4168impl sum_tree::Summary for PathEntrySummary {
4169 type Context = ();
4170
4171 fn zero(_cx: &Self::Context) -> Self {
4172 Default::default()
4173 }
4174
4175 fn add_summary(&mut self, summary: &Self, _: &Self::Context) {
4176 self.max_id = summary.max_id;
4177 }
4178}
4179
4180impl<'a> sum_tree::Dimension<'a, PathEntrySummary> for ProjectEntryId {
4181 fn zero(_cx: &()) -> Self {
4182 Default::default()
4183 }
4184
4185 fn add_summary(&mut self, summary: &'a PathEntrySummary, _: &()) {
4186 *self = summary.max_id;
4187 }
4188}
4189
4190#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
4191pub struct PathKey(pub Arc<Path>);
4192
4193impl Default for PathKey {
4194 fn default() -> Self {
4195 Self(Path::new("").into())
4196 }
4197}
4198
4199impl<'a> sum_tree::Dimension<'a, EntrySummary> for PathKey {
4200 fn zero(_cx: &()) -> Self {
4201 Default::default()
4202 }
4203
4204 fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
4205 self.0 = summary.max_path.clone();
4206 }
4207}
4208
4209struct BackgroundScanner {
4210 state: Arc<Mutex<BackgroundScannerState>>,
4211 fs: Arc<dyn Fs>,
4212 fs_case_sensitive: bool,
4213 status_updates_tx: UnboundedSender<ScanState>,
4214 scans_running: Arc<AtomicI32>,
4215 executor: BackgroundExecutor,
4216 scan_requests_rx: channel::Receiver<ScanRequest>,
4217 path_prefixes_to_scan_rx: channel::Receiver<PathPrefixScanRequest>,
4218 next_entry_id: Arc<AtomicUsize>,
4219 phase: BackgroundScannerPhase,
4220 watcher: Arc<dyn Watcher>,
4221 settings: WorktreeSettings,
4222 share_private_files: bool,
4223}
4224
4225#[derive(Copy, Clone, PartialEq)]
4226enum BackgroundScannerPhase {
4227 InitialScan,
4228 EventsReceivedDuringInitialScan,
4229 Events,
4230}
4231
4232impl BackgroundScanner {
4233 async fn run(&mut self, mut fs_events_rx: Pin<Box<dyn Send + Stream<Item = Vec<PathEvent>>>>) {
4234 // If the worktree root does not contain a git repository, then find
4235 // the git repository in an ancestor directory. Find any gitignore files
4236 // in ancestor directories.
4237 let root_abs_path = self.state.lock().snapshot.abs_path.clone();
4238 let mut containing_git_repository = None;
4239 for (index, ancestor) in root_abs_path.as_path().ancestors().enumerate() {
4240 if index != 0 {
4241 if Some(ancestor) == self.fs.home_dir().as_deref() {
4242 // Unless $HOME is itself the worktree root, don't consider it as a
4243 // containing git repository---expensive and likely unwanted.
4244 break;
4245 } else if let Ok(ignore) =
4246 build_gitignore(&ancestor.join(*GITIGNORE), self.fs.as_ref()).await
4247 {
4248 self.state
4249 .lock()
4250 .snapshot
4251 .ignores_by_parent_abs_path
4252 .insert(ancestor.into(), (ignore.into(), false));
4253 }
4254 }
4255
4256 let ancestor_dot_git = ancestor.join(*DOT_GIT);
4257 log::info!("considering ancestor: {ancestor_dot_git:?}");
4258 // Check whether the directory or file called `.git` exists (in the
4259 // case of worktrees it's a file.)
4260 if self
4261 .fs
4262 .metadata(&ancestor_dot_git)
4263 .await
4264 .is_ok_and(|metadata| metadata.is_some())
4265 {
4266 if index != 0 {
4267 // We canonicalize, since the FS events use the canonicalized path.
4268 if let Some(ancestor_dot_git) =
4269 self.fs.canonicalize(&ancestor_dot_git).await.log_err()
4270 {
4271 let location_in_repo = root_abs_path
4272 .as_path()
4273 .strip_prefix(ancestor)
4274 .unwrap()
4275 .into();
4276 log::info!(
4277 "inserting parent git repo for this worktree: {location_in_repo:?}"
4278 );
4279 // We associate the external git repo with our root folder and
4280 // also mark where in the git repo the root folder is located.
4281 let local_repository = self.state.lock().insert_git_repository_for_path(
4282 WorkDirectory::AboveProject {
4283 absolute_path: ancestor.into(),
4284 location_in_repo,
4285 },
4286 ancestor_dot_git.clone().into(),
4287 self.fs.as_ref(),
4288 self.watcher.as_ref(),
4289 );
4290
4291 if local_repository.is_some() {
4292 containing_git_repository = Some(ancestor_dot_git)
4293 }
4294 };
4295 }
4296
4297 // Reached root of git repository.
4298 break;
4299 }
4300 }
4301
4302 log::info!("containing git repository: {containing_git_repository:?}");
4303
4304 let (scan_job_tx, scan_job_rx) = channel::unbounded();
4305 {
4306 let mut state = self.state.lock();
4307 state.snapshot.scan_id += 1;
4308 if let Some(mut root_entry) = state.snapshot.root_entry().cloned() {
4309 let ignore_stack = state
4310 .snapshot
4311 .ignore_stack_for_abs_path(root_abs_path.as_path(), true);
4312 if ignore_stack.is_abs_path_ignored(root_abs_path.as_path(), true) {
4313 root_entry.is_ignored = true;
4314 state.insert_entry(root_entry.clone(), self.fs.as_ref(), self.watcher.as_ref());
4315 }
4316 state.enqueue_scan_dir(root_abs_path.into(), &root_entry, &scan_job_tx);
4317 }
4318 };
4319
4320 // Perform an initial scan of the directory.
4321 drop(scan_job_tx);
4322 self.scan_dirs(true, scan_job_rx).await;
4323 {
4324 let mut state = self.state.lock();
4325 state.snapshot.completed_scan_id = state.snapshot.scan_id;
4326 }
4327
4328 let scanning = self.scans_running.load(atomic::Ordering::Acquire) > 0;
4329 self.send_status_update(scanning, SmallVec::new());
4330
4331 // Process any any FS events that occurred while performing the initial scan.
4332 // For these events, update events cannot be as precise, because we didn't
4333 // have the previous state loaded yet.
4334 self.phase = BackgroundScannerPhase::EventsReceivedDuringInitialScan;
4335 if let Poll::Ready(Some(mut paths)) = futures::poll!(fs_events_rx.next()) {
4336 while let Poll::Ready(Some(more_paths)) = futures::poll!(fs_events_rx.next()) {
4337 paths.extend(more_paths);
4338 }
4339 self.process_events(paths.into_iter().map(Into::into).collect())
4340 .await;
4341 }
4342 if let Some(abs_path) = containing_git_repository {
4343 self.process_events(vec![abs_path]).await;
4344 }
4345
4346 // Continue processing events until the worktree is dropped.
4347 self.phase = BackgroundScannerPhase::Events;
4348
4349 loop {
4350 select_biased! {
4351 // Process any path refresh requests from the worktree. Prioritize
4352 // these before handling changes reported by the filesystem.
4353 request = self.next_scan_request().fuse() => {
4354 let Ok(request) = request else { break };
4355 let scanning = self.scans_running.load(atomic::Ordering::Acquire) > 0;
4356 if !self.process_scan_request(request, scanning).await {
4357 return;
4358 }
4359 }
4360
4361 path_prefix_request = self.path_prefixes_to_scan_rx.recv().fuse() => {
4362 let Ok(request) = path_prefix_request else { break };
4363 log::trace!("adding path prefix {:?}", request.path);
4364
4365 let did_scan = self.forcibly_load_paths(&[request.path.clone()]).await;
4366 if did_scan {
4367 let abs_path =
4368 {
4369 let mut state = self.state.lock();
4370 state.path_prefixes_to_scan.insert(request.path.clone());
4371 state.snapshot.abs_path.as_path().join(&request.path)
4372 };
4373
4374 if let Some(abs_path) = self.fs.canonicalize(&abs_path).await.log_err() {
4375 self.process_events(vec![abs_path]).await;
4376 }
4377 }
4378 let scanning = self.scans_running.load(atomic::Ordering::Acquire) > 0;
4379 self.send_status_update(scanning, request.done);
4380 }
4381
4382 paths = fs_events_rx.next().fuse() => {
4383 let Some(mut paths) = paths else { break };
4384 while let Poll::Ready(Some(more_paths)) = futures::poll!(fs_events_rx.next()) {
4385 paths.extend(more_paths);
4386 }
4387 self.process_events(paths.into_iter().map(Into::into).collect()).await;
4388 }
4389 }
4390 }
4391 }
4392
4393 async fn process_scan_request(&self, mut request: ScanRequest, scanning: bool) -> bool {
4394 log::debug!("rescanning paths {:?}", request.relative_paths);
4395
4396 request.relative_paths.sort_unstable();
4397 self.forcibly_load_paths(&request.relative_paths).await;
4398
4399 let root_path = self.state.lock().snapshot.abs_path.clone();
4400 let root_canonical_path = match self.fs.canonicalize(root_path.as_path()).await {
4401 Ok(path) => SanitizedPath::from(path),
4402 Err(err) => {
4403 log::error!("failed to canonicalize root path: {}", err);
4404 return true;
4405 }
4406 };
4407 let abs_paths = request
4408 .relative_paths
4409 .iter()
4410 .map(|path| {
4411 if path.file_name().is_some() {
4412 root_canonical_path.as_path().join(path).to_path_buf()
4413 } else {
4414 root_canonical_path.as_path().to_path_buf()
4415 }
4416 })
4417 .collect::<Vec<_>>();
4418
4419 {
4420 let mut state = self.state.lock();
4421 let is_idle = state.snapshot.completed_scan_id == state.snapshot.scan_id;
4422 state.snapshot.scan_id += 1;
4423 if is_idle {
4424 state.snapshot.completed_scan_id = state.snapshot.scan_id;
4425 }
4426 }
4427
4428 self.reload_entries_for_paths(
4429 root_path,
4430 root_canonical_path,
4431 &request.relative_paths,
4432 abs_paths,
4433 None,
4434 )
4435 .await;
4436
4437 self.send_status_update(scanning, request.done)
4438 }
4439
4440 async fn process_events(&self, mut abs_paths: Vec<PathBuf>) {
4441 let root_path = self.state.lock().snapshot.abs_path.clone();
4442 let root_canonical_path = match self.fs.canonicalize(root_path.as_path()).await {
4443 Ok(path) => SanitizedPath::from(path),
4444 Err(err) => {
4445 let new_path = self
4446 .state
4447 .lock()
4448 .snapshot
4449 .root_file_handle
4450 .clone()
4451 .and_then(|handle| handle.current_path(&self.fs).log_err())
4452 .map(SanitizedPath::from)
4453 .filter(|new_path| *new_path != root_path);
4454
4455 if let Some(new_path) = new_path.as_ref() {
4456 log::info!(
4457 "root renamed from {} to {}",
4458 root_path.as_path().display(),
4459 new_path.as_path().display()
4460 )
4461 } else {
4462 log::warn!("root path could not be canonicalized: {}", err);
4463 }
4464 self.status_updates_tx
4465 .unbounded_send(ScanState::RootUpdated { new_path })
4466 .ok();
4467 return;
4468 }
4469 };
4470
4471 // Certain directories may have FS changes, but do not lead to git data changes that Zed cares about.
4472 // Ignore these, to avoid Zed unnecessarily rescanning git metadata.
4473 let skipped_files_in_dot_git = HashSet::from_iter([*COMMIT_MESSAGE, *INDEX_LOCK]);
4474 let skipped_dirs_in_dot_git = [*FSMONITOR_DAEMON, *LFS_DIR];
4475
4476 let mut relative_paths = Vec::with_capacity(abs_paths.len());
4477 let mut dot_git_abs_paths = Vec::new();
4478 abs_paths.sort_unstable();
4479 abs_paths.dedup_by(|a, b| a.starts_with(b));
4480 abs_paths.retain(|abs_path| {
4481 let abs_path = SanitizedPath::from(abs_path);
4482
4483 let snapshot = &self.state.lock().snapshot;
4484 {
4485 let mut is_git_related = false;
4486
4487 let dot_git_paths = abs_path.as_path().ancestors().find_map(|ancestor| {
4488 if smol::block_on(is_git_dir(ancestor, self.fs.as_ref())) {
4489 let path_in_git_dir = abs_path.as_path().strip_prefix(ancestor).expect("stripping off the ancestor");
4490 Some((ancestor.to_owned(), path_in_git_dir.to_owned()))
4491 } else {
4492 None
4493 }
4494 });
4495
4496 if let Some((dot_git_abs_path, path_in_git_dir)) = dot_git_paths {
4497 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)) {
4498 log::debug!("ignoring event {abs_path:?} as it's in the .git directory among skipped files or directories");
4499 return false;
4500 }
4501
4502 is_git_related = true;
4503 if !dot_git_abs_paths.contains(&dot_git_abs_path) {
4504 dot_git_abs_paths.push(dot_git_abs_path);
4505 }
4506 }
4507
4508 let relative_path: Arc<Path> =
4509 if let Ok(path) = abs_path.strip_prefix(&root_canonical_path) {
4510 path.into()
4511 } else {
4512 if is_git_related {
4513 log::debug!(
4514 "ignoring event {abs_path:?}, since it's in git dir outside of root path {root_canonical_path:?}",
4515 );
4516 } else {
4517 log::error!(
4518 "ignoring event {abs_path:?} outside of root path {root_canonical_path:?}",
4519 );
4520 }
4521 return false;
4522 };
4523
4524 if abs_path.0.file_name() == Some(*GITIGNORE) {
4525 for (_, repo) in snapshot.git_repositories.iter().filter(|(_, repo)| repo.directory_contains(&relative_path)) {
4526 if !dot_git_abs_paths.iter().any(|dot_git_abs_path| dot_git_abs_path == repo.dot_git_dir_abs_path.as_ref()) {
4527 dot_git_abs_paths.push(repo.dot_git_dir_abs_path.to_path_buf());
4528 }
4529 }
4530 }
4531
4532 let parent_dir_is_loaded = relative_path.parent().map_or(true, |parent| {
4533 snapshot
4534 .entry_for_path(parent)
4535 .map_or(false, |entry| entry.kind == EntryKind::Dir)
4536 });
4537 if !parent_dir_is_loaded {
4538 log::debug!("ignoring event {relative_path:?} within unloaded directory");
4539 return false;
4540 }
4541
4542 if self.settings.is_path_excluded(&relative_path) {
4543 if !is_git_related {
4544 log::debug!("ignoring FS event for excluded path {relative_path:?}");
4545 }
4546 return false;
4547 }
4548
4549 relative_paths.push(relative_path);
4550 true
4551 }
4552 });
4553
4554 if relative_paths.is_empty() && dot_git_abs_paths.is_empty() {
4555 return;
4556 }
4557
4558 self.state.lock().snapshot.scan_id += 1;
4559
4560 let (scan_job_tx, scan_job_rx) = channel::unbounded();
4561 log::debug!("received fs events {:?}", relative_paths);
4562 self.reload_entries_for_paths(
4563 root_path,
4564 root_canonical_path,
4565 &relative_paths,
4566 abs_paths,
4567 Some(scan_job_tx.clone()),
4568 )
4569 .await;
4570
4571 self.update_ignore_statuses(scan_job_tx).await;
4572 self.scan_dirs(false, scan_job_rx).await;
4573
4574 let status_update = if !dot_git_abs_paths.is_empty() {
4575 Some(self.update_git_repositories(dot_git_abs_paths))
4576 } else {
4577 None
4578 };
4579
4580 let phase = self.phase;
4581 let status_update_tx = self.status_updates_tx.clone();
4582 let state = self.state.clone();
4583 let scans_running = self.scans_running.clone();
4584 self.executor
4585 .spawn(async move {
4586 if let Some(status_update) = status_update {
4587 status_update.await;
4588 }
4589
4590 {
4591 let mut state = state.lock();
4592 state.snapshot.completed_scan_id = state.snapshot.scan_id;
4593 for (_, entry) in mem::take(&mut state.removed_entries) {
4594 state.scanned_dirs.remove(&entry.id);
4595 }
4596 #[cfg(test)]
4597 state.snapshot.check_git_invariants();
4598 }
4599 let scanning = scans_running.load(atomic::Ordering::Acquire) > 0;
4600 send_status_update_inner(phase, state, status_update_tx, scanning, SmallVec::new());
4601 })
4602 .detach();
4603 }
4604
4605 async fn forcibly_load_paths(&self, paths: &[Arc<Path>]) -> bool {
4606 let (scan_job_tx, scan_job_rx) = channel::unbounded();
4607 {
4608 let mut state = self.state.lock();
4609 let root_path = state.snapshot.abs_path.clone();
4610 for path in paths {
4611 for ancestor in path.ancestors() {
4612 if let Some(entry) = state.snapshot.entry_for_path(ancestor) {
4613 if entry.kind == EntryKind::UnloadedDir {
4614 let abs_path = root_path.as_path().join(ancestor);
4615 state.enqueue_scan_dir(abs_path.into(), entry, &scan_job_tx);
4616 state.paths_to_scan.insert(path.clone());
4617 break;
4618 }
4619 }
4620 }
4621 }
4622 drop(scan_job_tx);
4623 }
4624 while let Ok(job) = scan_job_rx.recv().await {
4625 self.scan_dir(&job).await.log_err();
4626 }
4627
4628 !mem::take(&mut self.state.lock().paths_to_scan).is_empty()
4629 }
4630
4631 async fn scan_dirs(
4632 &self,
4633 enable_progress_updates: bool,
4634 scan_jobs_rx: channel::Receiver<ScanJob>,
4635 ) {
4636 if self
4637 .status_updates_tx
4638 .unbounded_send(ScanState::Started)
4639 .is_err()
4640 {
4641 return;
4642 }
4643
4644 inc_scans_running(&self.scans_running);
4645 let progress_update_count = AtomicUsize::new(0);
4646 self.executor
4647 .scoped(|scope| {
4648 for _ in 0..self.executor.num_cpus() {
4649 scope.spawn(async {
4650 let mut last_progress_update_count = 0;
4651 let progress_update_timer = self.progress_timer(enable_progress_updates).fuse();
4652 futures::pin_mut!(progress_update_timer);
4653
4654 loop {
4655 select_biased! {
4656 // Process any path refresh requests before moving on to process
4657 // the scan queue, so that user operations are prioritized.
4658 request = self.next_scan_request().fuse() => {
4659 let Ok(request) = request else { break };
4660 if !self.process_scan_request(request, true).await {
4661 return;
4662 }
4663 }
4664
4665 // Send periodic progress updates to the worktree. Use an atomic counter
4666 // to ensure that only one of the workers sends a progress update after
4667 // the update interval elapses.
4668 _ = progress_update_timer => {
4669 match progress_update_count.compare_exchange(
4670 last_progress_update_count,
4671 last_progress_update_count + 1,
4672 SeqCst,
4673 SeqCst
4674 ) {
4675 Ok(_) => {
4676 last_progress_update_count += 1;
4677 self.send_status_update(true, SmallVec::new());
4678 }
4679 Err(count) => {
4680 last_progress_update_count = count;
4681 }
4682 }
4683 progress_update_timer.set(self.progress_timer(enable_progress_updates).fuse());
4684 }
4685
4686 // Recursively load directories from the file system.
4687 job = scan_jobs_rx.recv().fuse() => {
4688 let Ok(job) = job else { break };
4689 if let Err(err) = self.scan_dir(&job).await {
4690 if job.path.as_ref() != Path::new("") {
4691 log::error!("error scanning directory {:?}: {}", job.abs_path, err);
4692 }
4693 }
4694 }
4695 }
4696 }
4697 });
4698 }
4699 })
4700 .await;
4701
4702 dec_scans_running(&self.scans_running, 1);
4703 }
4704
4705 fn send_status_update(&self, scanning: bool, barrier: SmallVec<[barrier::Sender; 1]>) -> bool {
4706 send_status_update_inner(
4707 self.phase,
4708 self.state.clone(),
4709 self.status_updates_tx.clone(),
4710 scanning,
4711 barrier,
4712 )
4713 }
4714
4715 async fn scan_dir(&self, job: &ScanJob) -> Result<()> {
4716 let root_abs_path;
4717 let root_char_bag;
4718 {
4719 let snapshot = &self.state.lock().snapshot;
4720 if self.settings.is_path_excluded(&job.path) {
4721 log::error!("skipping excluded directory {:?}", job.path);
4722 return Ok(());
4723 }
4724 log::info!("scanning directory {:?}", job.path);
4725 root_abs_path = snapshot.abs_path().clone();
4726 root_char_bag = snapshot.root_char_bag;
4727 }
4728
4729 let next_entry_id = self.next_entry_id.clone();
4730 let mut ignore_stack = job.ignore_stack.clone();
4731 let mut new_ignore = None;
4732 let mut root_canonical_path = None;
4733 let mut new_entries: Vec<Entry> = Vec::new();
4734 let mut new_jobs: Vec<Option<ScanJob>> = Vec::new();
4735 let mut child_paths = self
4736 .fs
4737 .read_dir(&job.abs_path)
4738 .await?
4739 .filter_map(|entry| async {
4740 match entry {
4741 Ok(entry) => Some(entry),
4742 Err(error) => {
4743 log::error!("error processing entry {:?}", error);
4744 None
4745 }
4746 }
4747 })
4748 .collect::<Vec<_>>()
4749 .await;
4750
4751 // Ensure that .git and .gitignore are processed first.
4752 swap_to_front(&mut child_paths, *GITIGNORE);
4753 swap_to_front(&mut child_paths, *DOT_GIT);
4754
4755 let mut git_status_update_jobs = Vec::new();
4756 for child_abs_path in child_paths {
4757 let child_abs_path: Arc<Path> = child_abs_path.into();
4758 let child_name = child_abs_path.file_name().unwrap();
4759 let child_path: Arc<Path> = job.path.join(child_name).into();
4760
4761 if child_name == *DOT_GIT {
4762 {
4763 let mut state = self.state.lock();
4764 let repo = state.insert_git_repository(
4765 child_path.clone(),
4766 self.fs.as_ref(),
4767 self.watcher.as_ref(),
4768 );
4769 if let Some(local_repo) = repo {
4770 inc_scans_running(&self.scans_running);
4771 git_status_update_jobs
4772 .push(self.schedule_git_statuses_update(&mut state, local_repo));
4773 }
4774 }
4775 } else if child_name == *GITIGNORE {
4776 match build_gitignore(&child_abs_path, self.fs.as_ref()).await {
4777 Ok(ignore) => {
4778 let ignore = Arc::new(ignore);
4779 ignore_stack = ignore_stack.append(job.abs_path.clone(), ignore.clone());
4780 new_ignore = Some(ignore);
4781 }
4782 Err(error) => {
4783 log::error!(
4784 "error loading .gitignore file {:?} - {:?}",
4785 child_name,
4786 error
4787 );
4788 }
4789 }
4790 }
4791
4792 if self.settings.is_path_excluded(&child_path) {
4793 log::debug!("skipping excluded child entry {child_path:?}");
4794 self.state.lock().remove_path(&child_path);
4795 continue;
4796 }
4797
4798 let child_metadata = match self.fs.metadata(&child_abs_path).await {
4799 Ok(Some(metadata)) => metadata,
4800 Ok(None) => continue,
4801 Err(err) => {
4802 log::error!("error processing {child_abs_path:?}: {err:?}");
4803 continue;
4804 }
4805 };
4806
4807 let mut child_entry = Entry::new(
4808 child_path.clone(),
4809 &child_metadata,
4810 &next_entry_id,
4811 root_char_bag,
4812 None,
4813 );
4814
4815 if job.is_external {
4816 child_entry.is_external = true;
4817 } else if child_metadata.is_symlink {
4818 let canonical_path = match self.fs.canonicalize(&child_abs_path).await {
4819 Ok(path) => path,
4820 Err(err) => {
4821 log::error!(
4822 "error reading target of symlink {:?}: {:?}",
4823 child_abs_path,
4824 err
4825 );
4826 continue;
4827 }
4828 };
4829
4830 // lazily canonicalize the root path in order to determine if
4831 // symlinks point outside of the worktree.
4832 let root_canonical_path = match &root_canonical_path {
4833 Some(path) => path,
4834 None => match self.fs.canonicalize(&root_abs_path).await {
4835 Ok(path) => root_canonical_path.insert(path),
4836 Err(err) => {
4837 log::error!("error canonicalizing root {:?}: {:?}", root_abs_path, err);
4838 continue;
4839 }
4840 },
4841 };
4842
4843 if !canonical_path.starts_with(root_canonical_path) {
4844 child_entry.is_external = true;
4845 }
4846
4847 child_entry.canonical_path = Some(canonical_path.into());
4848 }
4849
4850 if child_entry.is_dir() {
4851 child_entry.is_ignored = ignore_stack.is_abs_path_ignored(&child_abs_path, true);
4852 child_entry.is_always_included = self.settings.is_path_always_included(&child_path);
4853
4854 // Avoid recursing until crash in the case of a recursive symlink
4855 if job.ancestor_inodes.contains(&child_entry.inode) {
4856 new_jobs.push(None);
4857 } else {
4858 let mut ancestor_inodes = job.ancestor_inodes.clone();
4859 ancestor_inodes.insert(child_entry.inode);
4860
4861 new_jobs.push(Some(ScanJob {
4862 abs_path: child_abs_path.clone(),
4863 path: child_path,
4864 is_external: child_entry.is_external,
4865 ignore_stack: if child_entry.is_ignored {
4866 IgnoreStack::all()
4867 } else {
4868 ignore_stack.clone()
4869 },
4870 ancestor_inodes,
4871 scan_queue: job.scan_queue.clone(),
4872 }));
4873 }
4874 } else {
4875 child_entry.is_ignored = ignore_stack.is_abs_path_ignored(&child_abs_path, false);
4876 child_entry.is_always_included = self.settings.is_path_always_included(&child_path);
4877 }
4878
4879 {
4880 let relative_path = job.path.join(child_name);
4881 if self.is_path_private(&relative_path) {
4882 log::debug!("detected private file: {relative_path:?}");
4883 child_entry.is_private = true;
4884 }
4885 }
4886
4887 new_entries.push(child_entry);
4888 }
4889
4890 let task_state = self.state.clone();
4891 let phase = self.phase;
4892 let status_updates_tx = self.status_updates_tx.clone();
4893 let scans_running = self.scans_running.clone();
4894 self.executor
4895 .spawn(async move {
4896 if !git_status_update_jobs.is_empty() {
4897 let status_updates = join_all(git_status_update_jobs).await;
4898 let status_updated = status_updates
4899 .iter()
4900 .any(|update_result| update_result.is_ok());
4901 dec_scans_running(&scans_running, status_updates.len() as i32);
4902 if status_updated {
4903 let scanning = scans_running.load(atomic::Ordering::Acquire) > 0;
4904 send_status_update_inner(
4905 phase,
4906 task_state,
4907 status_updates_tx,
4908 scanning,
4909 SmallVec::new(),
4910 );
4911 }
4912 }
4913 })
4914 .detach();
4915
4916 let mut state = self.state.lock();
4917
4918 // Identify any subdirectories that should not be scanned.
4919 let mut job_ix = 0;
4920 for entry in &mut new_entries {
4921 state.reuse_entry_id(entry);
4922 if entry.is_dir() {
4923 if state.should_scan_directory(entry) {
4924 job_ix += 1;
4925 } else {
4926 log::debug!("defer scanning directory {:?}", entry.path);
4927 entry.kind = EntryKind::UnloadedDir;
4928 new_jobs.remove(job_ix);
4929 }
4930 }
4931 if entry.is_always_included {
4932 state
4933 .snapshot
4934 .always_included_entries
4935 .push(entry.path.clone());
4936 }
4937 }
4938
4939 state.populate_dir(&job.path, new_entries, new_ignore);
4940 self.watcher.add(job.abs_path.as_ref()).log_err();
4941
4942 for new_job in new_jobs.into_iter().flatten() {
4943 job.scan_queue
4944 .try_send(new_job)
4945 .expect("channel is unbounded");
4946 }
4947
4948 Ok(())
4949 }
4950
4951 /// All list arguments should be sorted before calling this function
4952 async fn reload_entries_for_paths(
4953 &self,
4954 root_abs_path: SanitizedPath,
4955 root_canonical_path: SanitizedPath,
4956 relative_paths: &[Arc<Path>],
4957 abs_paths: Vec<PathBuf>,
4958 scan_queue_tx: Option<Sender<ScanJob>>,
4959 ) {
4960 // grab metadata for all requested paths
4961 let metadata = futures::future::join_all(
4962 abs_paths
4963 .iter()
4964 .map(|abs_path| async move {
4965 let metadata = self.fs.metadata(abs_path).await?;
4966 if let Some(metadata) = metadata {
4967 let canonical_path = self.fs.canonicalize(abs_path).await?;
4968
4969 // If we're on a case-insensitive filesystem (default on macOS), we want
4970 // to only ignore metadata for non-symlink files if their absolute-path matches
4971 // the canonical-path.
4972 // Because if not, this might be a case-only-renaming (`mv test.txt TEST.TXT`)
4973 // and we want to ignore the metadata for the old path (`test.txt`) so it's
4974 // treated as removed.
4975 if !self.fs_case_sensitive && !metadata.is_symlink {
4976 let canonical_file_name = canonical_path.file_name();
4977 let file_name = abs_path.file_name();
4978 if canonical_file_name != file_name {
4979 return Ok(None);
4980 }
4981 }
4982
4983 anyhow::Ok(Some((metadata, SanitizedPath::from(canonical_path))))
4984 } else {
4985 Ok(None)
4986 }
4987 })
4988 .collect::<Vec<_>>(),
4989 )
4990 .await;
4991
4992 let mut state = self.state.lock();
4993 let doing_recursive_update = scan_queue_tx.is_some();
4994
4995 // Remove any entries for paths that no longer exist or are being recursively
4996 // refreshed. Do this before adding any new entries, so that renames can be
4997 // detected regardless of the order of the paths.
4998 for (path, metadata) in relative_paths.iter().zip(metadata.iter()) {
4999 if matches!(metadata, Ok(None)) || doing_recursive_update {
5000 log::trace!("remove path {:?}", path);
5001 state.remove_path(path);
5002 }
5003 }
5004
5005 // Group all relative paths by their git repository.
5006 let mut paths_by_git_repo = HashMap::default();
5007 for (relative_path, abs_path) in relative_paths.iter().zip(&abs_paths) {
5008 let repository_data = state
5009 .snapshot
5010 .local_repo_containing_path(relative_path)
5011 .zip(state.snapshot.repository_containing_abs_path(abs_path));
5012 if let Some((local_repo, entry)) = repository_data {
5013 if let Ok(repo_path) = local_repo.relativize(relative_path) {
5014 paths_by_git_repo
5015 .entry(local_repo.work_directory.clone())
5016 .or_insert_with(|| RepoPaths {
5017 entry: entry.clone(),
5018 repo: local_repo.repo_ptr.clone(),
5019 repo_paths: Default::default(),
5020 })
5021 .add_path(repo_path);
5022 }
5023 }
5024 }
5025
5026 for (_work_directory, mut paths) in paths_by_git_repo {
5027 if let Ok(status) = paths.repo.status_blocking(&paths.repo_paths) {
5028 let mut changed_path_statuses = Vec::new();
5029 let statuses = paths.entry.statuses_by_path.clone();
5030 let mut cursor = statuses.cursor::<PathProgress>(&());
5031
5032 for (repo_path, status) in &*status.entries {
5033 paths.remove_repo_path(repo_path);
5034 if cursor.seek_forward(&PathTarget::Path(repo_path), Bias::Left, &()) {
5035 if &cursor.item().unwrap().status == status {
5036 continue;
5037 }
5038 }
5039
5040 changed_path_statuses.push(Edit::Insert(StatusEntry {
5041 repo_path: repo_path.clone(),
5042 status: *status,
5043 }));
5044 }
5045
5046 let mut cursor = statuses.cursor::<PathProgress>(&());
5047 for path in paths.repo_paths {
5048 if cursor.seek_forward(&PathTarget::Path(&path), Bias::Left, &()) {
5049 changed_path_statuses.push(Edit::Remove(PathKey(path.0)));
5050 }
5051 }
5052
5053 if !changed_path_statuses.is_empty() {
5054 let work_directory_id = state.snapshot.repositories.update(
5055 &AbsPathKey(paths.entry.work_directory_abs_path.as_path().into()),
5056 &(),
5057 move |repository_entry| {
5058 repository_entry
5059 .statuses_by_path
5060 .edit(changed_path_statuses, &());
5061
5062 repository_entry.work_directory_id
5063 },
5064 );
5065
5066 if let Some(work_directory_id) = work_directory_id {
5067 let scan_id = state.snapshot.scan_id;
5068 state.snapshot.git_repositories.update(
5069 &work_directory_id,
5070 |local_repository_entry| {
5071 local_repository_entry.status_scan_id = scan_id;
5072 },
5073 );
5074 }
5075 }
5076 }
5077 }
5078
5079 for (path, metadata) in relative_paths.iter().zip(metadata.into_iter()) {
5080 let abs_path: Arc<Path> = root_abs_path.as_path().join(path).into();
5081 match metadata {
5082 Ok(Some((metadata, canonical_path))) => {
5083 let ignore_stack = state
5084 .snapshot
5085 .ignore_stack_for_abs_path(&abs_path, metadata.is_dir);
5086 let is_external = !canonical_path.starts_with(&root_canonical_path);
5087 let mut fs_entry = Entry::new(
5088 path.clone(),
5089 &metadata,
5090 self.next_entry_id.as_ref(),
5091 state.snapshot.root_char_bag,
5092 if metadata.is_symlink {
5093 Some(canonical_path.as_path().to_path_buf().into())
5094 } else {
5095 None
5096 },
5097 );
5098
5099 let is_dir = fs_entry.is_dir();
5100 fs_entry.is_ignored = ignore_stack.is_abs_path_ignored(&abs_path, is_dir);
5101 fs_entry.is_external = is_external;
5102 fs_entry.is_private = self.is_path_private(path);
5103 fs_entry.is_always_included = self.settings.is_path_always_included(path);
5104
5105 if let (Some(scan_queue_tx), true) = (&scan_queue_tx, is_dir) {
5106 if state.should_scan_directory(&fs_entry)
5107 || (fs_entry.path.as_os_str().is_empty()
5108 && abs_path.file_name() == Some(*DOT_GIT))
5109 {
5110 state.enqueue_scan_dir(abs_path, &fs_entry, scan_queue_tx);
5111 } else {
5112 fs_entry.kind = EntryKind::UnloadedDir;
5113 }
5114 }
5115
5116 state.insert_entry(fs_entry.clone(), self.fs.as_ref(), self.watcher.as_ref());
5117 }
5118 Ok(None) => {
5119 self.remove_repo_path(path, &mut state.snapshot);
5120 }
5121 Err(err) => {
5122 log::error!("error reading file {abs_path:?} on event: {err:#}");
5123 }
5124 }
5125 }
5126
5127 util::extend_sorted(
5128 &mut state.changed_paths,
5129 relative_paths.iter().cloned(),
5130 usize::MAX,
5131 Ord::cmp,
5132 );
5133 }
5134
5135 fn remove_repo_path(&self, path: &Arc<Path>, snapshot: &mut LocalSnapshot) -> Option<()> {
5136 if !path
5137 .components()
5138 .any(|component| component.as_os_str() == *DOT_GIT)
5139 {
5140 if let Some(local_repo) = snapshot.local_repo_for_work_directory_path(path) {
5141 let id = local_repo.work_directory_id;
5142 log::debug!("remove repo path: {:?}", path);
5143 snapshot.git_repositories.remove(&id);
5144 snapshot
5145 .repositories
5146 .retain(&(), |repo_entry| repo_entry.work_directory_id != id);
5147 return Some(());
5148 }
5149 }
5150
5151 Some(())
5152 }
5153
5154 async fn update_ignore_statuses(&self, scan_job_tx: Sender<ScanJob>) {
5155 let mut ignores_to_update = Vec::new();
5156 let (ignore_queue_tx, ignore_queue_rx) = channel::unbounded();
5157 let prev_snapshot;
5158 {
5159 let snapshot = &mut self.state.lock().snapshot;
5160 let abs_path = snapshot.abs_path.clone();
5161 snapshot
5162 .ignores_by_parent_abs_path
5163 .retain(|parent_abs_path, (_, needs_update)| {
5164 if let Ok(parent_path) = parent_abs_path.strip_prefix(abs_path.as_path()) {
5165 if *needs_update {
5166 *needs_update = false;
5167 if snapshot.snapshot.entry_for_path(parent_path).is_some() {
5168 ignores_to_update.push(parent_abs_path.clone());
5169 }
5170 }
5171
5172 let ignore_path = parent_path.join(*GITIGNORE);
5173 if snapshot.snapshot.entry_for_path(ignore_path).is_none() {
5174 return false;
5175 }
5176 }
5177 true
5178 });
5179
5180 ignores_to_update.sort_unstable();
5181 let mut ignores_to_update = ignores_to_update.into_iter().peekable();
5182 while let Some(parent_abs_path) = ignores_to_update.next() {
5183 while ignores_to_update
5184 .peek()
5185 .map_or(false, |p| p.starts_with(&parent_abs_path))
5186 {
5187 ignores_to_update.next().unwrap();
5188 }
5189
5190 let ignore_stack = snapshot.ignore_stack_for_abs_path(&parent_abs_path, true);
5191 ignore_queue_tx
5192 .send_blocking(UpdateIgnoreStatusJob {
5193 abs_path: parent_abs_path,
5194 ignore_stack,
5195 ignore_queue: ignore_queue_tx.clone(),
5196 scan_queue: scan_job_tx.clone(),
5197 })
5198 .unwrap();
5199 }
5200
5201 prev_snapshot = snapshot.clone();
5202 }
5203 drop(ignore_queue_tx);
5204
5205 self.executor
5206 .scoped(|scope| {
5207 for _ in 0..self.executor.num_cpus() {
5208 scope.spawn(async {
5209 loop {
5210 select_biased! {
5211 // Process any path refresh requests before moving on to process
5212 // the queue of ignore statuses.
5213 request = self.next_scan_request().fuse() => {
5214 let Ok(request) = request else { break };
5215 if !self.process_scan_request(request, true).await {
5216 return;
5217 }
5218 }
5219
5220 // Recursively process directories whose ignores have changed.
5221 job = ignore_queue_rx.recv().fuse() => {
5222 let Ok(job) = job else { break };
5223 self.update_ignore_status(job, &prev_snapshot).await;
5224 }
5225 }
5226 }
5227 });
5228 }
5229 })
5230 .await;
5231 }
5232
5233 async fn update_ignore_status(&self, job: UpdateIgnoreStatusJob, snapshot: &LocalSnapshot) {
5234 log::trace!("update ignore status {:?}", job.abs_path);
5235
5236 let mut ignore_stack = job.ignore_stack;
5237 if let Some((ignore, _)) = snapshot.ignores_by_parent_abs_path.get(&job.abs_path) {
5238 ignore_stack = ignore_stack.append(job.abs_path.clone(), ignore.clone());
5239 }
5240
5241 let mut entries_by_id_edits = Vec::new();
5242 let mut entries_by_path_edits = Vec::new();
5243 let path = job
5244 .abs_path
5245 .strip_prefix(snapshot.abs_path.as_path())
5246 .unwrap();
5247
5248 for mut entry in snapshot.child_entries(path).cloned() {
5249 let was_ignored = entry.is_ignored;
5250 let abs_path: Arc<Path> = snapshot.abs_path().join(&entry.path).into();
5251 entry.is_ignored = ignore_stack.is_abs_path_ignored(&abs_path, entry.is_dir());
5252
5253 if entry.is_dir() {
5254 let child_ignore_stack = if entry.is_ignored {
5255 IgnoreStack::all()
5256 } else {
5257 ignore_stack.clone()
5258 };
5259
5260 // Scan any directories that were previously ignored and weren't previously scanned.
5261 if was_ignored && !entry.is_ignored && entry.kind.is_unloaded() {
5262 let state = self.state.lock();
5263 if state.should_scan_directory(&entry) {
5264 state.enqueue_scan_dir(abs_path.clone(), &entry, &job.scan_queue);
5265 }
5266 }
5267
5268 job.ignore_queue
5269 .send(UpdateIgnoreStatusJob {
5270 abs_path: abs_path.clone(),
5271 ignore_stack: child_ignore_stack,
5272 ignore_queue: job.ignore_queue.clone(),
5273 scan_queue: job.scan_queue.clone(),
5274 })
5275 .await
5276 .unwrap();
5277 }
5278
5279 if entry.is_ignored != was_ignored {
5280 let mut path_entry = snapshot.entries_by_id.get(&entry.id, &()).unwrap().clone();
5281 path_entry.scan_id = snapshot.scan_id;
5282 path_entry.is_ignored = entry.is_ignored;
5283 entries_by_id_edits.push(Edit::Insert(path_entry));
5284 entries_by_path_edits.push(Edit::Insert(entry));
5285 }
5286 }
5287
5288 let state = &mut self.state.lock();
5289 for edit in &entries_by_path_edits {
5290 if let Edit::Insert(entry) = edit {
5291 if let Err(ix) = state.changed_paths.binary_search(&entry.path) {
5292 state.changed_paths.insert(ix, entry.path.clone());
5293 }
5294 }
5295 }
5296
5297 state
5298 .snapshot
5299 .entries_by_path
5300 .edit(entries_by_path_edits, &());
5301 state.snapshot.entries_by_id.edit(entries_by_id_edits, &());
5302 }
5303
5304 fn update_git_repositories(&self, dot_git_paths: Vec<PathBuf>) -> Task<()> {
5305 log::info!("reloading repositories: {dot_git_paths:?}");
5306
5307 let mut status_updates = Vec::new();
5308 {
5309 let mut state = self.state.lock();
5310 let scan_id = state.snapshot.scan_id;
5311 for dot_git_dir in dot_git_paths {
5312 let existing_repository_entry =
5313 state
5314 .snapshot
5315 .git_repositories
5316 .iter()
5317 .find_map(|(_, repo)| {
5318 if repo.dot_git_dir_abs_path.as_ref() == &dot_git_dir
5319 || repo.dot_git_worktree_abs_path.as_deref() == Some(&dot_git_dir)
5320 {
5321 Some(repo.clone())
5322 } else {
5323 None
5324 }
5325 });
5326
5327 let local_repository = match existing_repository_entry {
5328 None => {
5329 let Ok(relative) = dot_git_dir.strip_prefix(state.snapshot.abs_path())
5330 else {
5331 return Task::ready(());
5332 };
5333 match state.insert_git_repository(
5334 relative.into(),
5335 self.fs.as_ref(),
5336 self.watcher.as_ref(),
5337 ) {
5338 Some(output) => output,
5339 None => continue,
5340 }
5341 }
5342 Some(local_repository) => {
5343 if local_repository.git_dir_scan_id == scan_id {
5344 continue;
5345 }
5346 local_repository.repo_ptr.reload_index();
5347
5348 state.snapshot.git_repositories.update(
5349 &local_repository.work_directory_id,
5350 |entry| {
5351 entry.git_dir_scan_id = scan_id;
5352 entry.status_scan_id = scan_id;
5353 },
5354 );
5355 if let Some(repo_entry) = state
5356 .snapshot
5357 .repository_for_id(local_repository.work_directory_id)
5358 {
5359 let abs_path_key =
5360 AbsPathKey(repo_entry.work_directory_abs_path.as_path().into());
5361 state
5362 .snapshot
5363 .repositories
5364 .update(&abs_path_key, &(), |repo| repo.worktree_scan_id = scan_id);
5365 }
5366
5367 local_repository
5368 }
5369 };
5370
5371 inc_scans_running(&self.scans_running);
5372 status_updates
5373 .push(self.schedule_git_statuses_update(&mut state, local_repository));
5374 }
5375
5376 // Remove any git repositories whose .git entry no longer exists.
5377 let snapshot = &mut state.snapshot;
5378 let mut ids_to_preserve = HashSet::default();
5379 for (&work_directory_id, entry) in snapshot.git_repositories.iter() {
5380 let exists_in_snapshot = snapshot
5381 .entry_for_id(work_directory_id)
5382 .map_or(false, |entry| {
5383 snapshot.entry_for_path(entry.path.join(*DOT_GIT)).is_some()
5384 });
5385
5386 if exists_in_snapshot
5387 || matches!(
5388 smol::block_on(self.fs.metadata(&entry.dot_git_dir_abs_path)),
5389 Ok(Some(_))
5390 )
5391 {
5392 ids_to_preserve.insert(work_directory_id);
5393 }
5394 }
5395
5396 snapshot
5397 .git_repositories
5398 .retain(|work_directory_id, _| ids_to_preserve.contains(work_directory_id));
5399 snapshot.repositories.retain(&(), |entry| {
5400 ids_to_preserve.contains(&entry.work_directory_id)
5401 });
5402 }
5403
5404 let scans_running = self.scans_running.clone();
5405 self.executor.spawn(async move {
5406 let updates_finished: Vec<Result<(), oneshot::Canceled>> =
5407 join_all(status_updates).await;
5408 let n = updates_finished.len();
5409 dec_scans_running(&scans_running, n as i32);
5410 })
5411 }
5412
5413 /// Update the git statuses for a given batch of entries.
5414 fn schedule_git_statuses_update(
5415 &self,
5416 state: &mut BackgroundScannerState,
5417 local_repository: LocalRepositoryEntry,
5418 ) -> oneshot::Receiver<()> {
5419 let job_state = self.state.clone();
5420 let (tx, rx) = oneshot::channel();
5421
5422 state.repository_scans.insert(
5423 local_repository.work_directory.path_key(),
5424 self.executor
5425 .spawn(do_git_status_update(job_state, local_repository, tx)),
5426 );
5427 rx
5428 }
5429
5430 async fn progress_timer(&self, running: bool) {
5431 if !running {
5432 return futures::future::pending().await;
5433 }
5434
5435 #[cfg(any(test, feature = "test-support"))]
5436 if self.fs.is_fake() {
5437 return self.executor.simulate_random_delay().await;
5438 }
5439
5440 smol::Timer::after(FS_WATCH_LATENCY).await;
5441 }
5442
5443 fn is_path_private(&self, path: &Path) -> bool {
5444 !self.share_private_files && self.settings.is_path_private(path)
5445 }
5446
5447 async fn next_scan_request(&self) -> Result<ScanRequest> {
5448 let mut request = self.scan_requests_rx.recv().await?;
5449 while let Ok(next_request) = self.scan_requests_rx.try_recv() {
5450 request.relative_paths.extend(next_request.relative_paths);
5451 request.done.extend(next_request.done);
5452 }
5453 Ok(request)
5454 }
5455}
5456
5457fn inc_scans_running(scans_running: &AtomicI32) {
5458 scans_running.fetch_add(1, atomic::Ordering::Release);
5459}
5460
5461fn dec_scans_running(scans_running: &AtomicI32, by: i32) {
5462 let old = scans_running.fetch_sub(by, atomic::Ordering::Release);
5463 debug_assert!(old >= by);
5464}
5465
5466fn send_status_update_inner(
5467 phase: BackgroundScannerPhase,
5468 state: Arc<Mutex<BackgroundScannerState>>,
5469 status_updates_tx: UnboundedSender<ScanState>,
5470 scanning: bool,
5471 barrier: SmallVec<[barrier::Sender; 1]>,
5472) -> bool {
5473 let mut state = state.lock();
5474 if state.changed_paths.is_empty() && scanning {
5475 return true;
5476 }
5477
5478 let new_snapshot = state.snapshot.clone();
5479 let old_snapshot = mem::replace(&mut state.prev_snapshot, new_snapshot.snapshot.clone());
5480 let changes = build_diff(phase, &old_snapshot, &new_snapshot, &state.changed_paths);
5481 state.changed_paths.clear();
5482
5483 status_updates_tx
5484 .unbounded_send(ScanState::Updated {
5485 snapshot: new_snapshot,
5486 changes,
5487 scanning,
5488 barrier,
5489 })
5490 .is_ok()
5491}
5492
5493async fn update_branches(
5494 state: &Mutex<BackgroundScannerState>,
5495 repository: &mut LocalRepositoryEntry,
5496) -> Result<()> {
5497 let branches = repository.repo().branches().await?;
5498 let snapshot = state.lock().snapshot.snapshot.clone();
5499 let mut repository = snapshot
5500 .repositories
5501 .iter()
5502 .find(|repo_entry| repo_entry.work_directory_id == repository.work_directory_id)
5503 .context("missing repository")?
5504 .clone();
5505 repository.current_branch = branches.into_iter().find(|branch| branch.is_head);
5506
5507 let mut state = state.lock();
5508 state
5509 .snapshot
5510 .repositories
5511 .insert_or_replace(repository, &());
5512
5513 Ok(())
5514}
5515
5516async fn do_git_status_update(
5517 job_state: Arc<Mutex<BackgroundScannerState>>,
5518 mut local_repository: LocalRepositoryEntry,
5519 tx: oneshot::Sender<()>,
5520) {
5521 let repository_name = local_repository.work_directory.display_name();
5522 log::trace!("updating git branches for repo {repository_name}");
5523 update_branches(&job_state, &mut local_repository)
5524 .await
5525 .log_err();
5526 let t0 = Instant::now();
5527
5528 log::trace!("updating git statuses for repo {repository_name}");
5529 let Some(statuses) = local_repository
5530 .repo()
5531 .status_blocking(&[git::WORK_DIRECTORY_REPO_PATH.clone()])
5532 .log_err()
5533 else {
5534 return;
5535 };
5536 log::trace!(
5537 "computed git statuses for repo {repository_name} in {:?}",
5538 t0.elapsed()
5539 );
5540
5541 let t0 = Instant::now();
5542 let mut changed_paths = Vec::new();
5543 let snapshot = job_state.lock().snapshot.snapshot.clone();
5544
5545 let Some(mut repository) = snapshot
5546 .repository_for_id(local_repository.work_directory_id)
5547 .context("tried to update git statuses for a repository that isn't in the snapshot")
5548 .log_err()
5549 .cloned()
5550 else {
5551 return;
5552 };
5553
5554 let merge_head_shas = local_repository.repo().merge_head_shas();
5555 if merge_head_shas != local_repository.current_merge_head_shas {
5556 mem::take(&mut repository.current_merge_conflicts);
5557 }
5558
5559 let mut new_entries_by_path = SumTree::new(&());
5560 for (repo_path, status) in statuses.entries.iter() {
5561 let project_path = local_repository.work_directory.try_unrelativize(repo_path);
5562
5563 new_entries_by_path.insert_or_replace(
5564 StatusEntry {
5565 repo_path: repo_path.clone(),
5566 status: *status,
5567 },
5568 &(),
5569 );
5570 if status.is_conflicted() {
5571 repository.current_merge_conflicts.insert(repo_path.clone());
5572 }
5573
5574 if let Some(path) = project_path {
5575 changed_paths.push(path);
5576 }
5577 }
5578
5579 log::trace!("statuses: {:#?}", new_entries_by_path);
5580 repository.statuses_by_path = new_entries_by_path;
5581 let mut state = job_state.lock();
5582 state
5583 .snapshot
5584 .repositories
5585 .insert_or_replace(repository, &());
5586 state
5587 .snapshot
5588 .git_repositories
5589 .update(&local_repository.work_directory_id, |entry| {
5590 entry.current_merge_head_shas = merge_head_shas;
5591 entry.merge_message =
5592 std::fs::read_to_string(local_repository.dot_git_dir_abs_path.join("MERGE_MSG"))
5593 .ok()
5594 .and_then(|merge_msg| Some(merge_msg.lines().next()?.to_owned()));
5595 entry.status_scan_id += 1;
5596 });
5597
5598 util::extend_sorted(
5599 &mut state.changed_paths,
5600 changed_paths,
5601 usize::MAX,
5602 Ord::cmp,
5603 );
5604
5605 log::trace!(
5606 "applied git status updates for repo {repository_name} in {:?}",
5607 t0.elapsed(),
5608 );
5609 tx.send(()).ok();
5610}
5611
5612fn build_diff(
5613 phase: BackgroundScannerPhase,
5614 old_snapshot: &Snapshot,
5615 new_snapshot: &Snapshot,
5616 event_paths: &[Arc<Path>],
5617) -> UpdatedEntriesSet {
5618 use BackgroundScannerPhase::*;
5619 use PathChange::{Added, AddedOrUpdated, Loaded, Removed, Updated};
5620
5621 // Identify which paths have changed. Use the known set of changed
5622 // parent paths to optimize the search.
5623 let mut changes = Vec::new();
5624 let mut old_paths = old_snapshot.entries_by_path.cursor::<PathKey>(&());
5625 let mut new_paths = new_snapshot.entries_by_path.cursor::<PathKey>(&());
5626 let mut last_newly_loaded_dir_path = None;
5627 old_paths.next(&());
5628 new_paths.next(&());
5629 for path in event_paths {
5630 let path = PathKey(path.clone());
5631 if old_paths.item().map_or(false, |e| e.path < path.0) {
5632 old_paths.seek_forward(&path, Bias::Left, &());
5633 }
5634 if new_paths.item().map_or(false, |e| e.path < path.0) {
5635 new_paths.seek_forward(&path, Bias::Left, &());
5636 }
5637 loop {
5638 match (old_paths.item(), new_paths.item()) {
5639 (Some(old_entry), Some(new_entry)) => {
5640 if old_entry.path > path.0
5641 && new_entry.path > path.0
5642 && !old_entry.path.starts_with(&path.0)
5643 && !new_entry.path.starts_with(&path.0)
5644 {
5645 break;
5646 }
5647
5648 match Ord::cmp(&old_entry.path, &new_entry.path) {
5649 Ordering::Less => {
5650 changes.push((old_entry.path.clone(), old_entry.id, Removed));
5651 old_paths.next(&());
5652 }
5653 Ordering::Equal => {
5654 if phase == EventsReceivedDuringInitialScan {
5655 if old_entry.id != new_entry.id {
5656 changes.push((old_entry.path.clone(), old_entry.id, Removed));
5657 }
5658 // If the worktree was not fully initialized when this event was generated,
5659 // we can't know whether this entry was added during the scan or whether
5660 // it was merely updated.
5661 changes.push((
5662 new_entry.path.clone(),
5663 new_entry.id,
5664 AddedOrUpdated,
5665 ));
5666 } else if old_entry.id != new_entry.id {
5667 changes.push((old_entry.path.clone(), old_entry.id, Removed));
5668 changes.push((new_entry.path.clone(), new_entry.id, Added));
5669 } else if old_entry != new_entry {
5670 if old_entry.kind.is_unloaded() {
5671 last_newly_loaded_dir_path = Some(&new_entry.path);
5672 changes.push((new_entry.path.clone(), new_entry.id, Loaded));
5673 } else {
5674 changes.push((new_entry.path.clone(), new_entry.id, Updated));
5675 }
5676 }
5677 old_paths.next(&());
5678 new_paths.next(&());
5679 }
5680 Ordering::Greater => {
5681 let is_newly_loaded = phase == InitialScan
5682 || last_newly_loaded_dir_path
5683 .as_ref()
5684 .map_or(false, |dir| new_entry.path.starts_with(dir));
5685 changes.push((
5686 new_entry.path.clone(),
5687 new_entry.id,
5688 if is_newly_loaded { Loaded } else { Added },
5689 ));
5690 new_paths.next(&());
5691 }
5692 }
5693 }
5694 (Some(old_entry), None) => {
5695 changes.push((old_entry.path.clone(), old_entry.id, Removed));
5696 old_paths.next(&());
5697 }
5698 (None, Some(new_entry)) => {
5699 let is_newly_loaded = phase == InitialScan
5700 || last_newly_loaded_dir_path
5701 .as_ref()
5702 .map_or(false, |dir| new_entry.path.starts_with(dir));
5703 changes.push((
5704 new_entry.path.clone(),
5705 new_entry.id,
5706 if is_newly_loaded { Loaded } else { Added },
5707 ));
5708 new_paths.next(&());
5709 }
5710 (None, None) => break,
5711 }
5712 }
5713 }
5714
5715 changes.into()
5716}
5717
5718fn swap_to_front(child_paths: &mut Vec<PathBuf>, file: &OsStr) {
5719 let position = child_paths
5720 .iter()
5721 .position(|path| path.file_name().unwrap() == file);
5722 if let Some(position) = position {
5723 let temp = child_paths.remove(position);
5724 child_paths.insert(0, temp);
5725 }
5726}
5727
5728fn char_bag_for_path(root_char_bag: CharBag, path: &Path) -> CharBag {
5729 let mut result = root_char_bag;
5730 result.extend(
5731 path.to_string_lossy()
5732 .chars()
5733 .map(|c| c.to_ascii_lowercase()),
5734 );
5735 result
5736}
5737
5738#[derive(Debug)]
5739struct RepoPaths {
5740 repo: Arc<dyn GitRepository>,
5741 entry: RepositoryEntry,
5742 // sorted
5743 repo_paths: Vec<RepoPath>,
5744}
5745
5746impl RepoPaths {
5747 fn add_path(&mut self, repo_path: RepoPath) {
5748 match self.repo_paths.binary_search(&repo_path) {
5749 Ok(_) => {}
5750 Err(ix) => self.repo_paths.insert(ix, repo_path),
5751 }
5752 }
5753
5754 fn remove_repo_path(&mut self, repo_path: &RepoPath) {
5755 match self.repo_paths.binary_search(&repo_path) {
5756 Ok(ix) => {
5757 self.repo_paths.remove(ix);
5758 }
5759 Err(_) => {}
5760 }
5761 }
5762}
5763
5764#[derive(Debug)]
5765struct ScanJob {
5766 abs_path: Arc<Path>,
5767 path: Arc<Path>,
5768 ignore_stack: Arc<IgnoreStack>,
5769 scan_queue: Sender<ScanJob>,
5770 ancestor_inodes: TreeSet<u64>,
5771 is_external: bool,
5772}
5773
5774struct UpdateIgnoreStatusJob {
5775 abs_path: Arc<Path>,
5776 ignore_stack: Arc<IgnoreStack>,
5777 ignore_queue: Sender<UpdateIgnoreStatusJob>,
5778 scan_queue: Sender<ScanJob>,
5779}
5780
5781pub trait WorktreeModelHandle {
5782 #[cfg(any(test, feature = "test-support"))]
5783 fn flush_fs_events<'a>(
5784 &self,
5785 cx: &'a mut gpui::TestAppContext,
5786 ) -> futures::future::LocalBoxFuture<'a, ()>;
5787
5788 #[cfg(any(test, feature = "test-support"))]
5789 fn flush_fs_events_in_root_git_repository<'a>(
5790 &self,
5791 cx: &'a mut gpui::TestAppContext,
5792 ) -> futures::future::LocalBoxFuture<'a, ()>;
5793}
5794
5795impl WorktreeModelHandle for Entity<Worktree> {
5796 // When the worktree's FS event stream sometimes delivers "redundant" events for FS changes that
5797 // occurred before the worktree was constructed. These events can cause the worktree to perform
5798 // extra directory scans, and emit extra scan-state notifications.
5799 //
5800 // This function mutates the worktree's directory and waits for those mutations to be picked up,
5801 // to ensure that all redundant FS events have already been processed.
5802 #[cfg(any(test, feature = "test-support"))]
5803 fn flush_fs_events<'a>(
5804 &self,
5805 cx: &'a mut gpui::TestAppContext,
5806 ) -> futures::future::LocalBoxFuture<'a, ()> {
5807 let file_name = "fs-event-sentinel";
5808
5809 let tree = self.clone();
5810 let (fs, root_path) = self.update(cx, |tree, _| {
5811 let tree = tree.as_local().unwrap();
5812 (tree.fs.clone(), tree.abs_path().clone())
5813 });
5814
5815 async move {
5816 fs.create_file(&root_path.join(file_name), Default::default())
5817 .await
5818 .unwrap();
5819
5820 let mut events = cx.events(&tree);
5821 while events.next().await.is_some() {
5822 if tree.update(cx, |tree, _| tree.entry_for_path(file_name).is_some()) {
5823 break;
5824 }
5825 }
5826
5827 fs.remove_file(&root_path.join(file_name), Default::default())
5828 .await
5829 .unwrap();
5830 while events.next().await.is_some() {
5831 if tree.update(cx, |tree, _| tree.entry_for_path(file_name).is_none()) {
5832 break;
5833 }
5834 }
5835
5836 cx.update(|cx| tree.read(cx).as_local().unwrap().scan_complete())
5837 .await;
5838 }
5839 .boxed_local()
5840 }
5841
5842 // This function is similar to flush_fs_events, except that it waits for events to be flushed in
5843 // the .git folder of the root repository.
5844 // The reason for its existence is that a repository's .git folder might live *outside* of the
5845 // worktree and thus its FS events might go through a different path.
5846 // In order to flush those, we need to create artificial events in the .git folder and wait
5847 // for the repository to be reloaded.
5848 #[cfg(any(test, feature = "test-support"))]
5849 fn flush_fs_events_in_root_git_repository<'a>(
5850 &self,
5851 cx: &'a mut gpui::TestAppContext,
5852 ) -> futures::future::LocalBoxFuture<'a, ()> {
5853 let file_name = "fs-event-sentinel";
5854
5855 let tree = self.clone();
5856 let (fs, root_path, mut git_dir_scan_id) = self.update(cx, |tree, _| {
5857 let tree = tree.as_local().unwrap();
5858 let repository = tree.repositories.first().unwrap();
5859 let local_repo_entry = tree.get_local_repo(&repository).unwrap();
5860 (
5861 tree.fs.clone(),
5862 local_repo_entry.dot_git_dir_abs_path.clone(),
5863 local_repo_entry.git_dir_scan_id,
5864 )
5865 });
5866
5867 let scan_id_increased = |tree: &mut Worktree, git_dir_scan_id: &mut usize| {
5868 let repository = tree.repositories.first().unwrap();
5869 let local_repo_entry = tree
5870 .as_local()
5871 .unwrap()
5872 .get_local_repo(&repository)
5873 .unwrap();
5874
5875 if local_repo_entry.git_dir_scan_id > *git_dir_scan_id {
5876 *git_dir_scan_id = local_repo_entry.git_dir_scan_id;
5877 true
5878 } else {
5879 false
5880 }
5881 };
5882
5883 async move {
5884 fs.create_file(&root_path.join(file_name), Default::default())
5885 .await
5886 .unwrap();
5887
5888 let mut events = cx.events(&tree);
5889 while events.next().await.is_some() {
5890 if tree.update(cx, |tree, _| scan_id_increased(tree, &mut git_dir_scan_id)) {
5891 break;
5892 }
5893 }
5894
5895 fs.remove_file(&root_path.join(file_name), Default::default())
5896 .await
5897 .unwrap();
5898
5899 while events.next().await.is_some() {
5900 if tree.update(cx, |tree, _| scan_id_increased(tree, &mut git_dir_scan_id)) {
5901 break;
5902 }
5903 }
5904
5905 cx.update(|cx| tree.read(cx).as_local().unwrap().scan_complete())
5906 .await;
5907 }
5908 .boxed_local()
5909 }
5910}
5911
5912#[derive(Clone, Debug)]
5913struct TraversalProgress<'a> {
5914 max_path: &'a Path,
5915 count: usize,
5916 non_ignored_count: usize,
5917 file_count: usize,
5918 non_ignored_file_count: usize,
5919}
5920
5921impl TraversalProgress<'_> {
5922 fn count(&self, include_files: bool, include_dirs: bool, include_ignored: bool) -> usize {
5923 match (include_files, include_dirs, include_ignored) {
5924 (true, true, true) => self.count,
5925 (true, true, false) => self.non_ignored_count,
5926 (true, false, true) => self.file_count,
5927 (true, false, false) => self.non_ignored_file_count,
5928 (false, true, true) => self.count - self.file_count,
5929 (false, true, false) => self.non_ignored_count - self.non_ignored_file_count,
5930 (false, false, _) => 0,
5931 }
5932 }
5933}
5934
5935impl<'a> sum_tree::Dimension<'a, EntrySummary> for TraversalProgress<'a> {
5936 fn zero(_cx: &()) -> Self {
5937 Default::default()
5938 }
5939
5940 fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
5941 self.max_path = summary.max_path.as_ref();
5942 self.count += summary.count;
5943 self.non_ignored_count += summary.non_ignored_count;
5944 self.file_count += summary.file_count;
5945 self.non_ignored_file_count += summary.non_ignored_file_count;
5946 }
5947}
5948
5949impl Default for TraversalProgress<'_> {
5950 fn default() -> Self {
5951 Self {
5952 max_path: Path::new(""),
5953 count: 0,
5954 non_ignored_count: 0,
5955 file_count: 0,
5956 non_ignored_file_count: 0,
5957 }
5958 }
5959}
5960
5961#[derive(Debug)]
5962pub struct Traversal<'a> {
5963 snapshot: &'a Snapshot,
5964 cursor: sum_tree::Cursor<'a, Entry, TraversalProgress<'a>>,
5965 include_ignored: bool,
5966 include_files: bool,
5967 include_dirs: bool,
5968}
5969
5970impl<'a> Traversal<'a> {
5971 fn new(
5972 snapshot: &'a Snapshot,
5973 include_files: bool,
5974 include_dirs: bool,
5975 include_ignored: bool,
5976 start_path: &Path,
5977 ) -> Self {
5978 let mut cursor = snapshot.entries_by_path.cursor(&());
5979 cursor.seek(&TraversalTarget::path(start_path), Bias::Left, &());
5980 let mut traversal = Self {
5981 snapshot,
5982 cursor,
5983 include_files,
5984 include_dirs,
5985 include_ignored,
5986 };
5987 if traversal.end_offset() == traversal.start_offset() {
5988 traversal.next();
5989 }
5990 traversal
5991 }
5992
5993 pub fn advance(&mut self) -> bool {
5994 self.advance_by(1)
5995 }
5996
5997 pub fn advance_by(&mut self, count: usize) -> bool {
5998 self.cursor.seek_forward(
5999 &TraversalTarget::Count {
6000 count: self.end_offset() + count,
6001 include_dirs: self.include_dirs,
6002 include_files: self.include_files,
6003 include_ignored: self.include_ignored,
6004 },
6005 Bias::Left,
6006 &(),
6007 )
6008 }
6009
6010 pub fn advance_to_sibling(&mut self) -> bool {
6011 while let Some(entry) = self.cursor.item() {
6012 self.cursor
6013 .seek_forward(&TraversalTarget::successor(&entry.path), Bias::Left, &());
6014 if let Some(entry) = self.cursor.item() {
6015 if (self.include_files || !entry.is_file())
6016 && (self.include_dirs || !entry.is_dir())
6017 && (self.include_ignored || !entry.is_ignored || entry.is_always_included)
6018 {
6019 return true;
6020 }
6021 }
6022 }
6023 false
6024 }
6025
6026 pub fn back_to_parent(&mut self) -> bool {
6027 let Some(parent_path) = self.cursor.item().and_then(|entry| entry.path.parent()) else {
6028 return false;
6029 };
6030 self.cursor
6031 .seek(&TraversalTarget::path(parent_path), Bias::Left, &())
6032 }
6033
6034 pub fn entry(&self) -> Option<&'a Entry> {
6035 self.cursor.item()
6036 }
6037
6038 pub fn snapshot(&self) -> &'a Snapshot {
6039 self.snapshot
6040 }
6041
6042 pub fn start_offset(&self) -> usize {
6043 self.cursor
6044 .start()
6045 .count(self.include_files, self.include_dirs, self.include_ignored)
6046 }
6047
6048 pub fn end_offset(&self) -> usize {
6049 self.cursor
6050 .end(&())
6051 .count(self.include_files, self.include_dirs, self.include_ignored)
6052 }
6053}
6054
6055impl<'a> Iterator for Traversal<'a> {
6056 type Item = &'a Entry;
6057
6058 fn next(&mut self) -> Option<Self::Item> {
6059 if let Some(item) = self.entry() {
6060 self.advance();
6061 Some(item)
6062 } else {
6063 None
6064 }
6065 }
6066}
6067
6068#[derive(Debug, Clone, Copy)]
6069pub enum PathTarget<'a> {
6070 Path(&'a Path),
6071 Successor(&'a Path),
6072}
6073
6074impl PathTarget<'_> {
6075 fn cmp_path(&self, other: &Path) -> Ordering {
6076 match self {
6077 PathTarget::Path(path) => path.cmp(&other),
6078 PathTarget::Successor(path) => {
6079 if other.starts_with(path) {
6080 Ordering::Greater
6081 } else {
6082 Ordering::Equal
6083 }
6084 }
6085 }
6086 }
6087}
6088
6089impl<'a, S: Summary> SeekTarget<'a, PathSummary<S>, PathProgress<'a>> for PathTarget<'_> {
6090 fn cmp(&self, cursor_location: &PathProgress<'a>, _: &S::Context) -> Ordering {
6091 self.cmp_path(&cursor_location.max_path)
6092 }
6093}
6094
6095impl<'a, S: Summary> SeekTarget<'a, PathSummary<S>, TraversalProgress<'a>> for PathTarget<'_> {
6096 fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: &S::Context) -> Ordering {
6097 self.cmp_path(&cursor_location.max_path)
6098 }
6099}
6100
6101impl<'a> SeekTarget<'a, PathSummary<GitSummary>, (TraversalProgress<'a>, GitSummary)>
6102 for PathTarget<'_>
6103{
6104 fn cmp(&self, cursor_location: &(TraversalProgress<'a>, GitSummary), _: &()) -> Ordering {
6105 self.cmp_path(&cursor_location.0.max_path)
6106 }
6107}
6108
6109#[derive(Debug)]
6110enum TraversalTarget<'a> {
6111 Path(PathTarget<'a>),
6112 Count {
6113 count: usize,
6114 include_files: bool,
6115 include_ignored: bool,
6116 include_dirs: bool,
6117 },
6118}
6119
6120impl<'a> TraversalTarget<'a> {
6121 fn path(path: &'a Path) -> Self {
6122 Self::Path(PathTarget::Path(path))
6123 }
6124
6125 fn successor(path: &'a Path) -> Self {
6126 Self::Path(PathTarget::Successor(path))
6127 }
6128
6129 fn cmp_progress(&self, progress: &TraversalProgress) -> Ordering {
6130 match self {
6131 TraversalTarget::Path(path) => path.cmp_path(&progress.max_path),
6132 TraversalTarget::Count {
6133 count,
6134 include_files,
6135 include_dirs,
6136 include_ignored,
6137 } => Ord::cmp(
6138 count,
6139 &progress.count(*include_files, *include_dirs, *include_ignored),
6140 ),
6141 }
6142 }
6143}
6144
6145impl<'a> SeekTarget<'a, EntrySummary, TraversalProgress<'a>> for TraversalTarget<'_> {
6146 fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: &()) -> Ordering {
6147 self.cmp_progress(cursor_location)
6148 }
6149}
6150
6151impl<'a> SeekTarget<'a, PathSummary<Unit>, TraversalProgress<'a>> for TraversalTarget<'_> {
6152 fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: &()) -> Ordering {
6153 self.cmp_progress(cursor_location)
6154 }
6155}
6156
6157pub struct ChildEntriesOptions {
6158 pub include_files: bool,
6159 pub include_dirs: bool,
6160 pub include_ignored: bool,
6161}
6162
6163pub struct ChildEntriesIter<'a> {
6164 parent_path: &'a Path,
6165 traversal: Traversal<'a>,
6166}
6167
6168impl<'a> Iterator for ChildEntriesIter<'a> {
6169 type Item = &'a Entry;
6170
6171 fn next(&mut self) -> Option<Self::Item> {
6172 if let Some(item) = self.traversal.entry() {
6173 if item.path.starts_with(self.parent_path) {
6174 self.traversal.advance_to_sibling();
6175 return Some(item);
6176 }
6177 }
6178 None
6179 }
6180}
6181
6182impl<'a> From<&'a Entry> for proto::Entry {
6183 fn from(entry: &'a Entry) -> Self {
6184 Self {
6185 id: entry.id.to_proto(),
6186 is_dir: entry.is_dir(),
6187 path: entry.path.as_ref().to_proto(),
6188 inode: entry.inode,
6189 mtime: entry.mtime.map(|time| time.into()),
6190 is_ignored: entry.is_ignored,
6191 is_external: entry.is_external,
6192 is_fifo: entry.is_fifo,
6193 size: Some(entry.size),
6194 canonical_path: entry
6195 .canonical_path
6196 .as_ref()
6197 .map(|path| path.as_ref().to_proto()),
6198 }
6199 }
6200}
6201
6202impl<'a> TryFrom<(&'a CharBag, &PathMatcher, proto::Entry)> for Entry {
6203 type Error = anyhow::Error;
6204
6205 fn try_from(
6206 (root_char_bag, always_included, entry): (&'a CharBag, &PathMatcher, proto::Entry),
6207 ) -> Result<Self> {
6208 let kind = if entry.is_dir {
6209 EntryKind::Dir
6210 } else {
6211 EntryKind::File
6212 };
6213
6214 let path = Arc::<Path>::from_proto(entry.path);
6215 let char_bag = char_bag_for_path(*root_char_bag, &path);
6216 let is_always_included = always_included.is_match(path.as_ref());
6217 Ok(Entry {
6218 id: ProjectEntryId::from_proto(entry.id),
6219 kind,
6220 path,
6221 inode: entry.inode,
6222 mtime: entry.mtime.map(|time| time.into()),
6223 size: entry.size.unwrap_or(0),
6224 canonical_path: entry
6225 .canonical_path
6226 .map(|path_string| Arc::from(PathBuf::from_proto(path_string))),
6227 is_ignored: entry.is_ignored,
6228 is_always_included,
6229 is_external: entry.is_external,
6230 is_private: false,
6231 char_bag,
6232 is_fifo: entry.is_fifo,
6233 })
6234 }
6235}
6236
6237fn status_from_proto(
6238 simple_status: i32,
6239 status: Option<proto::GitFileStatus>,
6240) -> anyhow::Result<FileStatus> {
6241 use proto::git_file_status::Variant;
6242
6243 let Some(variant) = status.and_then(|status| status.variant) else {
6244 let code = proto::GitStatus::from_i32(simple_status)
6245 .ok_or_else(|| anyhow!("Invalid git status code: {simple_status}"))?;
6246 let result = match code {
6247 proto::GitStatus::Added => TrackedStatus {
6248 worktree_status: StatusCode::Added,
6249 index_status: StatusCode::Unmodified,
6250 }
6251 .into(),
6252 proto::GitStatus::Modified => TrackedStatus {
6253 worktree_status: StatusCode::Modified,
6254 index_status: StatusCode::Unmodified,
6255 }
6256 .into(),
6257 proto::GitStatus::Conflict => UnmergedStatus {
6258 first_head: UnmergedStatusCode::Updated,
6259 second_head: UnmergedStatusCode::Updated,
6260 }
6261 .into(),
6262 proto::GitStatus::Deleted => TrackedStatus {
6263 worktree_status: StatusCode::Deleted,
6264 index_status: StatusCode::Unmodified,
6265 }
6266 .into(),
6267 _ => return Err(anyhow!("Invalid code for simple status: {simple_status}")),
6268 };
6269 return Ok(result);
6270 };
6271
6272 let result = match variant {
6273 Variant::Untracked(_) => FileStatus::Untracked,
6274 Variant::Ignored(_) => FileStatus::Ignored,
6275 Variant::Unmerged(unmerged) => {
6276 let [first_head, second_head] =
6277 [unmerged.first_head, unmerged.second_head].map(|head| {
6278 let code = proto::GitStatus::from_i32(head)
6279 .ok_or_else(|| anyhow!("Invalid git status code: {head}"))?;
6280 let result = match code {
6281 proto::GitStatus::Added => UnmergedStatusCode::Added,
6282 proto::GitStatus::Updated => UnmergedStatusCode::Updated,
6283 proto::GitStatus::Deleted => UnmergedStatusCode::Deleted,
6284 _ => return Err(anyhow!("Invalid code for unmerged status: {code:?}")),
6285 };
6286 Ok(result)
6287 });
6288 let [first_head, second_head] = [first_head?, second_head?];
6289 UnmergedStatus {
6290 first_head,
6291 second_head,
6292 }
6293 .into()
6294 }
6295 Variant::Tracked(tracked) => {
6296 let [index_status, worktree_status] = [tracked.index_status, tracked.worktree_status]
6297 .map(|status| {
6298 let code = proto::GitStatus::from_i32(status)
6299 .ok_or_else(|| anyhow!("Invalid git status code: {status}"))?;
6300 let result = match code {
6301 proto::GitStatus::Modified => StatusCode::Modified,
6302 proto::GitStatus::TypeChanged => StatusCode::TypeChanged,
6303 proto::GitStatus::Added => StatusCode::Added,
6304 proto::GitStatus::Deleted => StatusCode::Deleted,
6305 proto::GitStatus::Renamed => StatusCode::Renamed,
6306 proto::GitStatus::Copied => StatusCode::Copied,
6307 proto::GitStatus::Unmodified => StatusCode::Unmodified,
6308 _ => return Err(anyhow!("Invalid code for tracked status: {code:?}")),
6309 };
6310 Ok(result)
6311 });
6312 let [index_status, worktree_status] = [index_status?, worktree_status?];
6313 TrackedStatus {
6314 index_status,
6315 worktree_status,
6316 }
6317 .into()
6318 }
6319 };
6320 Ok(result)
6321}
6322
6323fn status_to_proto(status: FileStatus) -> proto::GitFileStatus {
6324 use proto::git_file_status::{Tracked, Unmerged, Variant};
6325
6326 let variant = match status {
6327 FileStatus::Untracked => Variant::Untracked(Default::default()),
6328 FileStatus::Ignored => Variant::Ignored(Default::default()),
6329 FileStatus::Unmerged(UnmergedStatus {
6330 first_head,
6331 second_head,
6332 }) => Variant::Unmerged(Unmerged {
6333 first_head: unmerged_status_to_proto(first_head),
6334 second_head: unmerged_status_to_proto(second_head),
6335 }),
6336 FileStatus::Tracked(TrackedStatus {
6337 index_status,
6338 worktree_status,
6339 }) => Variant::Tracked(Tracked {
6340 index_status: tracked_status_to_proto(index_status),
6341 worktree_status: tracked_status_to_proto(worktree_status),
6342 }),
6343 };
6344 proto::GitFileStatus {
6345 variant: Some(variant),
6346 }
6347}
6348
6349fn unmerged_status_to_proto(code: UnmergedStatusCode) -> i32 {
6350 match code {
6351 UnmergedStatusCode::Added => proto::GitStatus::Added as _,
6352 UnmergedStatusCode::Deleted => proto::GitStatus::Deleted as _,
6353 UnmergedStatusCode::Updated => proto::GitStatus::Updated as _,
6354 }
6355}
6356
6357fn tracked_status_to_proto(code: StatusCode) -> i32 {
6358 match code {
6359 StatusCode::Added => proto::GitStatus::Added as _,
6360 StatusCode::Deleted => proto::GitStatus::Deleted as _,
6361 StatusCode::Modified => proto::GitStatus::Modified as _,
6362 StatusCode::Renamed => proto::GitStatus::Renamed as _,
6363 StatusCode::TypeChanged => proto::GitStatus::TypeChanged as _,
6364 StatusCode::Copied => proto::GitStatus::Copied as _,
6365 StatusCode::Unmodified => proto::GitStatus::Unmodified as _,
6366 }
6367}
6368
6369#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
6370pub struct ProjectEntryId(usize);
6371
6372impl ProjectEntryId {
6373 pub const MAX: Self = Self(usize::MAX);
6374 pub const MIN: Self = Self(usize::MIN);
6375
6376 pub fn new(counter: &AtomicUsize) -> Self {
6377 Self(counter.fetch_add(1, SeqCst))
6378 }
6379
6380 pub fn from_proto(id: u64) -> Self {
6381 Self(id as usize)
6382 }
6383
6384 pub fn to_proto(&self) -> u64 {
6385 self.0 as u64
6386 }
6387
6388 pub fn to_usize(&self) -> usize {
6389 self.0
6390 }
6391}
6392
6393#[cfg(any(test, feature = "test-support"))]
6394impl CreatedEntry {
6395 pub fn to_included(self) -> Option<Entry> {
6396 match self {
6397 CreatedEntry::Included(entry) => Some(entry),
6398 CreatedEntry::Excluded { .. } => None,
6399 }
6400 }
6401}