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