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