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