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