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