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