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