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