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