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