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