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