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