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