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