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.update_observer = Some(tx);
1830 cx.spawn(|this, mut cx| async move {
1831 let mut update = initial_update;
1832 loop {
1833 // SSH projects use a special project ID of 0, and we need to
1834 // remap it to the correct one here.
1835 update.project_id = project_id;
1836 if !callback(update).await {
1837 break;
1838 }
1839 if let Some(next_update) = rx.next().await {
1840 update = next_update;
1841 } else {
1842 break;
1843 }
1844 }
1845 this.update(&mut cx, |this, _| {
1846 let this = this.as_remote_mut().unwrap();
1847 this.update_observer.take();
1848 })
1849 })
1850 .detach();
1851 }
1852
1853 fn observed_snapshot(&self, scan_id: usize) -> bool {
1854 self.completed_scan_id >= scan_id
1855 }
1856
1857 pub fn wait_for_snapshot(&mut self, scan_id: usize) -> impl Future<Output = Result<()>> {
1858 let (tx, rx) = oneshot::channel();
1859 if self.observed_snapshot(scan_id) {
1860 let _ = tx.send(());
1861 } else if self.disconnected {
1862 drop(tx);
1863 } else {
1864 match self
1865 .snapshot_subscriptions
1866 .binary_search_by_key(&scan_id, |probe| probe.0)
1867 {
1868 Ok(ix) | Err(ix) => self.snapshot_subscriptions.insert(ix, (scan_id, tx)),
1869 }
1870 }
1871
1872 async move {
1873 rx.await?;
1874 Ok(())
1875 }
1876 }
1877
1878 fn insert_entry(
1879 &mut self,
1880 entry: proto::Entry,
1881 scan_id: usize,
1882 cx: &mut ModelContext<Worktree>,
1883 ) -> Task<Result<Entry>> {
1884 let wait_for_snapshot = self.wait_for_snapshot(scan_id);
1885 cx.spawn(|this, mut cx| async move {
1886 wait_for_snapshot.await?;
1887 this.update(&mut cx, |worktree, _| {
1888 let worktree = worktree.as_remote_mut().unwrap();
1889 let snapshot = &mut worktree.background_snapshot.lock().0;
1890 let entry = snapshot.insert_entry(entry);
1891 worktree.snapshot = snapshot.clone();
1892 entry
1893 })?
1894 })
1895 }
1896
1897 fn delete_entry(
1898 &mut self,
1899 entry_id: ProjectEntryId,
1900 trash: bool,
1901 cx: &mut ModelContext<Worktree>,
1902 ) -> Option<Task<Result<()>>> {
1903 let response = self.client.request(proto::DeleteProjectEntry {
1904 project_id: self.project_id,
1905 entry_id: entry_id.to_proto(),
1906 use_trash: trash,
1907 });
1908 Some(cx.spawn(move |this, mut cx| async move {
1909 let response = response.await?;
1910 let scan_id = response.worktree_scan_id as usize;
1911
1912 this.update(&mut cx, move |this, _| {
1913 this.as_remote_mut().unwrap().wait_for_snapshot(scan_id)
1914 })?
1915 .await?;
1916
1917 this.update(&mut cx, |this, _| {
1918 let this = this.as_remote_mut().unwrap();
1919 let snapshot = &mut this.background_snapshot.lock().0;
1920 snapshot.delete_entry(entry_id);
1921 this.snapshot = snapshot.clone();
1922 })
1923 }))
1924 }
1925
1926 fn rename_entry(
1927 &mut self,
1928 entry_id: ProjectEntryId,
1929 new_path: impl Into<Arc<Path>>,
1930 cx: &mut ModelContext<Worktree>,
1931 ) -> Task<Result<CreatedEntry>> {
1932 let new_path = new_path.into();
1933 let response = self.client.request(proto::RenameProjectEntry {
1934 project_id: self.project_id,
1935 entry_id: entry_id.to_proto(),
1936 new_path: new_path.to_string_lossy().into(),
1937 });
1938 cx.spawn(move |this, mut cx| async move {
1939 let response = response.await?;
1940 match response.entry {
1941 Some(entry) => this
1942 .update(&mut cx, |this, cx| {
1943 this.as_remote_mut().unwrap().insert_entry(
1944 entry,
1945 response.worktree_scan_id as usize,
1946 cx,
1947 )
1948 })?
1949 .await
1950 .map(CreatedEntry::Included),
1951 None => {
1952 let abs_path = this.update(&mut cx, |worktree, _| {
1953 worktree
1954 .absolutize(&new_path)
1955 .with_context(|| format!("absolutizing {new_path:?}"))
1956 })??;
1957 Ok(CreatedEntry::Excluded { abs_path })
1958 }
1959 }
1960 })
1961 }
1962}
1963
1964impl Snapshot {
1965 pub fn new(id: u64, root_name: String, abs_path: Arc<Path>) -> Self {
1966 Snapshot {
1967 id: WorktreeId::from_usize(id as usize),
1968 abs_path,
1969 root_char_bag: root_name.chars().map(|c| c.to_ascii_lowercase()).collect(),
1970 root_name,
1971 entries_by_path: Default::default(),
1972 entries_by_id: Default::default(),
1973 repository_entries: Default::default(),
1974 scan_id: 1,
1975 completed_scan_id: 0,
1976 }
1977 }
1978
1979 pub fn id(&self) -> WorktreeId {
1980 self.id
1981 }
1982
1983 pub fn abs_path(&self) -> &Arc<Path> {
1984 &self.abs_path
1985 }
1986
1987 fn build_initial_update(&self, project_id: u64, worktree_id: u64) -> proto::UpdateWorktree {
1988 let mut updated_entries = self
1989 .entries_by_path
1990 .iter()
1991 .map(proto::Entry::from)
1992 .collect::<Vec<_>>();
1993 updated_entries.sort_unstable_by_key(|e| e.id);
1994
1995 let mut updated_repositories = self
1996 .repository_entries
1997 .values()
1998 .map(proto::RepositoryEntry::from)
1999 .collect::<Vec<_>>();
2000 updated_repositories.sort_unstable_by_key(|e| e.work_directory_id);
2001
2002 proto::UpdateWorktree {
2003 project_id,
2004 worktree_id,
2005 abs_path: self.abs_path().to_string_lossy().into(),
2006 root_name: self.root_name().to_string(),
2007 updated_entries,
2008 removed_entries: Vec::new(),
2009 scan_id: self.scan_id as u64,
2010 is_last_update: self.completed_scan_id == self.scan_id,
2011 updated_repositories,
2012 removed_repositories: Vec::new(),
2013 }
2014 }
2015
2016 pub fn absolutize(&self, path: &Path) -> Result<PathBuf> {
2017 if path
2018 .components()
2019 .any(|component| !matches!(component, std::path::Component::Normal(_)))
2020 {
2021 return Err(anyhow!("invalid path"));
2022 }
2023 if path.file_name().is_some() {
2024 Ok(self.abs_path.join(path))
2025 } else {
2026 Ok(self.abs_path.to_path_buf())
2027 }
2028 }
2029
2030 pub fn contains_entry(&self, entry_id: ProjectEntryId) -> bool {
2031 self.entries_by_id.get(&entry_id, &()).is_some()
2032 }
2033
2034 fn insert_entry(&mut self, entry: proto::Entry) -> Result<Entry> {
2035 let entry = Entry::try_from((&self.root_char_bag, entry))?;
2036 let old_entry = self.entries_by_id.insert_or_replace(
2037 PathEntry {
2038 id: entry.id,
2039 path: entry.path.clone(),
2040 is_ignored: entry.is_ignored,
2041 scan_id: 0,
2042 },
2043 &(),
2044 );
2045 if let Some(old_entry) = old_entry {
2046 self.entries_by_path.remove(&PathKey(old_entry.path), &());
2047 }
2048 self.entries_by_path.insert_or_replace(entry.clone(), &());
2049 Ok(entry)
2050 }
2051
2052 fn delete_entry(&mut self, entry_id: ProjectEntryId) -> Option<Arc<Path>> {
2053 let removed_entry = self.entries_by_id.remove(&entry_id, &())?;
2054 self.entries_by_path = {
2055 let mut cursor = self.entries_by_path.cursor::<TraversalProgress>(&());
2056 let mut new_entries_by_path =
2057 cursor.slice(&TraversalTarget::Path(&removed_entry.path), Bias::Left, &());
2058 while let Some(entry) = cursor.item() {
2059 if entry.path.starts_with(&removed_entry.path) {
2060 self.entries_by_id.remove(&entry.id, &());
2061 cursor.next(&());
2062 } else {
2063 break;
2064 }
2065 }
2066 new_entries_by_path.append(cursor.suffix(&()), &());
2067 new_entries_by_path
2068 };
2069
2070 Some(removed_entry.path)
2071 }
2072
2073 #[cfg(any(test, feature = "test-support"))]
2074 pub fn status_for_file(&self, path: impl Into<PathBuf>) -> Option<GitFileStatus> {
2075 let path = path.into();
2076 self.entries_by_path
2077 .get(&PathKey(Arc::from(path)), &())
2078 .and_then(|entry| entry.git_status)
2079 }
2080
2081 pub(crate) fn apply_remote_update(&mut self, mut update: proto::UpdateWorktree) -> Result<()> {
2082 log::trace!(
2083 "applying remote worktree update. {} entries updated, {} removed",
2084 update.updated_entries.len(),
2085 update.removed_entries.len()
2086 );
2087
2088 let mut entries_by_path_edits = Vec::new();
2089 let mut entries_by_id_edits = Vec::new();
2090
2091 for entry_id in update.removed_entries {
2092 let entry_id = ProjectEntryId::from_proto(entry_id);
2093 entries_by_id_edits.push(Edit::Remove(entry_id));
2094 if let Some(entry) = self.entry_for_id(entry_id) {
2095 entries_by_path_edits.push(Edit::Remove(PathKey(entry.path.clone())));
2096 }
2097 }
2098
2099 for entry in update.updated_entries {
2100 let entry = Entry::try_from((&self.root_char_bag, entry))?;
2101 if let Some(PathEntry { path, .. }) = self.entries_by_id.get(&entry.id, &()) {
2102 entries_by_path_edits.push(Edit::Remove(PathKey(path.clone())));
2103 }
2104 if let Some(old_entry) = self.entries_by_path.get(&PathKey(entry.path.clone()), &()) {
2105 if old_entry.id != entry.id {
2106 entries_by_id_edits.push(Edit::Remove(old_entry.id));
2107 }
2108 }
2109 entries_by_id_edits.push(Edit::Insert(PathEntry {
2110 id: entry.id,
2111 path: entry.path.clone(),
2112 is_ignored: entry.is_ignored,
2113 scan_id: 0,
2114 }));
2115 entries_by_path_edits.push(Edit::Insert(entry));
2116 }
2117
2118 self.entries_by_path.edit(entries_by_path_edits, &());
2119 self.entries_by_id.edit(entries_by_id_edits, &());
2120
2121 update.removed_repositories.sort_unstable();
2122 self.repository_entries.retain(|_, entry| {
2123 update
2124 .removed_repositories
2125 .binary_search(&entry.work_directory.to_proto())
2126 .is_err()
2127 });
2128
2129 for repository in update.updated_repositories {
2130 let work_directory_entry: WorkDirectoryEntry =
2131 ProjectEntryId::from_proto(repository.work_directory_id).into();
2132
2133 if let Some(entry) = self.entry_for_id(*work_directory_entry) {
2134 let work_directory = RepositoryWorkDirectory(entry.path.clone());
2135 if self.repository_entries.get(&work_directory).is_some() {
2136 self.repository_entries.update(&work_directory, |repo| {
2137 repo.branch = repository.branch.map(Into::into);
2138 });
2139 } else {
2140 self.repository_entries.insert(
2141 work_directory,
2142 RepositoryEntry {
2143 work_directory: work_directory_entry,
2144 branch: repository.branch.map(Into::into),
2145 // When syncing repository entries from a peer, we don't need
2146 // the location_in_repo field, since git operations don't happen locally
2147 // anyway.
2148 location_in_repo: None,
2149 },
2150 )
2151 }
2152 } else {
2153 log::error!("no work directory entry for repository {:?}", repository)
2154 }
2155 }
2156
2157 self.scan_id = update.scan_id as usize;
2158 if update.is_last_update {
2159 self.completed_scan_id = update.scan_id as usize;
2160 }
2161
2162 Ok(())
2163 }
2164
2165 pub fn entry_count(&self) -> usize {
2166 self.entries_by_path.summary().count
2167 }
2168
2169 pub fn visible_entry_count(&self) -> usize {
2170 self.entries_by_path.summary().non_ignored_count
2171 }
2172
2173 pub fn dir_count(&self) -> usize {
2174 let summary = self.entries_by_path.summary();
2175 summary.count - summary.file_count
2176 }
2177
2178 pub fn visible_dir_count(&self) -> usize {
2179 let summary = self.entries_by_path.summary();
2180 summary.non_ignored_count - summary.non_ignored_file_count
2181 }
2182
2183 pub fn file_count(&self) -> usize {
2184 self.entries_by_path.summary().file_count
2185 }
2186
2187 pub fn visible_file_count(&self) -> usize {
2188 self.entries_by_path.summary().non_ignored_file_count
2189 }
2190
2191 fn traverse_from_offset(
2192 &self,
2193 include_files: bool,
2194 include_dirs: bool,
2195 include_ignored: bool,
2196 start_offset: usize,
2197 ) -> Traversal {
2198 let mut cursor = self.entries_by_path.cursor(&());
2199 cursor.seek(
2200 &TraversalTarget::Count {
2201 count: start_offset,
2202 include_files,
2203 include_dirs,
2204 include_ignored,
2205 },
2206 Bias::Right,
2207 &(),
2208 );
2209 Traversal {
2210 cursor,
2211 include_files,
2212 include_dirs,
2213 include_ignored,
2214 }
2215 }
2216
2217 pub fn traverse_from_path(
2218 &self,
2219 include_files: bool,
2220 include_dirs: bool,
2221 include_ignored: bool,
2222 path: &Path,
2223 ) -> Traversal {
2224 Traversal::new(
2225 &self.entries_by_path,
2226 include_files,
2227 include_dirs,
2228 include_ignored,
2229 path,
2230 )
2231 }
2232
2233 pub fn files(&self, include_ignored: bool, start: usize) -> Traversal {
2234 self.traverse_from_offset(true, false, include_ignored, start)
2235 }
2236
2237 pub fn directories(&self, include_ignored: bool, start: usize) -> Traversal {
2238 self.traverse_from_offset(false, true, include_ignored, start)
2239 }
2240
2241 pub fn entries(&self, include_ignored: bool, start: usize) -> Traversal {
2242 self.traverse_from_offset(true, true, include_ignored, start)
2243 }
2244
2245 pub fn repositories(&self) -> impl Iterator<Item = (&Arc<Path>, &RepositoryEntry)> {
2246 self.repository_entries
2247 .iter()
2248 .map(|(path, entry)| (&path.0, entry))
2249 }
2250
2251 /// Get the repository whose work directory contains the given path.
2252 pub fn repository_for_work_directory(&self, path: &Path) -> Option<RepositoryEntry> {
2253 self.repository_entries
2254 .get(&RepositoryWorkDirectory(path.into()))
2255 .cloned()
2256 }
2257
2258 /// Get the repository whose work directory contains the given path.
2259 pub fn repository_for_path(&self, path: &Path) -> Option<RepositoryEntry> {
2260 self.repository_and_work_directory_for_path(path)
2261 .map(|e| e.1)
2262 }
2263
2264 pub fn repository_and_work_directory_for_path(
2265 &self,
2266 path: &Path,
2267 ) -> Option<(RepositoryWorkDirectory, RepositoryEntry)> {
2268 self.repository_entries
2269 .iter()
2270 .filter(|(workdir_path, _)| path.starts_with(workdir_path))
2271 .last()
2272 .map(|(path, repo)| (path.clone(), repo.clone()))
2273 }
2274
2275 /// Given an ordered iterator of entries, returns an iterator of those entries,
2276 /// along with their containing git repository.
2277 pub fn entries_with_repositories<'a>(
2278 &'a self,
2279 entries: impl 'a + Iterator<Item = &'a Entry>,
2280 ) -> impl 'a + Iterator<Item = (&'a Entry, Option<&'a RepositoryEntry>)> {
2281 let mut containing_repos = Vec::<(&Arc<Path>, &RepositoryEntry)>::new();
2282 let mut repositories = self.repositories().peekable();
2283 entries.map(move |entry| {
2284 while let Some((repo_path, _)) = containing_repos.last() {
2285 if entry.path.starts_with(repo_path) {
2286 break;
2287 } else {
2288 containing_repos.pop();
2289 }
2290 }
2291 while let Some((repo_path, _)) = repositories.peek() {
2292 if entry.path.starts_with(repo_path) {
2293 containing_repos.push(repositories.next().unwrap());
2294 } else {
2295 break;
2296 }
2297 }
2298 let repo = containing_repos.last().map(|(_, repo)| *repo);
2299 (entry, repo)
2300 })
2301 }
2302
2303 /// Updates the `git_status` of the given entries such that files'
2304 /// statuses bubble up to their ancestor directories.
2305 pub fn propagate_git_statuses(&self, result: &mut [Entry]) {
2306 let mut cursor = self
2307 .entries_by_path
2308 .cursor::<(TraversalProgress, GitStatuses)>(&());
2309 let mut entry_stack = Vec::<(usize, GitStatuses)>::new();
2310
2311 let mut result_ix = 0;
2312 loop {
2313 let next_entry = result.get(result_ix);
2314 let containing_entry = entry_stack.last().map(|(ix, _)| &result[*ix]);
2315
2316 let entry_to_finish = match (containing_entry, next_entry) {
2317 (Some(_), None) => entry_stack.pop(),
2318 (Some(containing_entry), Some(next_path)) => {
2319 if next_path.path.starts_with(&containing_entry.path) {
2320 None
2321 } else {
2322 entry_stack.pop()
2323 }
2324 }
2325 (None, Some(_)) => None,
2326 (None, None) => break,
2327 };
2328
2329 if let Some((entry_ix, prev_statuses)) = entry_to_finish {
2330 cursor.seek_forward(
2331 &TraversalTarget::PathSuccessor(&result[entry_ix].path),
2332 Bias::Left,
2333 &(),
2334 );
2335
2336 let statuses = cursor.start().1 - prev_statuses;
2337
2338 result[entry_ix].git_status = if statuses.conflict > 0 {
2339 Some(GitFileStatus::Conflict)
2340 } else if statuses.modified > 0 {
2341 Some(GitFileStatus::Modified)
2342 } else if statuses.added > 0 {
2343 Some(GitFileStatus::Added)
2344 } else {
2345 None
2346 };
2347 } else {
2348 if result[result_ix].is_dir() {
2349 cursor.seek_forward(
2350 &TraversalTarget::Path(&result[result_ix].path),
2351 Bias::Left,
2352 &(),
2353 );
2354 entry_stack.push((result_ix, cursor.start().1));
2355 }
2356 result_ix += 1;
2357 }
2358 }
2359 }
2360
2361 pub fn paths(&self) -> impl Iterator<Item = &Arc<Path>> {
2362 let empty_path = Path::new("");
2363 self.entries_by_path
2364 .cursor::<()>(&())
2365 .filter(move |entry| entry.path.as_ref() != empty_path)
2366 .map(|entry| &entry.path)
2367 }
2368
2369 pub fn child_entries<'a>(&'a self, parent_path: &'a Path) -> ChildEntriesIter<'a> {
2370 let mut cursor = self.entries_by_path.cursor(&());
2371 cursor.seek(&TraversalTarget::Path(parent_path), Bias::Right, &());
2372 let traversal = Traversal {
2373 cursor,
2374 include_files: true,
2375 include_dirs: true,
2376 include_ignored: true,
2377 };
2378 ChildEntriesIter {
2379 traversal,
2380 parent_path,
2381 }
2382 }
2383
2384 pub fn root_entry(&self) -> Option<&Entry> {
2385 self.entry_for_path("")
2386 }
2387
2388 pub fn root_name(&self) -> &str {
2389 &self.root_name
2390 }
2391
2392 pub fn root_git_entry(&self) -> Option<RepositoryEntry> {
2393 self.repository_entries
2394 .get(&RepositoryWorkDirectory(Path::new("").into()))
2395 .map(|entry| entry.to_owned())
2396 }
2397
2398 pub fn git_entries(&self) -> impl Iterator<Item = &RepositoryEntry> {
2399 self.repository_entries.values()
2400 }
2401
2402 pub fn scan_id(&self) -> usize {
2403 self.scan_id
2404 }
2405
2406 pub fn entry_for_path(&self, path: impl AsRef<Path>) -> Option<&Entry> {
2407 let path = path.as_ref();
2408 self.traverse_from_path(true, true, true, path)
2409 .entry()
2410 .and_then(|entry| {
2411 if entry.path.as_ref() == path {
2412 Some(entry)
2413 } else {
2414 None
2415 }
2416 })
2417 }
2418
2419 pub fn entry_for_id(&self, id: ProjectEntryId) -> Option<&Entry> {
2420 let entry = self.entries_by_id.get(&id, &())?;
2421 self.entry_for_path(&entry.path)
2422 }
2423
2424 pub fn inode_for_path(&self, path: impl AsRef<Path>) -> Option<u64> {
2425 self.entry_for_path(path.as_ref()).map(|e| e.inode)
2426 }
2427}
2428
2429impl LocalSnapshot {
2430 pub fn repo_for_path(&self, path: &Path) -> Option<(RepositoryEntry, &LocalRepositoryEntry)> {
2431 let (_, repo_entry) = self.repository_and_work_directory_for_path(path)?;
2432 let work_directory_id = repo_entry.work_directory_id();
2433 Some((repo_entry, self.git_repositories.get(&work_directory_id)?))
2434 }
2435
2436 fn build_update(
2437 &self,
2438 project_id: u64,
2439 worktree_id: u64,
2440 entry_changes: UpdatedEntriesSet,
2441 repo_changes: UpdatedGitRepositoriesSet,
2442 ) -> proto::UpdateWorktree {
2443 let mut updated_entries = Vec::new();
2444 let mut removed_entries = Vec::new();
2445 let mut updated_repositories = Vec::new();
2446 let mut removed_repositories = Vec::new();
2447
2448 for (_, entry_id, path_change) in entry_changes.iter() {
2449 if let PathChange::Removed = path_change {
2450 removed_entries.push(entry_id.0 as u64);
2451 } else if let Some(entry) = self.entry_for_id(*entry_id) {
2452 updated_entries.push(proto::Entry::from(entry));
2453 }
2454 }
2455
2456 for (work_dir_path, change) in repo_changes.iter() {
2457 let new_repo = self
2458 .repository_entries
2459 .get(&RepositoryWorkDirectory(work_dir_path.clone()));
2460 match (&change.old_repository, new_repo) {
2461 (Some(old_repo), Some(new_repo)) => {
2462 updated_repositories.push(new_repo.build_update(old_repo));
2463 }
2464 (None, Some(new_repo)) => {
2465 updated_repositories.push(proto::RepositoryEntry::from(new_repo));
2466 }
2467 (Some(old_repo), None) => {
2468 removed_repositories.push(old_repo.work_directory.0.to_proto());
2469 }
2470 _ => {}
2471 }
2472 }
2473
2474 removed_entries.sort_unstable();
2475 updated_entries.sort_unstable_by_key(|e| e.id);
2476 removed_repositories.sort_unstable();
2477 updated_repositories.sort_unstable_by_key(|e| e.work_directory_id);
2478
2479 // TODO - optimize, knowing that removed_entries are sorted.
2480 removed_entries.retain(|id| updated_entries.binary_search_by_key(id, |e| e.id).is_err());
2481
2482 proto::UpdateWorktree {
2483 project_id,
2484 worktree_id,
2485 abs_path: self.abs_path().to_string_lossy().into(),
2486 root_name: self.root_name().to_string(),
2487 updated_entries,
2488 removed_entries,
2489 scan_id: self.scan_id as u64,
2490 is_last_update: self.completed_scan_id == self.scan_id,
2491 updated_repositories,
2492 removed_repositories,
2493 }
2494 }
2495
2496 fn insert_entry(&mut self, mut entry: Entry, fs: &dyn Fs) -> Entry {
2497 if entry.is_file() && entry.path.file_name() == Some(&GITIGNORE) {
2498 let abs_path = self.abs_path.join(&entry.path);
2499 match smol::block_on(build_gitignore(&abs_path, fs)) {
2500 Ok(ignore) => {
2501 self.ignores_by_parent_abs_path
2502 .insert(abs_path.parent().unwrap().into(), (Arc::new(ignore), true));
2503 }
2504 Err(error) => {
2505 log::error!(
2506 "error loading .gitignore file {:?} - {:?}",
2507 &entry.path,
2508 error
2509 );
2510 }
2511 }
2512 }
2513
2514 if entry.kind == EntryKind::PendingDir {
2515 if let Some(existing_entry) =
2516 self.entries_by_path.get(&PathKey(entry.path.clone()), &())
2517 {
2518 entry.kind = existing_entry.kind;
2519 }
2520 }
2521
2522 let scan_id = self.scan_id;
2523 let removed = self.entries_by_path.insert_or_replace(entry.clone(), &());
2524 if let Some(removed) = removed {
2525 if removed.id != entry.id {
2526 self.entries_by_id.remove(&removed.id, &());
2527 }
2528 }
2529 self.entries_by_id.insert_or_replace(
2530 PathEntry {
2531 id: entry.id,
2532 path: entry.path.clone(),
2533 is_ignored: entry.is_ignored,
2534 scan_id,
2535 },
2536 &(),
2537 );
2538
2539 entry
2540 }
2541
2542 fn ancestor_inodes_for_path(&self, path: &Path) -> TreeSet<u64> {
2543 let mut inodes = TreeSet::default();
2544 for ancestor in path.ancestors().skip(1) {
2545 if let Some(entry) = self.entry_for_path(ancestor) {
2546 inodes.insert(entry.inode);
2547 }
2548 }
2549 inodes
2550 }
2551
2552 fn ignore_stack_for_abs_path(&self, abs_path: &Path, is_dir: bool) -> Arc<IgnoreStack> {
2553 let mut new_ignores = Vec::new();
2554 for (index, ancestor) in abs_path.ancestors().enumerate() {
2555 if index > 0 {
2556 if let Some((ignore, _)) = self.ignores_by_parent_abs_path.get(ancestor) {
2557 new_ignores.push((ancestor, Some(ignore.clone())));
2558 } else {
2559 new_ignores.push((ancestor, None));
2560 }
2561 }
2562 if ancestor.join(*DOT_GIT).is_dir() {
2563 break;
2564 }
2565 }
2566
2567 let mut ignore_stack = IgnoreStack::none();
2568 for (parent_abs_path, ignore) in new_ignores.into_iter().rev() {
2569 if ignore_stack.is_abs_path_ignored(parent_abs_path, true) {
2570 ignore_stack = IgnoreStack::all();
2571 break;
2572 } else if let Some(ignore) = ignore {
2573 ignore_stack = ignore_stack.append(parent_abs_path.into(), ignore);
2574 }
2575 }
2576
2577 if ignore_stack.is_abs_path_ignored(abs_path, is_dir) {
2578 ignore_stack = IgnoreStack::all();
2579 }
2580
2581 ignore_stack
2582 }
2583
2584 #[cfg(test)]
2585 pub(crate) fn expanded_entries(&self) -> impl Iterator<Item = &Entry> {
2586 self.entries_by_path
2587 .cursor::<()>(&())
2588 .filter(|entry| entry.kind == EntryKind::Dir && (entry.is_external || entry.is_ignored))
2589 }
2590
2591 #[cfg(test)]
2592 pub fn check_invariants(&self, git_state: bool) {
2593 use pretty_assertions::assert_eq;
2594
2595 assert_eq!(
2596 self.entries_by_path
2597 .cursor::<()>(&())
2598 .map(|e| (&e.path, e.id))
2599 .collect::<Vec<_>>(),
2600 self.entries_by_id
2601 .cursor::<()>(&())
2602 .map(|e| (&e.path, e.id))
2603 .collect::<collections::BTreeSet<_>>()
2604 .into_iter()
2605 .collect::<Vec<_>>(),
2606 "entries_by_path and entries_by_id are inconsistent"
2607 );
2608
2609 let mut files = self.files(true, 0);
2610 let mut visible_files = self.files(false, 0);
2611 for entry in self.entries_by_path.cursor::<()>(&()) {
2612 if entry.is_file() {
2613 assert_eq!(files.next().unwrap().inode, entry.inode);
2614 if !entry.is_ignored && !entry.is_external {
2615 assert_eq!(visible_files.next().unwrap().inode, entry.inode);
2616 }
2617 }
2618 }
2619
2620 assert!(files.next().is_none());
2621 assert!(visible_files.next().is_none());
2622
2623 let mut bfs_paths = Vec::new();
2624 let mut stack = self
2625 .root_entry()
2626 .map(|e| e.path.as_ref())
2627 .into_iter()
2628 .collect::<Vec<_>>();
2629 while let Some(path) = stack.pop() {
2630 bfs_paths.push(path);
2631 let ix = stack.len();
2632 for child_entry in self.child_entries(path) {
2633 stack.insert(ix, &child_entry.path);
2634 }
2635 }
2636
2637 let dfs_paths_via_iter = self
2638 .entries_by_path
2639 .cursor::<()>(&())
2640 .map(|e| e.path.as_ref())
2641 .collect::<Vec<_>>();
2642 assert_eq!(bfs_paths, dfs_paths_via_iter);
2643
2644 let dfs_paths_via_traversal = self
2645 .entries(true, 0)
2646 .map(|e| e.path.as_ref())
2647 .collect::<Vec<_>>();
2648 assert_eq!(dfs_paths_via_traversal, dfs_paths_via_iter);
2649
2650 if git_state {
2651 for ignore_parent_abs_path in self.ignores_by_parent_abs_path.keys() {
2652 let ignore_parent_path =
2653 ignore_parent_abs_path.strip_prefix(&self.abs_path).unwrap();
2654 assert!(self.entry_for_path(ignore_parent_path).is_some());
2655 assert!(self
2656 .entry_for_path(ignore_parent_path.join(*GITIGNORE))
2657 .is_some());
2658 }
2659 }
2660 }
2661
2662 #[cfg(test)]
2663 fn check_git_invariants(&self) {
2664 let dotgit_paths = self
2665 .git_repositories
2666 .iter()
2667 .map(|repo| repo.1.git_dir_path.clone())
2668 .collect::<HashSet<_>>();
2669 let work_dir_paths = self
2670 .repository_entries
2671 .iter()
2672 .map(|repo| repo.0.clone().0)
2673 .collect::<HashSet<_>>();
2674 assert_eq!(dotgit_paths.len(), work_dir_paths.len());
2675 assert_eq!(self.repository_entries.iter().count(), work_dir_paths.len());
2676 assert_eq!(self.git_repositories.iter().count(), work_dir_paths.len());
2677 for (_, entry) in self.repository_entries.iter() {
2678 self.git_repositories.get(&entry.work_directory).unwrap();
2679 }
2680 }
2681
2682 #[cfg(test)]
2683 pub fn entries_without_ids(&self, include_ignored: bool) -> Vec<(&Path, u64, bool)> {
2684 let mut paths = Vec::new();
2685 for entry in self.entries_by_path.cursor::<()>(&()) {
2686 if include_ignored || !entry.is_ignored {
2687 paths.push((entry.path.as_ref(), entry.inode, entry.is_ignored));
2688 }
2689 }
2690 paths.sort_by(|a, b| a.0.cmp(b.0));
2691 paths
2692 }
2693}
2694
2695impl BackgroundScannerState {
2696 fn should_scan_directory(&self, entry: &Entry) -> bool {
2697 (!entry.is_external && !entry.is_ignored)
2698 || entry.path.file_name() == Some(*DOT_GIT)
2699 || entry.path.file_name() == Some(local_settings_folder_relative_path().as_os_str())
2700 || self.scanned_dirs.contains(&entry.id) // If we've ever scanned it, keep scanning
2701 || self
2702 .paths_to_scan
2703 .iter()
2704 .any(|p| p.starts_with(&entry.path))
2705 || self
2706 .path_prefixes_to_scan
2707 .iter()
2708 .any(|p| entry.path.starts_with(p))
2709 }
2710
2711 fn enqueue_scan_dir(&self, abs_path: Arc<Path>, entry: &Entry, scan_job_tx: &Sender<ScanJob>) {
2712 let path = entry.path.clone();
2713 let ignore_stack = self.snapshot.ignore_stack_for_abs_path(&abs_path, true);
2714 let mut ancestor_inodes = self.snapshot.ancestor_inodes_for_path(&path);
2715 let mut containing_repository = None;
2716 if !ignore_stack.is_abs_path_ignored(&abs_path, true) {
2717 if let Some((repo_entry, repo)) = self.snapshot.repo_for_path(&path) {
2718 if let Some(workdir_path) = repo_entry.work_directory(&self.snapshot) {
2719 if let Ok(repo_path) = repo_entry.relativize(&self.snapshot, &path) {
2720 containing_repository = Some(ScanJobContainingRepository {
2721 work_directory: workdir_path,
2722 statuses: repo
2723 .repo_ptr
2724 .status(&[repo_path.0])
2725 .log_err()
2726 .unwrap_or_default(),
2727 });
2728 }
2729 }
2730 }
2731 }
2732 if !ancestor_inodes.contains(&entry.inode) {
2733 ancestor_inodes.insert(entry.inode);
2734 scan_job_tx
2735 .try_send(ScanJob {
2736 abs_path,
2737 path,
2738 ignore_stack,
2739 scan_queue: scan_job_tx.clone(),
2740 ancestor_inodes,
2741 is_external: entry.is_external,
2742 containing_repository,
2743 })
2744 .unwrap();
2745 }
2746 }
2747
2748 fn reuse_entry_id(&mut self, entry: &mut Entry) {
2749 if let Some(mtime) = entry.mtime {
2750 // If an entry with the same inode was removed from the worktree during this scan,
2751 // then it *might* represent the same file or directory. But the OS might also have
2752 // re-used the inode for a completely different file or directory.
2753 //
2754 // Conditionally reuse the old entry's id:
2755 // * if the mtime is the same, the file was probably been renamed.
2756 // * if the path is the same, the file may just have been updated
2757 if let Some(removed_entry) = self.removed_entries.remove(&entry.inode) {
2758 if removed_entry.mtime == Some(mtime) || removed_entry.path == entry.path {
2759 entry.id = removed_entry.id;
2760 }
2761 } else if let Some(existing_entry) = self.snapshot.entry_for_path(&entry.path) {
2762 entry.id = existing_entry.id;
2763 }
2764 }
2765 }
2766
2767 fn insert_entry(&mut self, mut entry: Entry, fs: &dyn Fs) -> Entry {
2768 self.reuse_entry_id(&mut entry);
2769 let entry = self.snapshot.insert_entry(entry, fs);
2770 if entry.path.file_name() == Some(&DOT_GIT) {
2771 self.build_git_repository(entry.path.clone(), fs);
2772 }
2773
2774 #[cfg(test)]
2775 self.snapshot.check_invariants(false);
2776
2777 entry
2778 }
2779
2780 fn populate_dir(
2781 &mut self,
2782 parent_path: &Arc<Path>,
2783 entries: impl IntoIterator<Item = Entry>,
2784 ignore: Option<Arc<Gitignore>>,
2785 ) {
2786 let mut parent_entry = if let Some(parent_entry) = self
2787 .snapshot
2788 .entries_by_path
2789 .get(&PathKey(parent_path.clone()), &())
2790 {
2791 parent_entry.clone()
2792 } else {
2793 log::warn!(
2794 "populating a directory {:?} that has been removed",
2795 parent_path
2796 );
2797 return;
2798 };
2799
2800 match parent_entry.kind {
2801 EntryKind::PendingDir | EntryKind::UnloadedDir => parent_entry.kind = EntryKind::Dir,
2802 EntryKind::Dir => {}
2803 _ => return,
2804 }
2805
2806 if let Some(ignore) = ignore {
2807 let abs_parent_path = self.snapshot.abs_path.join(parent_path).into();
2808 self.snapshot
2809 .ignores_by_parent_abs_path
2810 .insert(abs_parent_path, (ignore, false));
2811 }
2812
2813 let parent_entry_id = parent_entry.id;
2814 self.scanned_dirs.insert(parent_entry_id);
2815 let mut entries_by_path_edits = vec![Edit::Insert(parent_entry)];
2816 let mut entries_by_id_edits = Vec::new();
2817
2818 for entry in entries {
2819 entries_by_id_edits.push(Edit::Insert(PathEntry {
2820 id: entry.id,
2821 path: entry.path.clone(),
2822 is_ignored: entry.is_ignored,
2823 scan_id: self.snapshot.scan_id,
2824 }));
2825 entries_by_path_edits.push(Edit::Insert(entry));
2826 }
2827
2828 self.snapshot
2829 .entries_by_path
2830 .edit(entries_by_path_edits, &());
2831 self.snapshot.entries_by_id.edit(entries_by_id_edits, &());
2832
2833 if let Err(ix) = self.changed_paths.binary_search(parent_path) {
2834 self.changed_paths.insert(ix, parent_path.clone());
2835 }
2836
2837 #[cfg(test)]
2838 self.snapshot.check_invariants(false);
2839 }
2840
2841 fn remove_path(&mut self, path: &Path) {
2842 let mut new_entries;
2843 let removed_entries;
2844 {
2845 let mut cursor = self
2846 .snapshot
2847 .entries_by_path
2848 .cursor::<TraversalProgress>(&());
2849 new_entries = cursor.slice(&TraversalTarget::Path(path), Bias::Left, &());
2850 removed_entries = cursor.slice(&TraversalTarget::PathSuccessor(path), Bias::Left, &());
2851 new_entries.append(cursor.suffix(&()), &());
2852 }
2853 self.snapshot.entries_by_path = new_entries;
2854
2855 let mut removed_ids = Vec::with_capacity(removed_entries.summary().count);
2856 for entry in removed_entries.cursor::<()>(&()) {
2857 match self.removed_entries.entry(entry.inode) {
2858 hash_map::Entry::Occupied(mut e) => {
2859 let prev_removed_entry = e.get_mut();
2860 if entry.id > prev_removed_entry.id {
2861 *prev_removed_entry = entry.clone();
2862 }
2863 }
2864 hash_map::Entry::Vacant(e) => {
2865 e.insert(entry.clone());
2866 }
2867 }
2868
2869 if entry.path.file_name() == Some(&GITIGNORE) {
2870 let abs_parent_path = self.snapshot.abs_path.join(entry.path.parent().unwrap());
2871 if let Some((_, needs_update)) = self
2872 .snapshot
2873 .ignores_by_parent_abs_path
2874 .get_mut(abs_parent_path.as_path())
2875 {
2876 *needs_update = true;
2877 }
2878 }
2879
2880 if let Err(ix) = removed_ids.binary_search(&entry.id) {
2881 removed_ids.insert(ix, entry.id);
2882 }
2883 }
2884
2885 self.snapshot.entries_by_id.edit(
2886 removed_ids.iter().map(|&id| Edit::Remove(id)).collect(),
2887 &(),
2888 );
2889 self.snapshot
2890 .git_repositories
2891 .retain(|id, _| removed_ids.binary_search(id).is_err());
2892 self.snapshot
2893 .repository_entries
2894 .retain(|repo_path, _| !repo_path.0.starts_with(path));
2895
2896 #[cfg(test)]
2897 self.snapshot.check_invariants(false);
2898 }
2899
2900 fn build_git_repository(
2901 &mut self,
2902 dot_git_path: Arc<Path>,
2903 fs: &dyn Fs,
2904 ) -> Option<(RepositoryWorkDirectory, Arc<dyn GitRepository>)> {
2905 let work_dir_path: Arc<Path> = match dot_git_path.parent() {
2906 Some(parent_dir) => {
2907 // Guard against repositories inside the repository metadata
2908 if parent_dir.iter().any(|component| component == *DOT_GIT) {
2909 log::info!(
2910 "not building git repository for nested `.git` directory, `.git` path in the worktree: {dot_git_path:?}"
2911 );
2912 return None;
2913 };
2914 log::info!(
2915 "building git repository, `.git` path in the worktree: {dot_git_path:?}"
2916 );
2917
2918 parent_dir.into()
2919 }
2920 None => {
2921 // `dot_git_path.parent().is_none()` means `.git` directory is the opened worktree itself,
2922 // no files inside that directory are tracked by git, so no need to build the repo around it
2923 log::info!(
2924 "not building git repository for the worktree itself, `.git` path in the worktree: {dot_git_path:?}"
2925 );
2926 return None;
2927 }
2928 };
2929
2930 self.build_git_repository_for_path(work_dir_path, dot_git_path, None, fs)
2931 }
2932
2933 fn build_git_repository_for_path(
2934 &mut self,
2935 work_dir_path: Arc<Path>,
2936 dot_git_path: Arc<Path>,
2937 location_in_repo: Option<Arc<Path>>,
2938 fs: &dyn Fs,
2939 ) -> Option<(RepositoryWorkDirectory, Arc<dyn GitRepository>)> {
2940 let work_dir_id = self
2941 .snapshot
2942 .entry_for_path(work_dir_path.clone())
2943 .map(|entry| entry.id)?;
2944
2945 if self.snapshot.git_repositories.get(&work_dir_id).is_some() {
2946 return None;
2947 }
2948
2949 let abs_path = self.snapshot.abs_path.join(&dot_git_path);
2950 let t0 = Instant::now();
2951 let repository = fs.open_repo(&abs_path)?;
2952 log::trace!("constructed libgit2 repo in {:?}", t0.elapsed());
2953 let work_directory = RepositoryWorkDirectory(work_dir_path.clone());
2954
2955 self.snapshot.repository_entries.insert(
2956 work_directory.clone(),
2957 RepositoryEntry {
2958 work_directory: work_dir_id.into(),
2959 branch: repository.branch_name().map(Into::into),
2960 location_in_repo,
2961 },
2962 );
2963 self.snapshot.git_repositories.insert(
2964 work_dir_id,
2965 LocalRepositoryEntry {
2966 git_dir_scan_id: 0,
2967 repo_ptr: repository.clone(),
2968 git_dir_path: dot_git_path.clone(),
2969 },
2970 );
2971
2972 Some((work_directory, repository))
2973 }
2974}
2975
2976async fn build_gitignore(abs_path: &Path, fs: &dyn Fs) -> Result<Gitignore> {
2977 let contents = fs.load(abs_path).await?;
2978 let parent = abs_path.parent().unwrap_or_else(|| Path::new("/"));
2979 let mut builder = GitignoreBuilder::new(parent);
2980 for line in contents.lines() {
2981 builder.add_line(Some(abs_path.into()), line)?;
2982 }
2983 Ok(builder.build()?)
2984}
2985
2986impl Deref for Worktree {
2987 type Target = Snapshot;
2988
2989 fn deref(&self) -> &Self::Target {
2990 match self {
2991 Worktree::Local(worktree) => &worktree.snapshot,
2992 Worktree::Remote(worktree) => &worktree.snapshot,
2993 }
2994 }
2995}
2996
2997impl Deref for LocalWorktree {
2998 type Target = LocalSnapshot;
2999
3000 fn deref(&self) -> &Self::Target {
3001 &self.snapshot
3002 }
3003}
3004
3005impl Deref for RemoteWorktree {
3006 type Target = Snapshot;
3007
3008 fn deref(&self) -> &Self::Target {
3009 &self.snapshot
3010 }
3011}
3012
3013impl fmt::Debug for LocalWorktree {
3014 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3015 self.snapshot.fmt(f)
3016 }
3017}
3018
3019impl fmt::Debug for Snapshot {
3020 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3021 struct EntriesById<'a>(&'a SumTree<PathEntry>);
3022 struct EntriesByPath<'a>(&'a SumTree<Entry>);
3023
3024 impl<'a> fmt::Debug for EntriesByPath<'a> {
3025 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3026 f.debug_map()
3027 .entries(self.0.iter().map(|entry| (&entry.path, entry.id)))
3028 .finish()
3029 }
3030 }
3031
3032 impl<'a> fmt::Debug for EntriesById<'a> {
3033 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3034 f.debug_list().entries(self.0.iter()).finish()
3035 }
3036 }
3037
3038 f.debug_struct("Snapshot")
3039 .field("id", &self.id)
3040 .field("root_name", &self.root_name)
3041 .field("entries_by_path", &EntriesByPath(&self.entries_by_path))
3042 .field("entries_by_id", &EntriesById(&self.entries_by_id))
3043 .finish()
3044 }
3045}
3046
3047#[derive(Clone, PartialEq)]
3048pub struct File {
3049 pub worktree: Model<Worktree>,
3050 pub path: Arc<Path>,
3051 pub mtime: Option<SystemTime>,
3052 pub entry_id: Option<ProjectEntryId>,
3053 pub is_local: bool,
3054 pub is_deleted: bool,
3055 pub is_private: bool,
3056}
3057
3058impl language::File for File {
3059 fn as_local(&self) -> Option<&dyn language::LocalFile> {
3060 if self.is_local {
3061 Some(self)
3062 } else {
3063 None
3064 }
3065 }
3066
3067 fn mtime(&self) -> Option<SystemTime> {
3068 self.mtime
3069 }
3070
3071 fn path(&self) -> &Arc<Path> {
3072 &self.path
3073 }
3074
3075 fn full_path(&self, cx: &AppContext) -> PathBuf {
3076 let mut full_path = PathBuf::new();
3077 let worktree = self.worktree.read(cx);
3078
3079 if worktree.is_visible() {
3080 full_path.push(worktree.root_name());
3081 } else {
3082 let path = worktree.abs_path();
3083
3084 if worktree.is_local() && path.starts_with(home_dir().as_path()) {
3085 full_path.push("~");
3086 full_path.push(path.strip_prefix(home_dir().as_path()).unwrap());
3087 } else {
3088 full_path.push(path)
3089 }
3090 }
3091
3092 if self.path.components().next().is_some() {
3093 full_path.push(&self.path);
3094 }
3095
3096 full_path
3097 }
3098
3099 /// Returns the last component of this handle's absolute path. If this handle refers to the root
3100 /// of its worktree, then this method will return the name of the worktree itself.
3101 fn file_name<'a>(&'a self, cx: &'a AppContext) -> &'a OsStr {
3102 self.path
3103 .file_name()
3104 .unwrap_or_else(|| OsStr::new(&self.worktree.read(cx).root_name))
3105 }
3106
3107 fn worktree_id(&self, cx: &AppContext) -> WorktreeId {
3108 self.worktree.read(cx).id()
3109 }
3110
3111 fn is_deleted(&self) -> bool {
3112 self.is_deleted
3113 }
3114
3115 fn as_any(&self) -> &dyn Any {
3116 self
3117 }
3118
3119 fn to_proto(&self, cx: &AppContext) -> rpc::proto::File {
3120 rpc::proto::File {
3121 worktree_id: self.worktree.read(cx).id().to_proto(),
3122 entry_id: self.entry_id.map(|id| id.to_proto()),
3123 path: self.path.to_string_lossy().into(),
3124 mtime: self.mtime.map(|time| time.into()),
3125 is_deleted: self.is_deleted,
3126 }
3127 }
3128
3129 fn is_private(&self) -> bool {
3130 self.is_private
3131 }
3132}
3133
3134impl language::LocalFile for File {
3135 fn abs_path(&self, cx: &AppContext) -> PathBuf {
3136 let worktree_path = &self.worktree.read(cx).as_local().unwrap().abs_path;
3137 if self.path.as_ref() == Path::new("") {
3138 worktree_path.to_path_buf()
3139 } else {
3140 worktree_path.join(&self.path)
3141 }
3142 }
3143
3144 fn load(&self, cx: &AppContext) -> Task<Result<String>> {
3145 let worktree = self.worktree.read(cx).as_local().unwrap();
3146 let abs_path = worktree.absolutize(&self.path);
3147 let fs = worktree.fs.clone();
3148 cx.background_executor()
3149 .spawn(async move { fs.load(&abs_path?).await })
3150 }
3151}
3152
3153impl File {
3154 pub fn for_entry(entry: Entry, worktree: Model<Worktree>) -> Arc<Self> {
3155 Arc::new(Self {
3156 worktree,
3157 path: entry.path.clone(),
3158 mtime: entry.mtime,
3159 entry_id: Some(entry.id),
3160 is_local: true,
3161 is_deleted: false,
3162 is_private: entry.is_private,
3163 })
3164 }
3165
3166 pub fn from_proto(
3167 proto: rpc::proto::File,
3168 worktree: Model<Worktree>,
3169 cx: &AppContext,
3170 ) -> Result<Self> {
3171 let worktree_id = worktree
3172 .read(cx)
3173 .as_remote()
3174 .ok_or_else(|| anyhow!("not remote"))?
3175 .id();
3176
3177 if worktree_id.to_proto() != proto.worktree_id {
3178 return Err(anyhow!("worktree id does not match file"));
3179 }
3180
3181 Ok(Self {
3182 worktree,
3183 path: Path::new(&proto.path).into(),
3184 mtime: proto.mtime.map(|time| time.into()),
3185 entry_id: proto.entry_id.map(ProjectEntryId::from_proto),
3186 is_local: false,
3187 is_deleted: proto.is_deleted,
3188 is_private: false,
3189 })
3190 }
3191
3192 pub fn from_dyn(file: Option<&Arc<dyn language::File>>) -> Option<&Self> {
3193 file.and_then(|f| f.as_any().downcast_ref())
3194 }
3195
3196 pub fn worktree_id(&self, cx: &AppContext) -> WorktreeId {
3197 self.worktree.read(cx).id()
3198 }
3199
3200 pub fn project_entry_id(&self, _: &AppContext) -> Option<ProjectEntryId> {
3201 if self.is_deleted {
3202 None
3203 } else {
3204 self.entry_id
3205 }
3206 }
3207}
3208
3209#[derive(Clone, Debug, PartialEq, Eq, Hash)]
3210pub struct Entry {
3211 pub id: ProjectEntryId,
3212 pub kind: EntryKind,
3213 pub path: Arc<Path>,
3214 pub inode: u64,
3215 pub mtime: Option<SystemTime>,
3216
3217 pub canonical_path: Option<Box<Path>>,
3218 pub is_symlink: bool,
3219 /// Whether this entry is ignored by Git.
3220 ///
3221 /// We only scan ignored entries once the directory is expanded and
3222 /// exclude them from searches.
3223 pub is_ignored: bool,
3224
3225 /// Whether this entry's canonical path is outside of the worktree.
3226 /// This means the entry is only accessible from the worktree root via a
3227 /// symlink.
3228 ///
3229 /// We only scan entries outside of the worktree once the symlinked
3230 /// directory is expanded. External entries are treated like gitignored
3231 /// entries in that they are not included in searches.
3232 pub is_external: bool,
3233 pub git_status: Option<GitFileStatus>,
3234 /// Whether this entry is considered to be a `.env` file.
3235 pub is_private: bool,
3236 /// The entry's size on disk, in bytes.
3237 pub size: u64,
3238 pub char_bag: CharBag,
3239 pub is_fifo: bool,
3240}
3241
3242#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
3243pub enum EntryKind {
3244 UnloadedDir,
3245 PendingDir,
3246 Dir,
3247 File,
3248}
3249
3250#[derive(Clone, Copy, Debug, PartialEq)]
3251pub enum PathChange {
3252 /// A filesystem entry was was created.
3253 Added,
3254 /// A filesystem entry was removed.
3255 Removed,
3256 /// A filesystem entry was updated.
3257 Updated,
3258 /// A filesystem entry was either updated or added. We don't know
3259 /// whether or not it already existed, because the path had not
3260 /// been loaded before the event.
3261 AddedOrUpdated,
3262 /// A filesystem entry was found during the initial scan of the worktree.
3263 Loaded,
3264}
3265
3266pub struct GitRepositoryChange {
3267 /// The previous state of the repository, if it already existed.
3268 pub old_repository: Option<RepositoryEntry>,
3269}
3270
3271pub type UpdatedEntriesSet = Arc<[(Arc<Path>, ProjectEntryId, PathChange)]>;
3272pub type UpdatedGitRepositoriesSet = Arc<[(Arc<Path>, GitRepositoryChange)]>;
3273
3274impl Entry {
3275 fn new(
3276 path: Arc<Path>,
3277 metadata: &fs::Metadata,
3278 next_entry_id: &AtomicUsize,
3279 root_char_bag: CharBag,
3280 canonical_path: Option<Box<Path>>,
3281 ) -> Self {
3282 let char_bag = char_bag_for_path(root_char_bag, &path);
3283 Self {
3284 id: ProjectEntryId::new(next_entry_id),
3285 kind: if metadata.is_dir {
3286 EntryKind::PendingDir
3287 } else {
3288 EntryKind::File
3289 },
3290 path,
3291 inode: metadata.inode,
3292 mtime: Some(metadata.mtime),
3293 size: metadata.len,
3294 canonical_path,
3295 is_symlink: metadata.is_symlink,
3296 is_ignored: false,
3297 is_external: false,
3298 is_private: false,
3299 git_status: None,
3300 char_bag,
3301 is_fifo: metadata.is_fifo,
3302 }
3303 }
3304
3305 pub fn is_created(&self) -> bool {
3306 self.mtime.is_some()
3307 }
3308
3309 pub fn is_dir(&self) -> bool {
3310 self.kind.is_dir()
3311 }
3312
3313 pub fn is_file(&self) -> bool {
3314 self.kind.is_file()
3315 }
3316
3317 pub fn git_status(&self) -> Option<GitFileStatus> {
3318 self.git_status
3319 }
3320}
3321
3322impl EntryKind {
3323 pub fn is_dir(&self) -> bool {
3324 matches!(
3325 self,
3326 EntryKind::Dir | EntryKind::PendingDir | EntryKind::UnloadedDir
3327 )
3328 }
3329
3330 pub fn is_unloaded(&self) -> bool {
3331 matches!(self, EntryKind::UnloadedDir)
3332 }
3333
3334 pub fn is_file(&self) -> bool {
3335 matches!(self, EntryKind::File)
3336 }
3337}
3338
3339impl sum_tree::Item for Entry {
3340 type Summary = EntrySummary;
3341
3342 fn summary(&self, _cx: &()) -> Self::Summary {
3343 let non_ignored_count = if self.is_ignored || self.is_external {
3344 0
3345 } else {
3346 1
3347 };
3348 let file_count;
3349 let non_ignored_file_count;
3350 if self.is_file() {
3351 file_count = 1;
3352 non_ignored_file_count = non_ignored_count;
3353 } else {
3354 file_count = 0;
3355 non_ignored_file_count = 0;
3356 }
3357
3358 let mut statuses = GitStatuses::default();
3359 if let Some(status) = self.git_status {
3360 match status {
3361 GitFileStatus::Added => statuses.added = 1,
3362 GitFileStatus::Modified => statuses.modified = 1,
3363 GitFileStatus::Conflict => statuses.conflict = 1,
3364 }
3365 }
3366
3367 EntrySummary {
3368 max_path: self.path.clone(),
3369 count: 1,
3370 non_ignored_count,
3371 file_count,
3372 non_ignored_file_count,
3373 statuses,
3374 }
3375 }
3376}
3377
3378impl sum_tree::KeyedItem for Entry {
3379 type Key = PathKey;
3380
3381 fn key(&self) -> Self::Key {
3382 PathKey(self.path.clone())
3383 }
3384}
3385
3386#[derive(Clone, Debug)]
3387pub struct EntrySummary {
3388 max_path: Arc<Path>,
3389 count: usize,
3390 non_ignored_count: usize,
3391 file_count: usize,
3392 non_ignored_file_count: usize,
3393 statuses: GitStatuses,
3394}
3395
3396impl Default for EntrySummary {
3397 fn default() -> Self {
3398 Self {
3399 max_path: Arc::from(Path::new("")),
3400 count: 0,
3401 non_ignored_count: 0,
3402 file_count: 0,
3403 non_ignored_file_count: 0,
3404 statuses: Default::default(),
3405 }
3406 }
3407}
3408
3409impl sum_tree::Summary for EntrySummary {
3410 type Context = ();
3411
3412 fn zero(_cx: &()) -> Self {
3413 Default::default()
3414 }
3415
3416 fn add_summary(&mut self, rhs: &Self, _: &()) {
3417 self.max_path = rhs.max_path.clone();
3418 self.count += rhs.count;
3419 self.non_ignored_count += rhs.non_ignored_count;
3420 self.file_count += rhs.file_count;
3421 self.non_ignored_file_count += rhs.non_ignored_file_count;
3422 self.statuses += rhs.statuses;
3423 }
3424}
3425
3426#[derive(Clone, Debug)]
3427struct PathEntry {
3428 id: ProjectEntryId,
3429 path: Arc<Path>,
3430 is_ignored: bool,
3431 scan_id: usize,
3432}
3433
3434impl sum_tree::Item for PathEntry {
3435 type Summary = PathEntrySummary;
3436
3437 fn summary(&self, _cx: &()) -> Self::Summary {
3438 PathEntrySummary { max_id: self.id }
3439 }
3440}
3441
3442impl sum_tree::KeyedItem for PathEntry {
3443 type Key = ProjectEntryId;
3444
3445 fn key(&self) -> Self::Key {
3446 self.id
3447 }
3448}
3449
3450#[derive(Clone, Debug, Default)]
3451struct PathEntrySummary {
3452 max_id: ProjectEntryId,
3453}
3454
3455impl sum_tree::Summary for PathEntrySummary {
3456 type Context = ();
3457
3458 fn zero(_cx: &Self::Context) -> Self {
3459 Default::default()
3460 }
3461
3462 fn add_summary(&mut self, summary: &Self, _: &Self::Context) {
3463 self.max_id = summary.max_id;
3464 }
3465}
3466
3467impl<'a> sum_tree::Dimension<'a, PathEntrySummary> for ProjectEntryId {
3468 fn zero(_cx: &()) -> Self {
3469 Default::default()
3470 }
3471
3472 fn add_summary(&mut self, summary: &'a PathEntrySummary, _: &()) {
3473 *self = summary.max_id;
3474 }
3475}
3476
3477#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
3478pub struct PathKey(Arc<Path>);
3479
3480impl Default for PathKey {
3481 fn default() -> Self {
3482 Self(Path::new("").into())
3483 }
3484}
3485
3486impl<'a> sum_tree::Dimension<'a, EntrySummary> for PathKey {
3487 fn zero(_cx: &()) -> Self {
3488 Default::default()
3489 }
3490
3491 fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
3492 self.0 = summary.max_path.clone();
3493 }
3494}
3495
3496struct BackgroundScanner {
3497 state: Mutex<BackgroundScannerState>,
3498 fs: Arc<dyn Fs>,
3499 fs_case_sensitive: bool,
3500 status_updates_tx: UnboundedSender<ScanState>,
3501 executor: BackgroundExecutor,
3502 scan_requests_rx: channel::Receiver<ScanRequest>,
3503 path_prefixes_to_scan_rx: channel::Receiver<Arc<Path>>,
3504 next_entry_id: Arc<AtomicUsize>,
3505 phase: BackgroundScannerPhase,
3506 watcher: Arc<dyn Watcher>,
3507 settings: WorktreeSettings,
3508 share_private_files: bool,
3509}
3510
3511#[derive(PartialEq)]
3512enum BackgroundScannerPhase {
3513 InitialScan,
3514 EventsReceivedDuringInitialScan,
3515 Events,
3516}
3517
3518impl BackgroundScanner {
3519 async fn run(&mut self, mut fs_events_rx: Pin<Box<dyn Send + Stream<Item = Vec<PathEvent>>>>) {
3520 use futures::FutureExt as _;
3521
3522 // If the worktree root does not contain a git repository, then find
3523 // the git repository in an ancestor directory. Find any gitignore files
3524 // in ancestor directories.
3525 let root_abs_path = self.state.lock().snapshot.abs_path.clone();
3526 for (index, ancestor) in root_abs_path.ancestors().enumerate() {
3527 if index != 0 {
3528 if let Ok(ignore) =
3529 build_gitignore(&ancestor.join(*GITIGNORE), self.fs.as_ref()).await
3530 {
3531 self.state
3532 .lock()
3533 .snapshot
3534 .ignores_by_parent_abs_path
3535 .insert(ancestor.into(), (ignore.into(), false));
3536 }
3537 }
3538
3539 let ancestor_dot_git = ancestor.join(*DOT_GIT);
3540 if ancestor_dot_git.is_dir() {
3541 if index != 0 {
3542 // We canonicalize, since the FS events use the canonicalized path.
3543 if let Some(ancestor_dot_git) =
3544 self.fs.canonicalize(&ancestor_dot_git).await.log_err()
3545 {
3546 let (ancestor_git_events, _) =
3547 self.fs.watch(&ancestor_dot_git, FS_WATCH_LATENCY).await;
3548 fs_events_rx = select(fs_events_rx, ancestor_git_events).boxed();
3549
3550 // We associate the external git repo with our root folder and
3551 // also mark where in the git repo the root folder is located.
3552 self.state.lock().build_git_repository_for_path(
3553 Path::new("").into(),
3554 ancestor_dot_git.into(),
3555 Some(root_abs_path.strip_prefix(ancestor).unwrap().into()),
3556 self.fs.as_ref(),
3557 );
3558 };
3559 }
3560
3561 // Reached root of git repository.
3562 break;
3563 }
3564 }
3565
3566 let (scan_job_tx, scan_job_rx) = channel::unbounded();
3567 {
3568 let mut state = self.state.lock();
3569 state.snapshot.scan_id += 1;
3570 if let Some(mut root_entry) = state.snapshot.root_entry().cloned() {
3571 let ignore_stack = state
3572 .snapshot
3573 .ignore_stack_for_abs_path(&root_abs_path, true);
3574 if ignore_stack.is_abs_path_ignored(&root_abs_path, true) {
3575 root_entry.is_ignored = true;
3576 state.insert_entry(root_entry.clone(), self.fs.as_ref());
3577 }
3578 state.enqueue_scan_dir(root_abs_path, &root_entry, &scan_job_tx);
3579 }
3580 };
3581
3582 // Perform an initial scan of the directory.
3583 drop(scan_job_tx);
3584 self.scan_dirs(true, scan_job_rx).await;
3585 {
3586 let mut state = self.state.lock();
3587 state.snapshot.completed_scan_id = state.snapshot.scan_id;
3588 }
3589
3590 self.send_status_update(false, SmallVec::new());
3591
3592 // Process any any FS events that occurred while performing the initial scan.
3593 // For these events, update events cannot be as precise, because we didn't
3594 // have the previous state loaded yet.
3595 self.phase = BackgroundScannerPhase::EventsReceivedDuringInitialScan;
3596 if let Poll::Ready(Some(mut paths)) = futures::poll!(fs_events_rx.next()) {
3597 while let Poll::Ready(Some(more_paths)) = futures::poll!(fs_events_rx.next()) {
3598 paths.extend(more_paths);
3599 }
3600 self.process_events(paths.into_iter().map(Into::into).collect())
3601 .await;
3602 }
3603
3604 // Continue processing events until the worktree is dropped.
3605 self.phase = BackgroundScannerPhase::Events;
3606
3607 loop {
3608 select_biased! {
3609 // Process any path refresh requests from the worktree. Prioritize
3610 // these before handling changes reported by the filesystem.
3611 request = self.next_scan_request().fuse() => {
3612 let Ok(request) = request else { break };
3613 if !self.process_scan_request(request, false).await {
3614 return;
3615 }
3616 }
3617
3618 path_prefix = self.path_prefixes_to_scan_rx.recv().fuse() => {
3619 let Ok(path_prefix) = path_prefix else { break };
3620 log::trace!("adding path prefix {:?}", path_prefix);
3621
3622 let did_scan = self.forcibly_load_paths(&[path_prefix.clone()]).await;
3623 if did_scan {
3624 let abs_path =
3625 {
3626 let mut state = self.state.lock();
3627 state.path_prefixes_to_scan.insert(path_prefix.clone());
3628 state.snapshot.abs_path.join(&path_prefix)
3629 };
3630
3631 if let Some(abs_path) = self.fs.canonicalize(&abs_path).await.log_err() {
3632 self.process_events(vec![abs_path]).await;
3633 }
3634 }
3635 }
3636
3637 paths = fs_events_rx.next().fuse() => {
3638 let Some(mut paths) = paths else { break };
3639 while let Poll::Ready(Some(more_paths)) = futures::poll!(fs_events_rx.next()) {
3640 paths.extend(more_paths);
3641 }
3642 self.process_events(paths.into_iter().map(Into::into).collect()).await;
3643 }
3644 }
3645 }
3646 }
3647
3648 async fn process_scan_request(&self, mut request: ScanRequest, scanning: bool) -> bool {
3649 log::debug!("rescanning paths {:?}", request.relative_paths);
3650
3651 request.relative_paths.sort_unstable();
3652 self.forcibly_load_paths(&request.relative_paths).await;
3653
3654 let root_path = self.state.lock().snapshot.abs_path.clone();
3655 let root_canonical_path = match self.fs.canonicalize(&root_path).await {
3656 Ok(path) => path,
3657 Err(err) => {
3658 log::error!("failed to canonicalize root path: {}", err);
3659 return true;
3660 }
3661 };
3662 let abs_paths = request
3663 .relative_paths
3664 .iter()
3665 .map(|path| {
3666 if path.file_name().is_some() {
3667 root_canonical_path.join(path)
3668 } else {
3669 root_canonical_path.clone()
3670 }
3671 })
3672 .collect::<Vec<_>>();
3673
3674 {
3675 let mut state = self.state.lock();
3676 let is_idle = state.snapshot.completed_scan_id == state.snapshot.scan_id;
3677 state.snapshot.scan_id += 1;
3678 if is_idle {
3679 state.snapshot.completed_scan_id = state.snapshot.scan_id;
3680 }
3681 }
3682
3683 self.reload_entries_for_paths(
3684 root_path,
3685 root_canonical_path,
3686 &request.relative_paths,
3687 abs_paths,
3688 None,
3689 )
3690 .await;
3691
3692 self.send_status_update(scanning, request.done)
3693 }
3694
3695 async fn process_events(&mut self, mut abs_paths: Vec<PathBuf>) {
3696 let root_path = self.state.lock().snapshot.abs_path.clone();
3697 let root_canonical_path = match self.fs.canonicalize(&root_path).await {
3698 Ok(path) => path,
3699 Err(err) => {
3700 log::error!("failed to canonicalize root path: {}", err);
3701 return;
3702 }
3703 };
3704
3705 let mut relative_paths = Vec::with_capacity(abs_paths.len());
3706 let mut dot_git_paths = Vec::new();
3707 abs_paths.sort_unstable();
3708 abs_paths.dedup_by(|a, b| a.starts_with(b));
3709 abs_paths.retain(|abs_path| {
3710 let snapshot = &self.state.lock().snapshot;
3711 {
3712 let mut is_git_related = false;
3713
3714 // We don't want to trigger .git rescan for events within .git/fsmonitor--daemon/cookies directory.
3715 #[derive(PartialEq)]
3716 enum FsMonitorParseState {
3717 Cookies,
3718 FsMonitor
3719 }
3720 let mut fsmonitor_parse_state = None;
3721 if let Some(dot_git_dir) = abs_path
3722 .ancestors()
3723 .find(|ancestor| {
3724 let file_name = ancestor.file_name();
3725 if file_name == Some(*COOKIES) {
3726 fsmonitor_parse_state = Some(FsMonitorParseState::Cookies);
3727 false
3728 } else if fsmonitor_parse_state == Some(FsMonitorParseState::Cookies) && file_name == Some(*FSMONITOR_DAEMON) {
3729 fsmonitor_parse_state = Some(FsMonitorParseState::FsMonitor);
3730 false
3731 } else if fsmonitor_parse_state != Some(FsMonitorParseState::FsMonitor) && file_name == Some(*DOT_GIT) {
3732 true
3733 } else {
3734 fsmonitor_parse_state.take();
3735 false
3736 }
3737
3738 })
3739 {
3740 let dot_git_path = dot_git_dir
3741 .strip_prefix(&root_canonical_path)
3742 .unwrap_or(dot_git_dir)
3743 .to_path_buf();
3744 if !dot_git_paths.contains(&dot_git_path) {
3745 dot_git_paths.push(dot_git_path);
3746 }
3747 is_git_related = true;
3748 }
3749
3750 let relative_path: Arc<Path> =
3751 if let Ok(path) = abs_path.strip_prefix(&root_canonical_path) {
3752 path.into()
3753 } else {
3754 if is_git_related {
3755 log::debug!(
3756 "ignoring event {abs_path:?}, since it's in git dir outside of root path {root_canonical_path:?}",
3757 );
3758 } else {
3759 log::error!(
3760 "ignoring event {abs_path:?} outside of root path {root_canonical_path:?}",
3761 );
3762 }
3763 return false;
3764 };
3765
3766 let parent_dir_is_loaded = relative_path.parent().map_or(true, |parent| {
3767 snapshot
3768 .entry_for_path(parent)
3769 .map_or(false, |entry| entry.kind == EntryKind::Dir)
3770 });
3771 if !parent_dir_is_loaded {
3772 log::debug!("ignoring event {relative_path:?} within unloaded directory");
3773 return false;
3774 }
3775
3776 if self.settings.is_path_excluded(&relative_path) {
3777 if !is_git_related {
3778 log::debug!("ignoring FS event for excluded path {relative_path:?}");
3779 }
3780 return false;
3781 }
3782
3783 relative_paths.push(relative_path);
3784 true
3785 }
3786 });
3787
3788 if relative_paths.is_empty() && dot_git_paths.is_empty() {
3789 return;
3790 }
3791
3792 self.state.lock().snapshot.scan_id += 1;
3793
3794 let (scan_job_tx, scan_job_rx) = channel::unbounded();
3795 log::debug!("received fs events {:?}", relative_paths);
3796 self.reload_entries_for_paths(
3797 root_path,
3798 root_canonical_path,
3799 &relative_paths,
3800 abs_paths,
3801 Some(scan_job_tx.clone()),
3802 )
3803 .await;
3804
3805 self.update_ignore_statuses(scan_job_tx).await;
3806 self.scan_dirs(false, scan_job_rx).await;
3807
3808 if !dot_git_paths.is_empty() {
3809 self.update_git_repositories(dot_git_paths).await;
3810 }
3811
3812 {
3813 let mut state = self.state.lock();
3814 state.snapshot.completed_scan_id = state.snapshot.scan_id;
3815 for (_, entry) in mem::take(&mut state.removed_entries) {
3816 state.scanned_dirs.remove(&entry.id);
3817 }
3818 }
3819
3820 #[cfg(test)]
3821 self.state.lock().snapshot.check_git_invariants();
3822
3823 self.send_status_update(false, SmallVec::new());
3824 }
3825
3826 async fn forcibly_load_paths(&self, paths: &[Arc<Path>]) -> bool {
3827 let (scan_job_tx, mut scan_job_rx) = channel::unbounded();
3828 {
3829 let mut state = self.state.lock();
3830 let root_path = state.snapshot.abs_path.clone();
3831 for path in paths {
3832 for ancestor in path.ancestors() {
3833 if let Some(entry) = state.snapshot.entry_for_path(ancestor) {
3834 if entry.kind == EntryKind::UnloadedDir {
3835 let abs_path = root_path.join(ancestor);
3836 state.enqueue_scan_dir(abs_path.into(), entry, &scan_job_tx);
3837 state.paths_to_scan.insert(path.clone());
3838 break;
3839 }
3840 }
3841 }
3842 }
3843 drop(scan_job_tx);
3844 }
3845 while let Some(job) = scan_job_rx.next().await {
3846 self.scan_dir(&job).await.log_err();
3847 }
3848
3849 !mem::take(&mut self.state.lock().paths_to_scan).is_empty()
3850 }
3851
3852 async fn scan_dirs(
3853 &self,
3854 enable_progress_updates: bool,
3855 scan_jobs_rx: channel::Receiver<ScanJob>,
3856 ) {
3857 use futures::FutureExt as _;
3858
3859 if self
3860 .status_updates_tx
3861 .unbounded_send(ScanState::Started)
3862 .is_err()
3863 {
3864 return;
3865 }
3866
3867 let progress_update_count = AtomicUsize::new(0);
3868 self.executor
3869 .scoped(|scope| {
3870 for _ in 0..self.executor.num_cpus() {
3871 scope.spawn(async {
3872 let mut last_progress_update_count = 0;
3873 let progress_update_timer = self.progress_timer(enable_progress_updates).fuse();
3874 futures::pin_mut!(progress_update_timer);
3875
3876 loop {
3877 select_biased! {
3878 // Process any path refresh requests before moving on to process
3879 // the scan queue, so that user operations are prioritized.
3880 request = self.next_scan_request().fuse() => {
3881 let Ok(request) = request else { break };
3882 if !self.process_scan_request(request, true).await {
3883 return;
3884 }
3885 }
3886
3887 // Send periodic progress updates to the worktree. Use an atomic counter
3888 // to ensure that only one of the workers sends a progress update after
3889 // the update interval elapses.
3890 _ = progress_update_timer => {
3891 match progress_update_count.compare_exchange(
3892 last_progress_update_count,
3893 last_progress_update_count + 1,
3894 SeqCst,
3895 SeqCst
3896 ) {
3897 Ok(_) => {
3898 last_progress_update_count += 1;
3899 self.send_status_update(true, SmallVec::new());
3900 }
3901 Err(count) => {
3902 last_progress_update_count = count;
3903 }
3904 }
3905 progress_update_timer.set(self.progress_timer(enable_progress_updates).fuse());
3906 }
3907
3908 // Recursively load directories from the file system.
3909 job = scan_jobs_rx.recv().fuse() => {
3910 let Ok(job) = job else { break };
3911 if let Err(err) = self.scan_dir(&job).await {
3912 if job.path.as_ref() != Path::new("") {
3913 log::error!("error scanning directory {:?}: {}", job.abs_path, err);
3914 }
3915 }
3916 }
3917 }
3918 }
3919 })
3920 }
3921 })
3922 .await;
3923 }
3924
3925 fn send_status_update(&self, scanning: bool, barrier: SmallVec<[barrier::Sender; 1]>) -> bool {
3926 let mut state = self.state.lock();
3927 if state.changed_paths.is_empty() && scanning {
3928 return true;
3929 }
3930
3931 let new_snapshot = state.snapshot.clone();
3932 let old_snapshot = mem::replace(&mut state.prev_snapshot, new_snapshot.snapshot.clone());
3933 let changes = self.build_change_set(&old_snapshot, &new_snapshot, &state.changed_paths);
3934 state.changed_paths.clear();
3935
3936 self.status_updates_tx
3937 .unbounded_send(ScanState::Updated {
3938 snapshot: new_snapshot,
3939 changes,
3940 scanning,
3941 barrier,
3942 })
3943 .is_ok()
3944 }
3945
3946 async fn scan_dir(&self, job: &ScanJob) -> Result<()> {
3947 let root_abs_path;
3948 let root_char_bag;
3949 {
3950 let snapshot = &self.state.lock().snapshot;
3951 if self.settings.is_path_excluded(&job.path) {
3952 log::error!("skipping excluded directory {:?}", job.path);
3953 return Ok(());
3954 }
3955 log::debug!("scanning directory {:?}", job.path);
3956 root_abs_path = snapshot.abs_path().clone();
3957 root_char_bag = snapshot.root_char_bag;
3958 }
3959
3960 let next_entry_id = self.next_entry_id.clone();
3961 let mut ignore_stack = job.ignore_stack.clone();
3962 let mut containing_repository = job.containing_repository.clone();
3963 let mut new_ignore = None;
3964 let mut root_canonical_path = None;
3965 let mut new_entries: Vec<Entry> = Vec::new();
3966 let mut new_jobs: Vec<Option<ScanJob>> = Vec::new();
3967 let mut child_paths = self
3968 .fs
3969 .read_dir(&job.abs_path)
3970 .await?
3971 .filter_map(|entry| async {
3972 match entry {
3973 Ok(entry) => Some(entry),
3974 Err(error) => {
3975 log::error!("error processing entry {:?}", error);
3976 None
3977 }
3978 }
3979 })
3980 .collect::<Vec<_>>()
3981 .await;
3982
3983 // Ensure that .git and .gitignore are processed first.
3984 swap_to_front(&mut child_paths, *GITIGNORE);
3985 swap_to_front(&mut child_paths, *DOT_GIT);
3986
3987 for child_abs_path in child_paths {
3988 let child_abs_path: Arc<Path> = child_abs_path.into();
3989 let child_name = child_abs_path.file_name().unwrap();
3990 let child_path: Arc<Path> = job.path.join(child_name).into();
3991
3992 if child_name == *DOT_GIT {
3993 let repo = self
3994 .state
3995 .lock()
3996 .build_git_repository(child_path.clone(), self.fs.as_ref());
3997 if let Some((work_directory, repository)) = repo {
3998 let t0 = Instant::now();
3999 let statuses = repository
4000 .status(&[PathBuf::from("")])
4001 .log_err()
4002 .unwrap_or_default();
4003 log::trace!("computed git status in {:?}", t0.elapsed());
4004 containing_repository = Some(ScanJobContainingRepository {
4005 work_directory,
4006 statuses,
4007 });
4008 }
4009 self.watcher.add(child_abs_path.as_ref()).log_err();
4010 } else if child_name == *GITIGNORE {
4011 match build_gitignore(&child_abs_path, self.fs.as_ref()).await {
4012 Ok(ignore) => {
4013 let ignore = Arc::new(ignore);
4014 ignore_stack = ignore_stack.append(job.abs_path.clone(), ignore.clone());
4015 new_ignore = Some(ignore);
4016 }
4017 Err(error) => {
4018 log::error!(
4019 "error loading .gitignore file {:?} - {:?}",
4020 child_name,
4021 error
4022 );
4023 }
4024 }
4025 }
4026
4027 if self.settings.is_path_excluded(&child_path) {
4028 log::debug!("skipping excluded child entry {child_path:?}");
4029 self.state.lock().remove_path(&child_path);
4030 continue;
4031 }
4032
4033 let child_metadata = match self.fs.metadata(&child_abs_path).await {
4034 Ok(Some(metadata)) => metadata,
4035 Ok(None) => continue,
4036 Err(err) => {
4037 log::error!("error processing {child_abs_path:?}: {err:?}");
4038 continue;
4039 }
4040 };
4041
4042 let mut child_entry = Entry::new(
4043 child_path.clone(),
4044 &child_metadata,
4045 &next_entry_id,
4046 root_char_bag,
4047 None,
4048 );
4049
4050 if job.is_external {
4051 child_entry.is_external = true;
4052 } else if child_metadata.is_symlink {
4053 let canonical_path = match self.fs.canonicalize(&child_abs_path).await {
4054 Ok(path) => path,
4055 Err(err) => {
4056 log::error!(
4057 "error reading target of symlink {:?}: {:?}",
4058 child_abs_path,
4059 err
4060 );
4061 continue;
4062 }
4063 };
4064
4065 // lazily canonicalize the root path in order to determine if
4066 // symlinks point outside of the worktree.
4067 let root_canonical_path = match &root_canonical_path {
4068 Some(path) => path,
4069 None => match self.fs.canonicalize(&root_abs_path).await {
4070 Ok(path) => root_canonical_path.insert(path),
4071 Err(err) => {
4072 log::error!("error canonicalizing root {:?}: {:?}", root_abs_path, err);
4073 continue;
4074 }
4075 },
4076 };
4077
4078 if !canonical_path.starts_with(root_canonical_path) {
4079 child_entry.is_external = true;
4080 }
4081
4082 child_entry.canonical_path = Some(canonical_path.into());
4083 }
4084
4085 if child_entry.is_dir() {
4086 child_entry.is_ignored = ignore_stack.is_abs_path_ignored(&child_abs_path, true);
4087
4088 // Avoid recursing until crash in the case of a recursive symlink
4089 if job.ancestor_inodes.contains(&child_entry.inode) {
4090 new_jobs.push(None);
4091 } else {
4092 let mut ancestor_inodes = job.ancestor_inodes.clone();
4093 ancestor_inodes.insert(child_entry.inode);
4094
4095 new_jobs.push(Some(ScanJob {
4096 abs_path: child_abs_path.clone(),
4097 path: child_path,
4098 is_external: child_entry.is_external,
4099 ignore_stack: if child_entry.is_ignored {
4100 IgnoreStack::all()
4101 } else {
4102 ignore_stack.clone()
4103 },
4104 ancestor_inodes,
4105 scan_queue: job.scan_queue.clone(),
4106 containing_repository: containing_repository.clone(),
4107 }));
4108 }
4109 } else {
4110 child_entry.is_ignored = ignore_stack.is_abs_path_ignored(&child_abs_path, false);
4111 if !child_entry.is_ignored {
4112 if let Some(repo) = &containing_repository {
4113 if let Ok(repo_path) = child_entry.path.strip_prefix(&repo.work_directory) {
4114 let repo_path = RepoPath(repo_path.into());
4115 child_entry.git_status = repo.statuses.get(&repo_path);
4116 }
4117 }
4118 }
4119 }
4120
4121 {
4122 let relative_path = job.path.join(child_name);
4123 if self.is_path_private(&relative_path) {
4124 log::debug!("detected private file: {relative_path:?}");
4125 child_entry.is_private = true;
4126 }
4127 }
4128
4129 new_entries.push(child_entry);
4130 }
4131
4132 let mut state = self.state.lock();
4133
4134 // Identify any subdirectories that should not be scanned.
4135 let mut job_ix = 0;
4136 for entry in &mut new_entries {
4137 state.reuse_entry_id(entry);
4138 if entry.is_dir() {
4139 if state.should_scan_directory(entry) {
4140 job_ix += 1;
4141 } else {
4142 log::debug!("defer scanning directory {:?}", entry.path);
4143 entry.kind = EntryKind::UnloadedDir;
4144 new_jobs.remove(job_ix);
4145 }
4146 }
4147 }
4148
4149 state.populate_dir(&job.path, new_entries, new_ignore);
4150 self.watcher.add(job.abs_path.as_ref()).log_err();
4151
4152 for new_job in new_jobs.into_iter().flatten() {
4153 job.scan_queue
4154 .try_send(new_job)
4155 .expect("channel is unbounded");
4156 }
4157
4158 Ok(())
4159 }
4160
4161 async fn reload_entries_for_paths(
4162 &self,
4163 root_abs_path: Arc<Path>,
4164 root_canonical_path: PathBuf,
4165 relative_paths: &[Arc<Path>],
4166 abs_paths: Vec<PathBuf>,
4167 scan_queue_tx: Option<Sender<ScanJob>>,
4168 ) {
4169 let metadata = futures::future::join_all(
4170 abs_paths
4171 .iter()
4172 .map(|abs_path| async move {
4173 let metadata = self.fs.metadata(abs_path).await?;
4174 if let Some(metadata) = metadata {
4175 let canonical_path = self.fs.canonicalize(abs_path).await?;
4176
4177 // If we're on a case-insensitive filesystem (default on macOS), we want
4178 // to only ignore metadata for non-symlink files if their absolute-path matches
4179 // the canonical-path.
4180 // Because if not, this might be a case-only-renaming (`mv test.txt TEST.TXT`)
4181 // and we want to ignore the metadata for the old path (`test.txt`) so it's
4182 // treated as removed.
4183 if !self.fs_case_sensitive && !metadata.is_symlink {
4184 let canonical_file_name = canonical_path.file_name();
4185 let file_name = abs_path.file_name();
4186 if canonical_file_name != file_name {
4187 return Ok(None);
4188 }
4189 }
4190
4191 anyhow::Ok(Some((metadata, canonical_path)))
4192 } else {
4193 Ok(None)
4194 }
4195 })
4196 .collect::<Vec<_>>(),
4197 )
4198 .await;
4199
4200 let mut state = self.state.lock();
4201 let doing_recursive_update = scan_queue_tx.is_some();
4202
4203 // Remove any entries for paths that no longer exist or are being recursively
4204 // refreshed. Do this before adding any new entries, so that renames can be
4205 // detected regardless of the order of the paths.
4206 for (path, metadata) in relative_paths.iter().zip(metadata.iter()) {
4207 if matches!(metadata, Ok(None)) || doing_recursive_update {
4208 log::trace!("remove path {:?}", path);
4209 state.remove_path(path);
4210 }
4211 }
4212
4213 // Group all relative paths by their git repository.
4214 let mut paths_by_git_repo = HashMap::default();
4215 for relative_path in relative_paths.iter() {
4216 if let Some((repo_entry, repo)) = state.snapshot.repo_for_path(relative_path) {
4217 if let Ok(repo_path) = repo_entry.relativize(&state.snapshot, relative_path) {
4218 paths_by_git_repo
4219 .entry(repo.git_dir_path.clone())
4220 .or_insert_with(|| RepoPaths {
4221 repo: repo.repo_ptr.clone(),
4222 repo_paths: Vec::new(),
4223 relative_paths: Vec::new(),
4224 })
4225 .add_paths(relative_path, repo_path);
4226 }
4227 }
4228 }
4229
4230 // Now call `git status` once per repository and collect each file's git status.
4231 let mut git_statuses_by_relative_path =
4232 paths_by_git_repo
4233 .into_values()
4234 .fold(HashMap::default(), |mut map, repo_paths| {
4235 map.extend(repo_paths.into_git_file_statuses());
4236 map
4237 });
4238
4239 for (path, metadata) in relative_paths.iter().zip(metadata.into_iter()) {
4240 let abs_path: Arc<Path> = root_abs_path.join(path).into();
4241 match metadata {
4242 Ok(Some((metadata, canonical_path))) => {
4243 let ignore_stack = state
4244 .snapshot
4245 .ignore_stack_for_abs_path(&abs_path, metadata.is_dir);
4246 let is_external = !canonical_path.starts_with(&root_canonical_path);
4247 let mut fs_entry = Entry::new(
4248 path.clone(),
4249 &metadata,
4250 self.next_entry_id.as_ref(),
4251 state.snapshot.root_char_bag,
4252 if metadata.is_symlink {
4253 Some(canonical_path.into())
4254 } else {
4255 None
4256 },
4257 );
4258
4259 let is_dir = fs_entry.is_dir();
4260 fs_entry.is_ignored = ignore_stack.is_abs_path_ignored(&abs_path, is_dir);
4261 fs_entry.is_external = is_external;
4262 fs_entry.is_private = self.is_path_private(path);
4263
4264 if let (Some(scan_queue_tx), true) = (&scan_queue_tx, is_dir) {
4265 if state.should_scan_directory(&fs_entry)
4266 || (fs_entry.path.as_os_str().is_empty()
4267 && abs_path.file_name() == Some(*DOT_GIT))
4268 {
4269 state.enqueue_scan_dir(abs_path, &fs_entry, scan_queue_tx);
4270 } else {
4271 fs_entry.kind = EntryKind::UnloadedDir;
4272 }
4273 }
4274
4275 if !is_dir && !fs_entry.is_ignored && !fs_entry.is_external {
4276 fs_entry.git_status = git_statuses_by_relative_path.remove(path);
4277 }
4278
4279 state.insert_entry(fs_entry.clone(), self.fs.as_ref());
4280 }
4281 Ok(None) => {
4282 self.remove_repo_path(path, &mut state.snapshot);
4283 }
4284 Err(err) => {
4285 log::error!("error reading file {abs_path:?} on event: {err:#}");
4286 }
4287 }
4288 }
4289
4290 util::extend_sorted(
4291 &mut state.changed_paths,
4292 relative_paths.iter().cloned(),
4293 usize::MAX,
4294 Ord::cmp,
4295 );
4296 }
4297
4298 fn remove_repo_path(&self, path: &Path, snapshot: &mut LocalSnapshot) -> Option<()> {
4299 if !path
4300 .components()
4301 .any(|component| component.as_os_str() == *DOT_GIT)
4302 {
4303 if let Some(repository) = snapshot.repository_for_work_directory(path) {
4304 let entry = repository.work_directory.0;
4305 snapshot.git_repositories.remove(&entry);
4306 snapshot
4307 .snapshot
4308 .repository_entries
4309 .remove(&RepositoryWorkDirectory(path.into()));
4310 return Some(());
4311 }
4312 }
4313
4314 Some(())
4315 }
4316
4317 async fn update_ignore_statuses(&self, scan_job_tx: Sender<ScanJob>) {
4318 use futures::FutureExt as _;
4319
4320 let mut ignores_to_update = Vec::new();
4321 let (ignore_queue_tx, ignore_queue_rx) = channel::unbounded();
4322 let prev_snapshot;
4323 {
4324 let snapshot = &mut self.state.lock().snapshot;
4325 let abs_path = snapshot.abs_path.clone();
4326 snapshot
4327 .ignores_by_parent_abs_path
4328 .retain(|parent_abs_path, (_, needs_update)| {
4329 if let Ok(parent_path) = parent_abs_path.strip_prefix(&abs_path) {
4330 if *needs_update {
4331 *needs_update = false;
4332 if snapshot.snapshot.entry_for_path(parent_path).is_some() {
4333 ignores_to_update.push(parent_abs_path.clone());
4334 }
4335 }
4336
4337 let ignore_path = parent_path.join(*GITIGNORE);
4338 if snapshot.snapshot.entry_for_path(ignore_path).is_none() {
4339 return false;
4340 }
4341 }
4342 true
4343 });
4344
4345 ignores_to_update.sort_unstable();
4346 let mut ignores_to_update = ignores_to_update.into_iter().peekable();
4347 while let Some(parent_abs_path) = ignores_to_update.next() {
4348 while ignores_to_update
4349 .peek()
4350 .map_or(false, |p| p.starts_with(&parent_abs_path))
4351 {
4352 ignores_to_update.next().unwrap();
4353 }
4354
4355 let ignore_stack = snapshot.ignore_stack_for_abs_path(&parent_abs_path, true);
4356 ignore_queue_tx
4357 .send_blocking(UpdateIgnoreStatusJob {
4358 abs_path: parent_abs_path,
4359 ignore_stack,
4360 ignore_queue: ignore_queue_tx.clone(),
4361 scan_queue: scan_job_tx.clone(),
4362 })
4363 .unwrap();
4364 }
4365
4366 prev_snapshot = snapshot.clone();
4367 }
4368 drop(ignore_queue_tx);
4369
4370 self.executor
4371 .scoped(|scope| {
4372 for _ in 0..self.executor.num_cpus() {
4373 scope.spawn(async {
4374 loop {
4375 select_biased! {
4376 // Process any path refresh requests before moving on to process
4377 // the queue of ignore statuses.
4378 request = self.next_scan_request().fuse() => {
4379 let Ok(request) = request else { break };
4380 if !self.process_scan_request(request, true).await {
4381 return;
4382 }
4383 }
4384
4385 // Recursively process directories whose ignores have changed.
4386 job = ignore_queue_rx.recv().fuse() => {
4387 let Ok(job) = job else { break };
4388 self.update_ignore_status(job, &prev_snapshot).await;
4389 }
4390 }
4391 }
4392 });
4393 }
4394 })
4395 .await;
4396 }
4397
4398 async fn update_ignore_status(&self, job: UpdateIgnoreStatusJob, snapshot: &LocalSnapshot) {
4399 log::trace!("update ignore status {:?}", job.abs_path);
4400
4401 let mut ignore_stack = job.ignore_stack;
4402 if let Some((ignore, _)) = snapshot.ignores_by_parent_abs_path.get(&job.abs_path) {
4403 ignore_stack = ignore_stack.append(job.abs_path.clone(), ignore.clone());
4404 }
4405
4406 let mut entries_by_id_edits = Vec::new();
4407 let mut entries_by_path_edits = Vec::new();
4408 let path = job.abs_path.strip_prefix(&snapshot.abs_path).unwrap();
4409 let repo = snapshot.repo_for_path(path);
4410 for mut entry in snapshot.child_entries(path).cloned() {
4411 let was_ignored = entry.is_ignored;
4412 let abs_path: Arc<Path> = snapshot.abs_path().join(&entry.path).into();
4413 entry.is_ignored = ignore_stack.is_abs_path_ignored(&abs_path, entry.is_dir());
4414
4415 if entry.is_dir() {
4416 let child_ignore_stack = if entry.is_ignored {
4417 IgnoreStack::all()
4418 } else {
4419 ignore_stack.clone()
4420 };
4421
4422 // Scan any directories that were previously ignored and weren't previously scanned.
4423 if was_ignored && !entry.is_ignored && entry.kind.is_unloaded() {
4424 let state = self.state.lock();
4425 if state.should_scan_directory(&entry) {
4426 state.enqueue_scan_dir(abs_path.clone(), &entry, &job.scan_queue);
4427 }
4428 }
4429
4430 job.ignore_queue
4431 .send(UpdateIgnoreStatusJob {
4432 abs_path: abs_path.clone(),
4433 ignore_stack: child_ignore_stack,
4434 ignore_queue: job.ignore_queue.clone(),
4435 scan_queue: job.scan_queue.clone(),
4436 })
4437 .await
4438 .unwrap();
4439 }
4440
4441 if entry.is_ignored != was_ignored {
4442 let mut path_entry = snapshot.entries_by_id.get(&entry.id, &()).unwrap().clone();
4443 path_entry.scan_id = snapshot.scan_id;
4444 path_entry.is_ignored = entry.is_ignored;
4445 if !entry.is_dir() && !entry.is_ignored && !entry.is_external {
4446 if let Some((ref repo_entry, local_repo)) = repo {
4447 if let Ok(repo_path) = repo_entry.relativize(snapshot, &entry.path) {
4448 let status = local_repo
4449 .repo_ptr
4450 .status(&[repo_path.0.clone()])
4451 .ok()
4452 .and_then(|status| status.get(&repo_path));
4453 entry.git_status = status;
4454 }
4455 }
4456 }
4457 entries_by_id_edits.push(Edit::Insert(path_entry));
4458 entries_by_path_edits.push(Edit::Insert(entry));
4459 }
4460 }
4461
4462 let state = &mut self.state.lock();
4463 for edit in &entries_by_path_edits {
4464 if let Edit::Insert(entry) = edit {
4465 if let Err(ix) = state.changed_paths.binary_search(&entry.path) {
4466 state.changed_paths.insert(ix, entry.path.clone());
4467 }
4468 }
4469 }
4470
4471 state
4472 .snapshot
4473 .entries_by_path
4474 .edit(entries_by_path_edits, &());
4475 state.snapshot.entries_by_id.edit(entries_by_id_edits, &());
4476 }
4477
4478 async fn update_git_repositories(&self, dot_git_paths: Vec<PathBuf>) {
4479 log::debug!("reloading repositories: {dot_git_paths:?}");
4480
4481 let mut repo_updates = Vec::new();
4482 {
4483 let mut state = self.state.lock();
4484 let scan_id = state.snapshot.scan_id;
4485 for dot_git_dir in dot_git_paths {
4486 let existing_repository_entry =
4487 state
4488 .snapshot
4489 .git_repositories
4490 .iter()
4491 .find_map(|(entry_id, repo)| {
4492 (repo.git_dir_path.as_ref() == dot_git_dir)
4493 .then(|| (*entry_id, repo.clone()))
4494 });
4495
4496 let (work_directory, repository) = match existing_repository_entry {
4497 None => {
4498 match state.build_git_repository(dot_git_dir.into(), self.fs.as_ref()) {
4499 Some(output) => output,
4500 None => continue,
4501 }
4502 }
4503 Some((entry_id, repository)) => {
4504 if repository.git_dir_scan_id == scan_id {
4505 continue;
4506 }
4507 let Some(work_dir) = state
4508 .snapshot
4509 .entry_for_id(entry_id)
4510 .map(|entry| RepositoryWorkDirectory(entry.path.clone()))
4511 else {
4512 continue;
4513 };
4514
4515 let repo = &repository.repo_ptr;
4516 let branch = repo.branch_name();
4517 repo.reload_index();
4518
4519 state
4520 .snapshot
4521 .git_repositories
4522 .update(&entry_id, |entry| entry.git_dir_scan_id = scan_id);
4523 state
4524 .snapshot
4525 .snapshot
4526 .repository_entries
4527 .update(&work_dir, |entry| entry.branch = branch.map(Into::into));
4528 (work_dir, repository.repo_ptr.clone())
4529 }
4530 };
4531
4532 repo_updates.push(UpdateGitStatusesJob {
4533 location_in_repo: state
4534 .snapshot
4535 .repository_entries
4536 .get(&work_directory)
4537 .and_then(|repo| repo.location_in_repo.clone())
4538 .clone(),
4539 work_directory,
4540 repository,
4541 });
4542 }
4543
4544 // Remove any git repositories whose .git entry no longer exists.
4545 let snapshot = &mut state.snapshot;
4546 let mut ids_to_preserve = HashSet::default();
4547 for (&work_directory_id, entry) in snapshot.git_repositories.iter() {
4548 let exists_in_snapshot = snapshot
4549 .entry_for_id(work_directory_id)
4550 .map_or(false, |entry| {
4551 snapshot.entry_for_path(entry.path.join(*DOT_GIT)).is_some()
4552 });
4553 if exists_in_snapshot {
4554 ids_to_preserve.insert(work_directory_id);
4555 } else {
4556 let git_dir_abs_path = snapshot.abs_path().join(&entry.git_dir_path);
4557 let git_dir_excluded = self.settings.is_path_excluded(&entry.git_dir_path);
4558 if git_dir_excluded
4559 && !matches!(
4560 smol::block_on(self.fs.metadata(&git_dir_abs_path)),
4561 Ok(None)
4562 )
4563 {
4564 ids_to_preserve.insert(work_directory_id);
4565 }
4566 }
4567 }
4568
4569 snapshot
4570 .git_repositories
4571 .retain(|work_directory_id, _| ids_to_preserve.contains(work_directory_id));
4572 snapshot
4573 .repository_entries
4574 .retain(|_, entry| ids_to_preserve.contains(&entry.work_directory.0));
4575 }
4576
4577 let (mut updates_done_tx, mut updates_done_rx) = barrier::channel();
4578 self.executor
4579 .scoped(|scope| {
4580 scope.spawn(async {
4581 for repo_update in repo_updates {
4582 self.update_git_statuses(repo_update);
4583 }
4584 updates_done_tx.blocking_send(()).ok();
4585 });
4586
4587 scope.spawn(async {
4588 loop {
4589 select_biased! {
4590 // Process any path refresh requests before moving on to process
4591 // the queue of git statuses.
4592 request = self.next_scan_request().fuse() => {
4593 let Ok(request) = request else { break };
4594 if !self.process_scan_request(request, true).await {
4595 return;
4596 }
4597 }
4598 _ = updates_done_rx.recv().fuse() => break,
4599 }
4600 }
4601 });
4602 })
4603 .await;
4604 }
4605
4606 /// Update the git statuses for a given batch of entries.
4607 fn update_git_statuses(&self, job: UpdateGitStatusesJob) {
4608 log::trace!("updating git statuses for repo {:?}", job.work_directory.0);
4609 let t0 = Instant::now();
4610 let Some(statuses) = job.repository.status(&[PathBuf::from("")]).log_err() else {
4611 return;
4612 };
4613 log::trace!(
4614 "computed git statuses for repo {:?} in {:?}",
4615 job.work_directory.0,
4616 t0.elapsed()
4617 );
4618
4619 let t0 = Instant::now();
4620 let mut changes = Vec::new();
4621 let snapshot = self.state.lock().snapshot.snapshot.clone();
4622 for file in snapshot.traverse_from_path(true, false, false, job.work_directory.0.as_ref()) {
4623 let Ok(repo_path) = file.path.strip_prefix(&job.work_directory.0) else {
4624 break;
4625 };
4626 let git_status = if let Some(location) = &job.location_in_repo {
4627 statuses.get(&location.join(repo_path))
4628 } else {
4629 statuses.get(repo_path)
4630 };
4631 if file.git_status != git_status {
4632 let mut entry = file.clone();
4633 entry.git_status = git_status;
4634 changes.push((entry.path, git_status));
4635 }
4636 }
4637
4638 let mut state = self.state.lock();
4639 let edits = changes
4640 .iter()
4641 .filter_map(|(path, git_status)| {
4642 let entry = state.snapshot.entry_for_path(path)?.clone();
4643 Some(Edit::Insert(Entry {
4644 git_status: *git_status,
4645 ..entry.clone()
4646 }))
4647 })
4648 .collect();
4649
4650 // Apply the git status changes.
4651 util::extend_sorted(
4652 &mut state.changed_paths,
4653 changes.iter().map(|p| p.0.clone()),
4654 usize::MAX,
4655 Ord::cmp,
4656 );
4657 state.snapshot.entries_by_path.edit(edits, &());
4658 log::trace!(
4659 "applied git status updates for repo {:?} in {:?}",
4660 job.work_directory.0,
4661 t0.elapsed(),
4662 );
4663 }
4664
4665 fn build_change_set(
4666 &self,
4667 old_snapshot: &Snapshot,
4668 new_snapshot: &Snapshot,
4669 event_paths: &[Arc<Path>],
4670 ) -> UpdatedEntriesSet {
4671 use BackgroundScannerPhase::*;
4672 use PathChange::{Added, AddedOrUpdated, Loaded, Removed, Updated};
4673
4674 // Identify which paths have changed. Use the known set of changed
4675 // parent paths to optimize the search.
4676 let mut changes = Vec::new();
4677 let mut old_paths = old_snapshot.entries_by_path.cursor::<PathKey>(&());
4678 let mut new_paths = new_snapshot.entries_by_path.cursor::<PathKey>(&());
4679 let mut last_newly_loaded_dir_path = None;
4680 old_paths.next(&());
4681 new_paths.next(&());
4682 for path in event_paths {
4683 let path = PathKey(path.clone());
4684 if old_paths.item().map_or(false, |e| e.path < path.0) {
4685 old_paths.seek_forward(&path, Bias::Left, &());
4686 }
4687 if new_paths.item().map_or(false, |e| e.path < path.0) {
4688 new_paths.seek_forward(&path, Bias::Left, &());
4689 }
4690 loop {
4691 match (old_paths.item(), new_paths.item()) {
4692 (Some(old_entry), Some(new_entry)) => {
4693 if old_entry.path > path.0
4694 && new_entry.path > path.0
4695 && !old_entry.path.starts_with(&path.0)
4696 && !new_entry.path.starts_with(&path.0)
4697 {
4698 break;
4699 }
4700
4701 match Ord::cmp(&old_entry.path, &new_entry.path) {
4702 Ordering::Less => {
4703 changes.push((old_entry.path.clone(), old_entry.id, Removed));
4704 old_paths.next(&());
4705 }
4706 Ordering::Equal => {
4707 if self.phase == EventsReceivedDuringInitialScan {
4708 if old_entry.id != new_entry.id {
4709 changes.push((
4710 old_entry.path.clone(),
4711 old_entry.id,
4712 Removed,
4713 ));
4714 }
4715 // If the worktree was not fully initialized when this event was generated,
4716 // we can't know whether this entry was added during the scan or whether
4717 // it was merely updated.
4718 changes.push((
4719 new_entry.path.clone(),
4720 new_entry.id,
4721 AddedOrUpdated,
4722 ));
4723 } else if old_entry.id != new_entry.id {
4724 changes.push((old_entry.path.clone(), old_entry.id, Removed));
4725 changes.push((new_entry.path.clone(), new_entry.id, Added));
4726 } else if old_entry != new_entry {
4727 if old_entry.kind.is_unloaded() {
4728 last_newly_loaded_dir_path = Some(&new_entry.path);
4729 changes.push((
4730 new_entry.path.clone(),
4731 new_entry.id,
4732 Loaded,
4733 ));
4734 } else {
4735 changes.push((
4736 new_entry.path.clone(),
4737 new_entry.id,
4738 Updated,
4739 ));
4740 }
4741 }
4742 old_paths.next(&());
4743 new_paths.next(&());
4744 }
4745 Ordering::Greater => {
4746 let is_newly_loaded = self.phase == InitialScan
4747 || last_newly_loaded_dir_path
4748 .as_ref()
4749 .map_or(false, |dir| new_entry.path.starts_with(dir));
4750 changes.push((
4751 new_entry.path.clone(),
4752 new_entry.id,
4753 if is_newly_loaded { Loaded } else { Added },
4754 ));
4755 new_paths.next(&());
4756 }
4757 }
4758 }
4759 (Some(old_entry), None) => {
4760 changes.push((old_entry.path.clone(), old_entry.id, Removed));
4761 old_paths.next(&());
4762 }
4763 (None, Some(new_entry)) => {
4764 let is_newly_loaded = self.phase == InitialScan
4765 || last_newly_loaded_dir_path
4766 .as_ref()
4767 .map_or(false, |dir| new_entry.path.starts_with(dir));
4768 changes.push((
4769 new_entry.path.clone(),
4770 new_entry.id,
4771 if is_newly_loaded { Loaded } else { Added },
4772 ));
4773 new_paths.next(&());
4774 }
4775 (None, None) => break,
4776 }
4777 }
4778 }
4779
4780 changes.into()
4781 }
4782
4783 async fn progress_timer(&self, running: bool) {
4784 if !running {
4785 return futures::future::pending().await;
4786 }
4787
4788 #[cfg(any(test, feature = "test-support"))]
4789 if self.fs.is_fake() {
4790 return self.executor.simulate_random_delay().await;
4791 }
4792
4793 smol::Timer::after(FS_WATCH_LATENCY).await;
4794 }
4795
4796 fn is_path_private(&self, path: &Path) -> bool {
4797 !self.share_private_files && self.settings.is_path_private(path)
4798 }
4799
4800 async fn next_scan_request(&self) -> Result<ScanRequest> {
4801 let mut request = self.scan_requests_rx.recv().await?;
4802 while let Ok(next_request) = self.scan_requests_rx.try_recv() {
4803 request.relative_paths.extend(next_request.relative_paths);
4804 request.done.extend(next_request.done);
4805 }
4806 Ok(request)
4807 }
4808}
4809
4810fn swap_to_front(child_paths: &mut Vec<PathBuf>, file: &OsStr) {
4811 let position = child_paths
4812 .iter()
4813 .position(|path| path.file_name().unwrap() == file);
4814 if let Some(position) = position {
4815 let temp = child_paths.remove(position);
4816 child_paths.insert(0, temp);
4817 }
4818}
4819
4820fn char_bag_for_path(root_char_bag: CharBag, path: &Path) -> CharBag {
4821 let mut result = root_char_bag;
4822 result.extend(
4823 path.to_string_lossy()
4824 .chars()
4825 .map(|c| c.to_ascii_lowercase()),
4826 );
4827 result
4828}
4829
4830struct RepoPaths {
4831 repo: Arc<dyn GitRepository>,
4832 relative_paths: Vec<Arc<Path>>,
4833 repo_paths: Vec<PathBuf>,
4834}
4835
4836impl RepoPaths {
4837 fn add_paths(&mut self, relative_path: &Arc<Path>, repo_path: RepoPath) {
4838 self.relative_paths.push(relative_path.clone());
4839 self.repo_paths.push(repo_path.0);
4840 }
4841
4842 fn into_git_file_statuses(self) -> HashMap<Arc<Path>, GitFileStatus> {
4843 let mut statuses = HashMap::default();
4844 if let Ok(status) = self.repo.status(&self.repo_paths) {
4845 for (repo_path, relative_path) in self.repo_paths.into_iter().zip(self.relative_paths) {
4846 if let Some(path_status) = status.get(&repo_path) {
4847 statuses.insert(relative_path, path_status);
4848 }
4849 }
4850 }
4851 statuses
4852 }
4853}
4854
4855struct ScanJob {
4856 abs_path: Arc<Path>,
4857 path: Arc<Path>,
4858 ignore_stack: Arc<IgnoreStack>,
4859 scan_queue: Sender<ScanJob>,
4860 ancestor_inodes: TreeSet<u64>,
4861 is_external: bool,
4862 containing_repository: Option<ScanJobContainingRepository>,
4863}
4864
4865#[derive(Clone)]
4866struct ScanJobContainingRepository {
4867 work_directory: RepositoryWorkDirectory,
4868 statuses: GitStatus,
4869}
4870
4871struct UpdateIgnoreStatusJob {
4872 abs_path: Arc<Path>,
4873 ignore_stack: Arc<IgnoreStack>,
4874 ignore_queue: Sender<UpdateIgnoreStatusJob>,
4875 scan_queue: Sender<ScanJob>,
4876}
4877
4878struct UpdateGitStatusesJob {
4879 work_directory: RepositoryWorkDirectory,
4880 location_in_repo: Option<Arc<Path>>,
4881 repository: Arc<dyn GitRepository>,
4882}
4883
4884pub trait WorktreeModelHandle {
4885 #[cfg(any(test, feature = "test-support"))]
4886 fn flush_fs_events<'a>(
4887 &self,
4888 cx: &'a mut gpui::TestAppContext,
4889 ) -> futures::future::LocalBoxFuture<'a, ()>;
4890
4891 #[cfg(any(test, feature = "test-support"))]
4892 fn flush_fs_events_in_root_git_repository<'a>(
4893 &self,
4894 cx: &'a mut gpui::TestAppContext,
4895 ) -> futures::future::LocalBoxFuture<'a, ()>;
4896}
4897
4898impl WorktreeModelHandle for Model<Worktree> {
4899 // When the worktree's FS event stream sometimes delivers "redundant" events for FS changes that
4900 // occurred before the worktree was constructed. These events can cause the worktree to perform
4901 // extra directory scans, and emit extra scan-state notifications.
4902 //
4903 // This function mutates the worktree's directory and waits for those mutations to be picked up,
4904 // to ensure that all redundant FS events have already been processed.
4905 #[cfg(any(test, feature = "test-support"))]
4906 fn flush_fs_events<'a>(
4907 &self,
4908 cx: &'a mut gpui::TestAppContext,
4909 ) -> futures::future::LocalBoxFuture<'a, ()> {
4910 let file_name = "fs-event-sentinel";
4911
4912 let tree = self.clone();
4913 let (fs, root_path) = self.update(cx, |tree, _| {
4914 let tree = tree.as_local().unwrap();
4915 (tree.fs.clone(), tree.abs_path().clone())
4916 });
4917
4918 async move {
4919 fs.create_file(&root_path.join(file_name), Default::default())
4920 .await
4921 .unwrap();
4922
4923 cx.condition(&tree, |tree, _| tree.entry_for_path(file_name).is_some())
4924 .await;
4925
4926 fs.remove_file(&root_path.join(file_name), Default::default())
4927 .await
4928 .unwrap();
4929 cx.condition(&tree, |tree, _| tree.entry_for_path(file_name).is_none())
4930 .await;
4931
4932 cx.update(|cx| tree.read(cx).as_local().unwrap().scan_complete())
4933 .await;
4934 }
4935 .boxed_local()
4936 }
4937
4938 // This function is similar to flush_fs_events, except that it waits for events to be flushed in
4939 // the .git folder of the root repository.
4940 // The reason for its existence is that a repository's .git folder might live *outside* of the
4941 // worktree and thus its FS events might go through a different path.
4942 // In order to flush those, we need to create artificial events in the .git folder and wait
4943 // for the repository to be reloaded.
4944 #[cfg(any(test, feature = "test-support"))]
4945 fn flush_fs_events_in_root_git_repository<'a>(
4946 &self,
4947 cx: &'a mut gpui::TestAppContext,
4948 ) -> futures::future::LocalBoxFuture<'a, ()> {
4949 let file_name = "fs-event-sentinel";
4950
4951 let tree = self.clone();
4952 let (fs, root_path, mut git_dir_scan_id) = self.update(cx, |tree, _| {
4953 let tree = tree.as_local().unwrap();
4954 let root_entry = tree.root_git_entry().unwrap();
4955 let local_repo_entry = tree.get_local_repo(&root_entry).unwrap();
4956 (
4957 tree.fs.clone(),
4958 local_repo_entry.git_dir_path.clone(),
4959 local_repo_entry.git_dir_scan_id,
4960 )
4961 });
4962
4963 let scan_id_increased = |tree: &mut Worktree, git_dir_scan_id: &mut usize| {
4964 let root_entry = tree.root_git_entry().unwrap();
4965 let local_repo_entry = tree
4966 .as_local()
4967 .unwrap()
4968 .get_local_repo(&root_entry)
4969 .unwrap();
4970
4971 if local_repo_entry.git_dir_scan_id > *git_dir_scan_id {
4972 *git_dir_scan_id = local_repo_entry.git_dir_scan_id;
4973 true
4974 } else {
4975 false
4976 }
4977 };
4978
4979 async move {
4980 fs.create_file(&root_path.join(file_name), Default::default())
4981 .await
4982 .unwrap();
4983
4984 cx.condition(&tree, |tree, _| {
4985 scan_id_increased(tree, &mut git_dir_scan_id)
4986 })
4987 .await;
4988
4989 fs.remove_file(&root_path.join(file_name), Default::default())
4990 .await
4991 .unwrap();
4992
4993 cx.condition(&tree, |tree, _| {
4994 scan_id_increased(tree, &mut git_dir_scan_id)
4995 })
4996 .await;
4997
4998 cx.update(|cx| tree.read(cx).as_local().unwrap().scan_complete())
4999 .await;
5000 }
5001 .boxed_local()
5002 }
5003}
5004
5005#[derive(Clone, Debug)]
5006struct TraversalProgress<'a> {
5007 max_path: &'a Path,
5008 count: usize,
5009 non_ignored_count: usize,
5010 file_count: usize,
5011 non_ignored_file_count: usize,
5012}
5013
5014impl<'a> TraversalProgress<'a> {
5015 fn count(&self, include_files: bool, include_dirs: bool, include_ignored: bool) -> usize {
5016 match (include_files, include_dirs, include_ignored) {
5017 (true, true, true) => self.count,
5018 (true, true, false) => self.non_ignored_count,
5019 (true, false, true) => self.file_count,
5020 (true, false, false) => self.non_ignored_file_count,
5021 (false, true, true) => self.count - self.file_count,
5022 (false, true, false) => self.non_ignored_count - self.non_ignored_file_count,
5023 (false, false, _) => 0,
5024 }
5025 }
5026}
5027
5028impl<'a> sum_tree::Dimension<'a, EntrySummary> for TraversalProgress<'a> {
5029 fn zero(_cx: &()) -> Self {
5030 Default::default()
5031 }
5032
5033 fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
5034 self.max_path = summary.max_path.as_ref();
5035 self.count += summary.count;
5036 self.non_ignored_count += summary.non_ignored_count;
5037 self.file_count += summary.file_count;
5038 self.non_ignored_file_count += summary.non_ignored_file_count;
5039 }
5040}
5041
5042impl<'a> Default for TraversalProgress<'a> {
5043 fn default() -> Self {
5044 Self {
5045 max_path: Path::new(""),
5046 count: 0,
5047 non_ignored_count: 0,
5048 file_count: 0,
5049 non_ignored_file_count: 0,
5050 }
5051 }
5052}
5053
5054#[derive(Clone, Debug, Default, Copy)]
5055struct GitStatuses {
5056 added: usize,
5057 modified: usize,
5058 conflict: usize,
5059}
5060
5061impl AddAssign for GitStatuses {
5062 fn add_assign(&mut self, rhs: Self) {
5063 self.added += rhs.added;
5064 self.modified += rhs.modified;
5065 self.conflict += rhs.conflict;
5066 }
5067}
5068
5069impl Sub for GitStatuses {
5070 type Output = GitStatuses;
5071
5072 fn sub(self, rhs: Self) -> Self::Output {
5073 GitStatuses {
5074 added: self.added - rhs.added,
5075 modified: self.modified - rhs.modified,
5076 conflict: self.conflict - rhs.conflict,
5077 }
5078 }
5079}
5080
5081impl<'a> sum_tree::Dimension<'a, EntrySummary> for GitStatuses {
5082 fn zero(_cx: &()) -> Self {
5083 Default::default()
5084 }
5085
5086 fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
5087 *self += summary.statuses
5088 }
5089}
5090
5091pub struct Traversal<'a> {
5092 cursor: sum_tree::Cursor<'a, Entry, TraversalProgress<'a>>,
5093 include_ignored: bool,
5094 include_files: bool,
5095 include_dirs: bool,
5096}
5097
5098impl<'a> Traversal<'a> {
5099 fn new(
5100 entries: &'a SumTree<Entry>,
5101 include_files: bool,
5102 include_dirs: bool,
5103 include_ignored: bool,
5104 start_path: &Path,
5105 ) -> Self {
5106 let mut cursor = entries.cursor(&());
5107 cursor.seek(&TraversalTarget::Path(start_path), Bias::Left, &());
5108 let mut traversal = Self {
5109 cursor,
5110 include_files,
5111 include_dirs,
5112 include_ignored,
5113 };
5114 if traversal.end_offset() == traversal.start_offset() {
5115 traversal.next();
5116 }
5117 traversal
5118 }
5119 pub fn advance(&mut self) -> bool {
5120 self.advance_by(1)
5121 }
5122
5123 pub fn advance_by(&mut self, count: usize) -> bool {
5124 self.cursor.seek_forward(
5125 &TraversalTarget::Count {
5126 count: self.end_offset() + count,
5127 include_dirs: self.include_dirs,
5128 include_files: self.include_files,
5129 include_ignored: self.include_ignored,
5130 },
5131 Bias::Left,
5132 &(),
5133 )
5134 }
5135
5136 pub fn advance_to_sibling(&mut self) -> bool {
5137 while let Some(entry) = self.cursor.item() {
5138 self.cursor.seek_forward(
5139 &TraversalTarget::PathSuccessor(&entry.path),
5140 Bias::Left,
5141 &(),
5142 );
5143 if let Some(entry) = self.cursor.item() {
5144 if (self.include_files || !entry.is_file())
5145 && (self.include_dirs || !entry.is_dir())
5146 && (self.include_ignored || !entry.is_ignored)
5147 {
5148 return true;
5149 }
5150 }
5151 }
5152 false
5153 }
5154
5155 pub fn back_to_parent(&mut self) -> bool {
5156 let Some(parent_path) = self.cursor.item().and_then(|entry| entry.path.parent()) else {
5157 return false;
5158 };
5159 self.cursor
5160 .seek(&TraversalTarget::Path(parent_path), Bias::Left, &())
5161 }
5162
5163 pub fn entry(&self) -> Option<&'a Entry> {
5164 self.cursor.item()
5165 }
5166
5167 pub fn start_offset(&self) -> usize {
5168 self.cursor
5169 .start()
5170 .count(self.include_files, self.include_dirs, self.include_ignored)
5171 }
5172
5173 pub fn end_offset(&self) -> usize {
5174 self.cursor
5175 .end(&())
5176 .count(self.include_files, self.include_dirs, self.include_ignored)
5177 }
5178}
5179
5180impl<'a> Iterator for Traversal<'a> {
5181 type Item = &'a Entry;
5182
5183 fn next(&mut self) -> Option<Self::Item> {
5184 if let Some(item) = self.entry() {
5185 self.advance();
5186 Some(item)
5187 } else {
5188 None
5189 }
5190 }
5191}
5192
5193#[derive(Debug)]
5194enum TraversalTarget<'a> {
5195 Path(&'a Path),
5196 PathSuccessor(&'a Path),
5197 Count {
5198 count: usize,
5199 include_files: bool,
5200 include_ignored: bool,
5201 include_dirs: bool,
5202 },
5203}
5204
5205impl<'a, 'b> SeekTarget<'a, EntrySummary, TraversalProgress<'a>> for TraversalTarget<'b> {
5206 fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: &()) -> Ordering {
5207 match self {
5208 TraversalTarget::Path(path) => path.cmp(&cursor_location.max_path),
5209 TraversalTarget::PathSuccessor(path) => {
5210 if cursor_location.max_path.starts_with(path) {
5211 Ordering::Greater
5212 } else {
5213 Ordering::Equal
5214 }
5215 }
5216 TraversalTarget::Count {
5217 count,
5218 include_files,
5219 include_dirs,
5220 include_ignored,
5221 } => Ord::cmp(
5222 count,
5223 &cursor_location.count(*include_files, *include_dirs, *include_ignored),
5224 ),
5225 }
5226 }
5227}
5228
5229impl<'a, 'b> SeekTarget<'a, EntrySummary, (TraversalProgress<'a>, GitStatuses)>
5230 for TraversalTarget<'b>
5231{
5232 fn cmp(&self, cursor_location: &(TraversalProgress<'a>, GitStatuses), _: &()) -> Ordering {
5233 self.cmp(&cursor_location.0, &())
5234 }
5235}
5236
5237pub struct ChildEntriesIter<'a> {
5238 parent_path: &'a Path,
5239 traversal: Traversal<'a>,
5240}
5241
5242impl<'a> Iterator for ChildEntriesIter<'a> {
5243 type Item = &'a Entry;
5244
5245 fn next(&mut self) -> Option<Self::Item> {
5246 if let Some(item) = self.traversal.entry() {
5247 if item.path.starts_with(self.parent_path) {
5248 self.traversal.advance_to_sibling();
5249 return Some(item);
5250 }
5251 }
5252 None
5253 }
5254}
5255
5256impl<'a> From<&'a Entry> for proto::Entry {
5257 fn from(entry: &'a Entry) -> Self {
5258 Self {
5259 id: entry.id.to_proto(),
5260 is_dir: entry.is_dir(),
5261 path: entry.path.to_string_lossy().into(),
5262 inode: entry.inode,
5263 mtime: entry.mtime.map(|time| time.into()),
5264 is_symlink: entry.is_symlink,
5265 is_ignored: entry.is_ignored,
5266 is_external: entry.is_external,
5267 git_status: entry.git_status.map(git_status_to_proto),
5268 is_fifo: entry.is_fifo,
5269 size: Some(entry.size),
5270 }
5271 }
5272}
5273
5274impl<'a> TryFrom<(&'a CharBag, proto::Entry)> for Entry {
5275 type Error = anyhow::Error;
5276
5277 fn try_from((root_char_bag, entry): (&'a CharBag, proto::Entry)) -> Result<Self> {
5278 let kind = if entry.is_dir {
5279 EntryKind::Dir
5280 } else {
5281 EntryKind::File
5282 };
5283 let path: Arc<Path> = PathBuf::from(entry.path).into();
5284 let char_bag = char_bag_for_path(*root_char_bag, &path);
5285 Ok(Entry {
5286 id: ProjectEntryId::from_proto(entry.id),
5287 kind,
5288 path,
5289 inode: entry.inode,
5290 mtime: entry.mtime.map(|time| time.into()),
5291 size: entry.size.unwrap_or(0),
5292 canonical_path: None,
5293 is_ignored: entry.is_ignored,
5294 is_external: entry.is_external,
5295 git_status: git_status_from_proto(entry.git_status),
5296 is_private: false,
5297 is_symlink: entry.is_symlink,
5298 char_bag,
5299 is_fifo: entry.is_fifo,
5300 })
5301 }
5302}
5303
5304fn git_status_from_proto(git_status: Option<i32>) -> Option<GitFileStatus> {
5305 git_status.and_then(|status| {
5306 proto::GitStatus::from_i32(status).map(|status| match status {
5307 proto::GitStatus::Added => GitFileStatus::Added,
5308 proto::GitStatus::Modified => GitFileStatus::Modified,
5309 proto::GitStatus::Conflict => GitFileStatus::Conflict,
5310 })
5311 })
5312}
5313
5314fn git_status_to_proto(status: GitFileStatus) -> i32 {
5315 match status {
5316 GitFileStatus::Added => proto::GitStatus::Added as i32,
5317 GitFileStatus::Modified => proto::GitStatus::Modified as i32,
5318 GitFileStatus::Conflict => proto::GitStatus::Conflict as i32,
5319 }
5320}
5321
5322#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
5323pub struct ProjectEntryId(usize);
5324
5325impl ProjectEntryId {
5326 pub const MAX: Self = Self(usize::MAX);
5327 pub const MIN: Self = Self(usize::MIN);
5328
5329 pub fn new(counter: &AtomicUsize) -> Self {
5330 Self(counter.fetch_add(1, SeqCst))
5331 }
5332
5333 pub fn from_proto(id: u64) -> Self {
5334 Self(id as usize)
5335 }
5336
5337 pub fn to_proto(&self) -> u64 {
5338 self.0 as u64
5339 }
5340
5341 pub fn to_usize(&self) -> usize {
5342 self.0
5343 }
5344}
5345
5346#[cfg(any(test, feature = "test-support"))]
5347impl CreatedEntry {
5348 pub fn to_included(self) -> Option<Entry> {
5349 match self {
5350 CreatedEntry::Included(entry) => Some(entry),
5351 CreatedEntry::Excluded { .. } => None,
5352 }
5353 }
5354}