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