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