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