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