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