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