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