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