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