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