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