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