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