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