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