1use crate::{ProjectEntryId, RemoveOptions};
2
3use super::{
4 fs::{self, Fs},
5 ignore::IgnoreStack,
6 DiagnosticSummary,
7};
8use ::ignore::gitignore::{Gitignore, GitignoreBuilder};
9use anyhow::{anyhow, Context, Result};
10use client::{proto, Client};
11use clock::ReplicaId;
12use collections::{HashMap, VecDeque};
13use futures::{
14 channel::{
15 mpsc::{self, UnboundedSender},
16 oneshot,
17 },
18 Stream, StreamExt,
19};
20use fuzzy::CharBag;
21use gpui::{
22 executor, AppContext, AsyncAppContext, Entity, ModelContext, ModelHandle, MutableAppContext,
23 Task,
24};
25use language::{
26 proto::{deserialize_version, serialize_version},
27 Buffer, DiagnosticEntry, PointUtf16, Rope,
28};
29use lazy_static::lazy_static;
30use parking_lot::Mutex;
31use postage::{
32 prelude::{Sink as _, Stream as _},
33 watch,
34};
35use smol::channel::{self, Sender};
36use std::{
37 any::Any,
38 cmp::{self, Ordering},
39 convert::TryFrom,
40 ffi::{OsStr, OsString},
41 fmt,
42 future::Future,
43 ops::{Deref, DerefMut},
44 os::unix::prelude::{OsStrExt, OsStringExt},
45 path::{Path, PathBuf},
46 sync::{atomic::AtomicUsize, Arc},
47 task::Poll,
48 time::{Duration, SystemTime},
49};
50use sum_tree::{Bias, Edit, SeekTarget, SumTree, TreeMap};
51use util::{ResultExt, TryFutureExt};
52
53lazy_static! {
54 static ref GITIGNORE: &'static OsStr = OsStr::new(".gitignore");
55}
56
57#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash, PartialOrd, Ord)]
58pub struct WorktreeId(usize);
59
60pub enum Worktree {
61 Local(LocalWorktree),
62 Remote(RemoteWorktree),
63}
64
65pub struct LocalWorktree {
66 snapshot: LocalSnapshot,
67 background_snapshot: Arc<Mutex<LocalSnapshot>>,
68 last_scan_state_rx: watch::Receiver<ScanState>,
69 _background_scanner_task: Option<Task<()>>,
70 poll_task: Option<Task<()>>,
71 share: Option<ShareState>,
72 diagnostics: HashMap<Arc<Path>, Vec<DiagnosticEntry<PointUtf16>>>,
73 diagnostic_summaries: TreeMap<PathKey, DiagnosticSummary>,
74 client: Arc<Client>,
75 fs: Arc<dyn Fs>,
76 visible: bool,
77}
78
79pub struct RemoteWorktree {
80 pub snapshot: Snapshot,
81 pub(crate) background_snapshot: Arc<Mutex<Snapshot>>,
82 project_id: u64,
83 client: Arc<Client>,
84 updates_tx: Option<UnboundedSender<proto::UpdateWorktree>>,
85 snapshot_subscriptions: VecDeque<(usize, oneshot::Sender<()>)>,
86 replica_id: ReplicaId,
87 diagnostic_summaries: TreeMap<PathKey, DiagnosticSummary>,
88 visible: bool,
89}
90
91#[derive(Clone)]
92pub struct Snapshot {
93 id: WorktreeId,
94 root_name: String,
95 root_char_bag: CharBag,
96 entries_by_path: SumTree<Entry>,
97 entries_by_id: SumTree<PathEntry>,
98 scan_id: usize,
99 is_complete: bool,
100}
101
102#[derive(Clone)]
103pub struct LocalSnapshot {
104 abs_path: Arc<Path>,
105 ignores: HashMap<Arc<Path>, (Arc<Gitignore>, usize)>,
106 removed_entry_ids: HashMap<u64, ProjectEntryId>,
107 next_entry_id: Arc<AtomicUsize>,
108 snapshot: Snapshot,
109}
110
111impl Deref for LocalSnapshot {
112 type Target = Snapshot;
113
114 fn deref(&self) -> &Self::Target {
115 &self.snapshot
116 }
117}
118
119impl DerefMut for LocalSnapshot {
120 fn deref_mut(&mut self) -> &mut Self::Target {
121 &mut self.snapshot
122 }
123}
124
125#[derive(Clone, Debug)]
126enum ScanState {
127 Idle,
128 /// The worktree is performing its initial scan of the filesystem.
129 Initializing,
130 /// The worktree is updating in response to filesystem events.
131 Updating,
132 Err(Arc<anyhow::Error>),
133}
134
135struct ShareState {
136 project_id: u64,
137 snapshots_tx: watch::Sender<LocalSnapshot>,
138 _maintain_remote_snapshot: Option<Task<Option<()>>>,
139}
140
141pub enum Event {
142 UpdatedEntries,
143}
144
145impl Entity for Worktree {
146 type Event = Event;
147}
148
149impl Worktree {
150 pub async fn local(
151 client: Arc<Client>,
152 path: impl Into<Arc<Path>>,
153 visible: bool,
154 fs: Arc<dyn Fs>,
155 next_entry_id: Arc<AtomicUsize>,
156 cx: &mut AsyncAppContext,
157 ) -> Result<ModelHandle<Self>> {
158 let (tree, scan_states_tx) =
159 LocalWorktree::new(client, path, visible, fs.clone(), next_entry_id, cx).await?;
160 tree.update(cx, |tree, cx| {
161 let tree = tree.as_local_mut().unwrap();
162 let abs_path = tree.abs_path().clone();
163 let background_snapshot = tree.background_snapshot.clone();
164 let background = cx.background().clone();
165 tree._background_scanner_task = Some(cx.background().spawn(async move {
166 let events = fs.watch(&abs_path, Duration::from_millis(100)).await;
167 let scanner =
168 BackgroundScanner::new(background_snapshot, scan_states_tx, fs, background);
169 scanner.run(events).await;
170 }));
171 });
172 Ok(tree)
173 }
174
175 pub fn remote(
176 project_remote_id: u64,
177 replica_id: ReplicaId,
178 worktree: proto::WorktreeMetadata,
179 client: Arc<Client>,
180 cx: &mut MutableAppContext,
181 ) -> ModelHandle<Self> {
182 let remote_id = worktree.id;
183 let root_char_bag: CharBag = worktree
184 .root_name
185 .chars()
186 .map(|c| c.to_ascii_lowercase())
187 .collect();
188 let root_name = worktree.root_name.clone();
189 let visible = worktree.visible;
190 let snapshot = Snapshot {
191 id: WorktreeId(remote_id as usize),
192 root_name,
193 root_char_bag,
194 entries_by_path: Default::default(),
195 entries_by_id: Default::default(),
196 scan_id: 0,
197 is_complete: false,
198 };
199
200 let (updates_tx, mut updates_rx) = mpsc::unbounded();
201 let background_snapshot = Arc::new(Mutex::new(snapshot.clone()));
202 let (mut snapshot_updated_tx, mut snapshot_updated_rx) = watch::channel();
203 let worktree_handle = cx.add_model(|_: &mut ModelContext<Worktree>| {
204 Worktree::Remote(RemoteWorktree {
205 project_id: project_remote_id,
206 replica_id,
207 snapshot: snapshot.clone(),
208 background_snapshot: background_snapshot.clone(),
209 updates_tx: Some(updates_tx),
210 snapshot_subscriptions: Default::default(),
211 client: client.clone(),
212 diagnostic_summaries: Default::default(),
213 visible,
214 })
215 });
216
217 cx.background()
218 .spawn(async move {
219 while let Some(update) = updates_rx.next().await {
220 if let Err(error) = background_snapshot.lock().apply_remote_update(update) {
221 log::error!("error applying worktree update: {}", error);
222 }
223 snapshot_updated_tx.send(()).await.ok();
224 }
225 })
226 .detach();
227
228 cx.spawn(|mut cx| {
229 let this = worktree_handle.downgrade();
230 async move {
231 while let Some(_) = snapshot_updated_rx.recv().await {
232 if let Some(this) = this.upgrade(&cx) {
233 this.update(&mut cx, |this, cx| {
234 this.poll_snapshot(cx);
235 let this = this.as_remote_mut().unwrap();
236 while let Some((scan_id, _)) = this.snapshot_subscriptions.front() {
237 if this.observed_snapshot(*scan_id) {
238 let (_, tx) = this.snapshot_subscriptions.pop_front().unwrap();
239 let _ = tx.send(());
240 } else {
241 break;
242 }
243 }
244 });
245 } else {
246 break;
247 }
248 }
249 }
250 })
251 .detach();
252
253 worktree_handle
254 }
255
256 pub fn as_local(&self) -> Option<&LocalWorktree> {
257 if let Worktree::Local(worktree) = self {
258 Some(worktree)
259 } else {
260 None
261 }
262 }
263
264 pub fn as_remote(&self) -> Option<&RemoteWorktree> {
265 if let Worktree::Remote(worktree) = self {
266 Some(worktree)
267 } else {
268 None
269 }
270 }
271
272 pub fn as_local_mut(&mut self) -> Option<&mut LocalWorktree> {
273 if let Worktree::Local(worktree) = self {
274 Some(worktree)
275 } else {
276 None
277 }
278 }
279
280 pub fn as_remote_mut(&mut self) -> Option<&mut RemoteWorktree> {
281 if let Worktree::Remote(worktree) = self {
282 Some(worktree)
283 } else {
284 None
285 }
286 }
287
288 pub fn is_local(&self) -> bool {
289 matches!(self, Worktree::Local(_))
290 }
291
292 pub fn is_remote(&self) -> bool {
293 !self.is_local()
294 }
295
296 pub fn snapshot(&self) -> Snapshot {
297 match self {
298 Worktree::Local(worktree) => worktree.snapshot().snapshot,
299 Worktree::Remote(worktree) => worktree.snapshot(),
300 }
301 }
302
303 pub fn scan_id(&self) -> usize {
304 match self {
305 Worktree::Local(worktree) => worktree.snapshot.scan_id,
306 Worktree::Remote(worktree) => worktree.snapshot.scan_id,
307 }
308 }
309
310 pub fn is_visible(&self) -> bool {
311 match self {
312 Worktree::Local(worktree) => worktree.visible,
313 Worktree::Remote(worktree) => worktree.visible,
314 }
315 }
316
317 pub fn replica_id(&self) -> ReplicaId {
318 match self {
319 Worktree::Local(_) => 0,
320 Worktree::Remote(worktree) => worktree.replica_id,
321 }
322 }
323
324 pub fn diagnostic_summaries<'a>(
325 &'a self,
326 ) -> impl Iterator<Item = (Arc<Path>, DiagnosticSummary)> + 'a {
327 match self {
328 Worktree::Local(worktree) => &worktree.diagnostic_summaries,
329 Worktree::Remote(worktree) => &worktree.diagnostic_summaries,
330 }
331 .iter()
332 .map(|(path, summary)| (path.0.clone(), summary.clone()))
333 }
334
335 fn poll_snapshot(&mut self, cx: &mut ModelContext<Self>) {
336 match self {
337 Self::Local(worktree) => worktree.poll_snapshot(cx),
338 Self::Remote(worktree) => worktree.poll_snapshot(cx),
339 };
340 }
341}
342
343impl LocalWorktree {
344 async fn new(
345 client: Arc<Client>,
346 path: impl Into<Arc<Path>>,
347 visible: bool,
348 fs: Arc<dyn Fs>,
349 next_entry_id: Arc<AtomicUsize>,
350 cx: &mut AsyncAppContext,
351 ) -> Result<(ModelHandle<Worktree>, UnboundedSender<ScanState>)> {
352 let abs_path = path.into();
353 let path: Arc<Path> = Arc::from(Path::new(""));
354
355 // After determining whether the root entry is a file or a directory, populate the
356 // snapshot's "root name", which will be used for the purpose of fuzzy matching.
357 let root_name = abs_path
358 .file_name()
359 .map_or(String::new(), |f| f.to_string_lossy().to_string());
360 let root_char_bag = root_name.chars().map(|c| c.to_ascii_lowercase()).collect();
361 let metadata = fs
362 .metadata(&abs_path)
363 .await
364 .context("failed to stat worktree path")?;
365
366 let (scan_states_tx, mut scan_states_rx) = mpsc::unbounded();
367 let (mut last_scan_state_tx, last_scan_state_rx) =
368 watch::channel_with(ScanState::Initializing);
369 let tree = cx.add_model(move |cx: &mut ModelContext<Worktree>| {
370 let mut snapshot = LocalSnapshot {
371 abs_path,
372 ignores: Default::default(),
373 removed_entry_ids: Default::default(),
374 next_entry_id,
375 snapshot: Snapshot {
376 id: WorktreeId::from_usize(cx.model_id()),
377 root_name: root_name.clone(),
378 root_char_bag,
379 entries_by_path: Default::default(),
380 entries_by_id: Default::default(),
381 scan_id: 0,
382 is_complete: true,
383 },
384 };
385 if let Some(metadata) = metadata {
386 let entry = Entry::new(
387 path.into(),
388 &metadata,
389 &snapshot.next_entry_id,
390 snapshot.root_char_bag,
391 );
392 snapshot.insert_entry(entry, fs.as_ref());
393 }
394
395 let tree = Self {
396 snapshot: snapshot.clone(),
397 background_snapshot: Arc::new(Mutex::new(snapshot)),
398 last_scan_state_rx,
399 _background_scanner_task: None,
400 share: None,
401 poll_task: None,
402 diagnostics: Default::default(),
403 diagnostic_summaries: Default::default(),
404 client,
405 fs,
406 visible,
407 };
408
409 cx.spawn_weak(|this, mut cx| async move {
410 while let Some(scan_state) = scan_states_rx.next().await {
411 if let Some(this) = this.upgrade(&cx) {
412 last_scan_state_tx.blocking_send(scan_state).ok();
413 this.update(&mut cx, |this, cx| this.poll_snapshot(cx));
414 } else {
415 break;
416 }
417 }
418 })
419 .detach();
420
421 Worktree::Local(tree)
422 });
423
424 Ok((tree, scan_states_tx))
425 }
426
427 pub fn contains_abs_path(&self, path: &Path) -> bool {
428 path.starts_with(&self.abs_path)
429 }
430
431 fn absolutize(&self, path: &Path) -> PathBuf {
432 if path.file_name().is_some() {
433 self.abs_path.join(path)
434 } else {
435 self.abs_path.to_path_buf()
436 }
437 }
438
439 pub(crate) fn load_buffer(
440 &mut self,
441 path: &Path,
442 cx: &mut ModelContext<Worktree>,
443 ) -> Task<Result<ModelHandle<Buffer>>> {
444 let path = Arc::from(path);
445 cx.spawn(move |this, mut cx| async move {
446 let (file, contents) = this
447 .update(&mut cx, |t, cx| t.as_local().unwrap().load(&path, cx))
448 .await?;
449 Ok(cx.add_model(|cx| Buffer::from_file(0, contents, Arc::new(file), cx)))
450 })
451 }
452
453 pub fn diagnostics_for_path(&self, path: &Path) -> Option<Vec<DiagnosticEntry<PointUtf16>>> {
454 self.diagnostics.get(path).cloned()
455 }
456
457 pub fn update_diagnostics(
458 &mut self,
459 language_server_id: usize,
460 worktree_path: Arc<Path>,
461 diagnostics: Vec<DiagnosticEntry<PointUtf16>>,
462 _: &mut ModelContext<Worktree>,
463 ) -> Result<bool> {
464 self.diagnostics.remove(&worktree_path);
465 let old_summary = self
466 .diagnostic_summaries
467 .remove(&PathKey(worktree_path.clone()))
468 .unwrap_or_default();
469 let new_summary = DiagnosticSummary::new(language_server_id, &diagnostics);
470 if !new_summary.is_empty() {
471 self.diagnostic_summaries
472 .insert(PathKey(worktree_path.clone()), new_summary);
473 self.diagnostics.insert(worktree_path.clone(), diagnostics);
474 }
475
476 let updated = !old_summary.is_empty() || !new_summary.is_empty();
477 if updated {
478 if let Some(share) = self.share.as_ref() {
479 self.client
480 .send(proto::UpdateDiagnosticSummary {
481 project_id: share.project_id,
482 worktree_id: self.id().to_proto(),
483 summary: Some(proto::DiagnosticSummary {
484 path: worktree_path.to_string_lossy().to_string(),
485 language_server_id: language_server_id as u64,
486 error_count: new_summary.error_count as u32,
487 warning_count: new_summary.warning_count as u32,
488 }),
489 })
490 .log_err();
491 }
492 }
493
494 Ok(updated)
495 }
496
497 fn poll_snapshot(&mut self, cx: &mut ModelContext<Worktree>) {
498 match self.scan_state() {
499 ScanState::Idle => {
500 self.poll_task.take();
501 self.snapshot = self.background_snapshot.lock().clone();
502 if let Some(share) = self.share.as_mut() {
503 *share.snapshots_tx.borrow_mut() = self.snapshot.clone();
504 }
505 cx.emit(Event::UpdatedEntries);
506 }
507 ScanState::Initializing => {
508 self.snapshot = self.background_snapshot.lock().clone();
509 if self.poll_task.is_none() {
510 let is_fake_fs = self.fs.is_fake();
511 self.poll_task = Some(cx.spawn_weak(|this, mut cx| async move {
512 if is_fake_fs {
513 #[cfg(any(test, feature = "test-support"))]
514 cx.background().simulate_random_delay().await;
515 } else {
516 smol::Timer::after(Duration::from_millis(100)).await;
517 }
518 if let Some(this) = this.upgrade(&cx) {
519 this.update(&mut cx, |this, cx| {
520 this.as_local_mut().unwrap().poll_task = None;
521 this.poll_snapshot(cx);
522 });
523 }
524 }));
525 }
526 cx.emit(Event::UpdatedEntries);
527 }
528 ScanState::Updating => {}
529 ScanState::Err(_) => {}
530 }
531 cx.notify();
532 }
533
534 pub fn scan_complete(&self) -> impl Future<Output = ()> {
535 let mut scan_state_rx = self.last_scan_state_rx.clone();
536 async move {
537 let mut scan_state = Some(scan_state_rx.borrow().clone());
538 while let Some(ScanState::Initializing | ScanState::Updating) = scan_state {
539 scan_state = scan_state_rx.recv().await;
540 }
541 }
542 }
543
544 fn scan_state(&self) -> ScanState {
545 self.last_scan_state_rx.borrow().clone()
546 }
547
548 pub fn snapshot(&self) -> LocalSnapshot {
549 self.snapshot.clone()
550 }
551
552 pub fn metadata_proto(&self) -> proto::WorktreeMetadata {
553 proto::WorktreeMetadata {
554 id: self.id().to_proto(),
555 root_name: self.root_name().to_string(),
556 visible: self.visible,
557 }
558 }
559
560 fn load(&self, path: &Path, cx: &mut ModelContext<Worktree>) -> Task<Result<(File, String)>> {
561 let handle = cx.handle();
562 let path = Arc::from(path);
563 let abs_path = self.absolutize(&path);
564 let fs = self.fs.clone();
565 cx.spawn(|this, mut cx| async move {
566 let text = fs.load(&abs_path).await?;
567 // Eagerly populate the snapshot with an updated entry for the loaded file
568 let entry = this
569 .update(&mut cx, |this, cx| {
570 this.as_local()
571 .unwrap()
572 .refresh_entry(path, abs_path, None, cx)
573 })
574 .await?;
575 this.update(&mut cx, |this, cx| this.poll_snapshot(cx));
576 Ok((
577 File {
578 entry_id: Some(entry.id),
579 worktree: handle,
580 path: entry.path,
581 mtime: entry.mtime,
582 is_local: true,
583 },
584 text,
585 ))
586 })
587 }
588
589 pub fn save_buffer_as(
590 &self,
591 buffer_handle: ModelHandle<Buffer>,
592 path: impl Into<Arc<Path>>,
593 cx: &mut ModelContext<Worktree>,
594 ) -> Task<Result<()>> {
595 let buffer = buffer_handle.read(cx);
596 let text = buffer.as_rope().clone();
597 let fingerprint = text.fingerprint();
598 let version = buffer.version();
599 let save = self.write_file(path, text, cx);
600 let handle = cx.handle();
601 cx.as_mut().spawn(|mut cx| async move {
602 let entry = save.await?;
603 let file = File {
604 entry_id: Some(entry.id),
605 worktree: handle,
606 path: entry.path,
607 mtime: entry.mtime,
608 is_local: true,
609 };
610
611 buffer_handle.update(&mut cx, |buffer, cx| {
612 buffer.did_save(version, fingerprint, file.mtime, Some(Arc::new(file)), cx);
613 });
614
615 Ok(())
616 })
617 }
618
619 pub fn create_entry(
620 &self,
621 path: impl Into<Arc<Path>>,
622 is_dir: bool,
623 cx: &mut ModelContext<Worktree>,
624 ) -> Task<Result<Entry>> {
625 self.write_entry_internal(
626 path,
627 if is_dir {
628 None
629 } else {
630 Some(Default::default())
631 },
632 cx,
633 )
634 }
635
636 pub fn write_file(
637 &self,
638 path: impl Into<Arc<Path>>,
639 text: Rope,
640 cx: &mut ModelContext<Worktree>,
641 ) -> Task<Result<Entry>> {
642 self.write_entry_internal(path, Some(text), cx)
643 }
644
645 pub fn delete_entry(
646 &self,
647 entry_id: ProjectEntryId,
648 cx: &mut ModelContext<Worktree>,
649 ) -> Option<Task<Result<()>>> {
650 let entry = self.entry_for_id(entry_id)?.clone();
651 let abs_path = self.absolutize(&entry.path);
652 let delete = cx.background().spawn({
653 let fs = self.fs.clone();
654 let abs_path = abs_path.clone();
655 async move {
656 if entry.is_file() {
657 fs.remove_file(&abs_path, Default::default()).await
658 } else {
659 fs.remove_dir(
660 &abs_path,
661 RemoveOptions {
662 recursive: true,
663 ignore_if_not_exists: false,
664 },
665 )
666 .await
667 }
668 }
669 });
670
671 Some(cx.spawn(|this, mut cx| async move {
672 delete.await?;
673 this.update(&mut cx, |this, cx| {
674 let this = this.as_local_mut().unwrap();
675 {
676 let mut snapshot = this.background_snapshot.lock();
677 snapshot.delete_entry(entry_id);
678 }
679 this.poll_snapshot(cx);
680 });
681 Ok(())
682 }))
683 }
684
685 pub fn rename_entry(
686 &self,
687 entry_id: ProjectEntryId,
688 new_path: impl Into<Arc<Path>>,
689 cx: &mut ModelContext<Worktree>,
690 ) -> Option<Task<Result<Entry>>> {
691 let old_path = self.entry_for_id(entry_id)?.path.clone();
692 let new_path = new_path.into();
693 let abs_old_path = self.absolutize(&old_path);
694 let abs_new_path = self.absolutize(&new_path);
695 let rename = cx.background().spawn({
696 let fs = self.fs.clone();
697 let abs_new_path = abs_new_path.clone();
698 async move {
699 fs.rename(&abs_old_path, &abs_new_path, Default::default())
700 .await
701 }
702 });
703
704 Some(cx.spawn(|this, mut cx| async move {
705 rename.await?;
706 let entry = this
707 .update(&mut cx, |this, cx| {
708 this.as_local_mut().unwrap().refresh_entry(
709 new_path.clone(),
710 abs_new_path,
711 Some(old_path),
712 cx,
713 )
714 })
715 .await?;
716 this.update(&mut cx, |this, cx| {
717 let this = this.as_local_mut().unwrap();
718 this.poll_snapshot(cx);
719 });
720 Ok(entry)
721 }))
722 }
723
724 pub fn copy_entry(
725 &self,
726 entry_id: ProjectEntryId,
727 new_path: impl Into<Arc<Path>>,
728 cx: &mut ModelContext<Worktree>,
729 ) -> Option<Task<Result<Entry>>> {
730 let old_path = self.entry_for_id(entry_id)?.path.clone();
731 let new_path = new_path.into();
732 let abs_old_path = self.absolutize(&old_path);
733 let abs_new_path = self.absolutize(&new_path);
734 let copy = cx.background().spawn({
735 let fs = self.fs.clone();
736 let abs_new_path = abs_new_path.clone();
737 async move {
738 fs.copy(&abs_old_path, &abs_new_path, Default::default())
739 .await
740 }
741 });
742
743 Some(cx.spawn(|this, mut cx| async move {
744 copy.await?;
745 let entry = this
746 .update(&mut cx, |this, cx| {
747 this.as_local_mut().unwrap().refresh_entry(
748 new_path.clone(),
749 abs_new_path,
750 None,
751 cx,
752 )
753 })
754 .await?;
755 this.update(&mut cx, |this, cx| {
756 let this = this.as_local_mut().unwrap();
757 this.poll_snapshot(cx);
758 });
759 Ok(entry)
760 }))
761 }
762
763 fn write_entry_internal(
764 &self,
765 path: impl Into<Arc<Path>>,
766 text_if_file: Option<Rope>,
767 cx: &mut ModelContext<Worktree>,
768 ) -> Task<Result<Entry>> {
769 let path = path.into();
770 let abs_path = self.absolutize(&path);
771 let write = cx.background().spawn({
772 let fs = self.fs.clone();
773 let abs_path = abs_path.clone();
774 async move {
775 if let Some(text) = text_if_file {
776 fs.save(&abs_path, &text).await
777 } else {
778 fs.create_dir(&abs_path).await
779 }
780 }
781 });
782
783 cx.spawn(|this, mut cx| async move {
784 write.await?;
785 let entry = this
786 .update(&mut cx, |this, cx| {
787 this.as_local_mut()
788 .unwrap()
789 .refresh_entry(path, abs_path, None, cx)
790 })
791 .await?;
792 this.update(&mut cx, |this, cx| {
793 let this = this.as_local_mut().unwrap();
794 this.poll_snapshot(cx);
795 });
796 Ok(entry)
797 })
798 }
799
800 fn refresh_entry(
801 &self,
802 path: Arc<Path>,
803 abs_path: PathBuf,
804 old_path: Option<Arc<Path>>,
805 cx: &mut ModelContext<Worktree>,
806 ) -> Task<Result<Entry>> {
807 let fs = self.fs.clone();
808 let root_char_bag;
809 let next_entry_id;
810 {
811 let snapshot = self.background_snapshot.lock();
812 root_char_bag = snapshot.root_char_bag;
813 next_entry_id = snapshot.next_entry_id.clone();
814 }
815 cx.spawn_weak(|this, mut cx| async move {
816 let mut entry = Entry::new(
817 path.clone(),
818 &fs.metadata(&abs_path)
819 .await?
820 .ok_or_else(|| anyhow!("could not read saved file metadata"))?,
821 &next_entry_id,
822 root_char_bag,
823 );
824
825 let this = this
826 .upgrade(&cx)
827 .ok_or_else(|| anyhow!("worktree was dropped"))?;
828 this.update(&mut cx, |this, cx| {
829 let this = this.as_local_mut().unwrap();
830 let inserted_entry;
831 {
832 let mut snapshot = this.background_snapshot.lock();
833 entry.is_ignored = snapshot
834 .ignore_stack_for_path(&path, entry.is_dir())
835 .is_path_ignored(&path, entry.is_dir());
836 if let Some(old_path) = old_path {
837 snapshot.remove_path(&old_path);
838 }
839 inserted_entry = snapshot.insert_entry(entry, fs.as_ref());
840 snapshot.scan_id += 1;
841 }
842 this.poll_snapshot(cx);
843 Ok(inserted_entry)
844 })
845 })
846 }
847
848 pub fn share(&mut self, project_id: u64, cx: &mut ModelContext<Worktree>) -> Task<Result<()>> {
849 let (share_tx, share_rx) = oneshot::channel();
850
851 if self.share.is_some() {
852 let _ = share_tx.send(Ok(()));
853 } else {
854 let (snapshots_tx, mut snapshots_rx) = watch::channel_with(self.snapshot());
855 let rpc = self.client.clone();
856 let worktree_id = cx.model_id() as u64;
857 let maintain_remote_snapshot = cx.background().spawn({
858 let rpc = rpc.clone();
859 let diagnostic_summaries = self.diagnostic_summaries.clone();
860 async move {
861 let mut prev_snapshot = match snapshots_rx.recv().await {
862 Some(snapshot) => {
863 let update = proto::UpdateWorktree {
864 project_id,
865 worktree_id,
866 root_name: snapshot.root_name().to_string(),
867 updated_entries: snapshot
868 .entries_by_path
869 .iter()
870 .map(Into::into)
871 .collect(),
872 removed_entries: Default::default(),
873 scan_id: snapshot.scan_id as u64,
874 is_last_update: true,
875 };
876 if let Err(error) = send_worktree_update(&rpc, update).await {
877 let _ = share_tx.send(Err(error));
878 return Err(anyhow!("failed to send initial update worktree"));
879 } else {
880 let _ = share_tx.send(Ok(()));
881 snapshot
882 }
883 }
884 None => {
885 share_tx
886 .send(Err(anyhow!("worktree dropped before share completed")))
887 .ok();
888 return Err(anyhow!("failed to send initial update worktree"));
889 }
890 };
891
892 for (path, summary) in diagnostic_summaries.iter() {
893 rpc.send(proto::UpdateDiagnosticSummary {
894 project_id,
895 worktree_id,
896 summary: Some(summary.to_proto(&path.0)),
897 })?;
898 }
899
900 while let Some(snapshot) = snapshots_rx.recv().await {
901 send_worktree_update(
902 &rpc,
903 snapshot.build_update(&prev_snapshot, project_id, worktree_id, true),
904 )
905 .await?;
906 prev_snapshot = snapshot;
907 }
908
909 Ok::<_, anyhow::Error>(())
910 }
911 .log_err()
912 });
913 self.share = Some(ShareState {
914 project_id,
915 snapshots_tx,
916 _maintain_remote_snapshot: Some(maintain_remote_snapshot),
917 });
918 }
919
920 cx.foreground().spawn(async move {
921 share_rx
922 .await
923 .unwrap_or_else(|_| Err(anyhow!("share ended")))
924 })
925 }
926
927 pub fn unshare(&mut self) {
928 self.share.take();
929 }
930
931 pub fn is_shared(&self) -> bool {
932 self.share.is_some()
933 }
934}
935
936impl RemoteWorktree {
937 fn snapshot(&self) -> Snapshot {
938 self.snapshot.clone()
939 }
940
941 fn poll_snapshot(&mut self, cx: &mut ModelContext<Worktree>) {
942 self.snapshot = self.background_snapshot.lock().clone();
943 cx.emit(Event::UpdatedEntries);
944 cx.notify();
945 }
946
947 pub fn disconnected_from_host(&mut self) {
948 self.updates_tx.take();
949 self.snapshot_subscriptions.clear();
950 }
951
952 pub fn update_from_remote(&mut self, update: proto::UpdateWorktree) {
953 if let Some(updates_tx) = &self.updates_tx {
954 updates_tx
955 .unbounded_send(update)
956 .expect("consumer runs to completion");
957 }
958 }
959
960 fn observed_snapshot(&self, scan_id: usize) -> bool {
961 self.scan_id > scan_id || (self.scan_id == scan_id && self.is_complete)
962 }
963
964 fn wait_for_snapshot(&mut self, scan_id: usize) -> impl Future<Output = ()> {
965 let (tx, rx) = oneshot::channel();
966 if self.observed_snapshot(scan_id) {
967 let _ = tx.send(());
968 } else {
969 match self
970 .snapshot_subscriptions
971 .binary_search_by_key(&scan_id, |probe| probe.0)
972 {
973 Ok(ix) | Err(ix) => self.snapshot_subscriptions.insert(ix, (scan_id, tx)),
974 }
975 }
976
977 async move {
978 let _ = rx.await;
979 }
980 }
981
982 pub fn update_diagnostic_summary(
983 &mut self,
984 path: Arc<Path>,
985 summary: &proto::DiagnosticSummary,
986 ) {
987 let summary = DiagnosticSummary {
988 language_server_id: summary.language_server_id as usize,
989 error_count: summary.error_count as usize,
990 warning_count: summary.warning_count as usize,
991 };
992 if summary.is_empty() {
993 self.diagnostic_summaries.remove(&PathKey(path.clone()));
994 } else {
995 self.diagnostic_summaries
996 .insert(PathKey(path.clone()), summary);
997 }
998 }
999
1000 pub fn insert_entry(
1001 &mut self,
1002 entry: proto::Entry,
1003 scan_id: usize,
1004 cx: &mut ModelContext<Worktree>,
1005 ) -> Task<Result<Entry>> {
1006 let wait_for_snapshot = self.wait_for_snapshot(scan_id);
1007 cx.spawn(|this, mut cx| async move {
1008 wait_for_snapshot.await;
1009 this.update(&mut cx, |worktree, _| {
1010 let worktree = worktree.as_remote_mut().unwrap();
1011 let mut snapshot = worktree.background_snapshot.lock();
1012 let entry = snapshot.insert_entry(entry);
1013 worktree.snapshot = snapshot.clone();
1014 entry
1015 })
1016 })
1017 }
1018
1019 pub(crate) fn delete_entry(
1020 &mut self,
1021 id: ProjectEntryId,
1022 scan_id: usize,
1023 cx: &mut ModelContext<Worktree>,
1024 ) -> Task<Result<()>> {
1025 let wait_for_snapshot = self.wait_for_snapshot(scan_id);
1026 cx.spawn(|this, mut cx| async move {
1027 wait_for_snapshot.await;
1028 this.update(&mut cx, |worktree, _| {
1029 let worktree = worktree.as_remote_mut().unwrap();
1030 let mut snapshot = worktree.background_snapshot.lock();
1031 snapshot.delete_entry(id);
1032 worktree.snapshot = snapshot.clone();
1033 });
1034 Ok(())
1035 })
1036 }
1037}
1038
1039impl Snapshot {
1040 pub fn id(&self) -> WorktreeId {
1041 self.id
1042 }
1043
1044 pub fn contains_entry(&self, entry_id: ProjectEntryId) -> bool {
1045 self.entries_by_id.get(&entry_id, &()).is_some()
1046 }
1047
1048 pub(crate) fn insert_entry(&mut self, entry: proto::Entry) -> Result<Entry> {
1049 let entry = Entry::try_from((&self.root_char_bag, entry))?;
1050 let old_entry = self.entries_by_id.insert_or_replace(
1051 PathEntry {
1052 id: entry.id,
1053 path: entry.path.clone(),
1054 is_ignored: entry.is_ignored,
1055 scan_id: 0,
1056 },
1057 &(),
1058 );
1059 if let Some(old_entry) = old_entry {
1060 self.entries_by_path.remove(&PathKey(old_entry.path), &());
1061 }
1062 self.entries_by_path.insert_or_replace(entry.clone(), &());
1063 Ok(entry)
1064 }
1065
1066 fn delete_entry(&mut self, entry_id: ProjectEntryId) -> bool {
1067 if let Some(removed_entry) = self.entries_by_id.remove(&entry_id, &()) {
1068 self.entries_by_path = {
1069 let mut cursor = self.entries_by_path.cursor();
1070 let mut new_entries_by_path =
1071 cursor.slice(&TraversalTarget::Path(&removed_entry.path), Bias::Left, &());
1072 while let Some(entry) = cursor.item() {
1073 if entry.path.starts_with(&removed_entry.path) {
1074 self.entries_by_id.remove(&entry.id, &());
1075 cursor.next(&());
1076 } else {
1077 break;
1078 }
1079 }
1080 new_entries_by_path.push_tree(cursor.suffix(&()), &());
1081 new_entries_by_path
1082 };
1083
1084 true
1085 } else {
1086 false
1087 }
1088 }
1089
1090 pub(crate) fn apply_remote_update(&mut self, update: proto::UpdateWorktree) -> Result<()> {
1091 let mut entries_by_path_edits = Vec::new();
1092 let mut entries_by_id_edits = Vec::new();
1093 for entry_id in update.removed_entries {
1094 let entry = self
1095 .entry_for_id(ProjectEntryId::from_proto(entry_id))
1096 .ok_or_else(|| anyhow!("unknown entry {}", entry_id))?;
1097 entries_by_path_edits.push(Edit::Remove(PathKey(entry.path.clone())));
1098 entries_by_id_edits.push(Edit::Remove(entry.id));
1099 }
1100
1101 for entry in update.updated_entries {
1102 let entry = Entry::try_from((&self.root_char_bag, entry))?;
1103 if let Some(PathEntry { path, .. }) = self.entries_by_id.get(&entry.id, &()) {
1104 entries_by_path_edits.push(Edit::Remove(PathKey(path.clone())));
1105 }
1106 entries_by_id_edits.push(Edit::Insert(PathEntry {
1107 id: entry.id,
1108 path: entry.path.clone(),
1109 is_ignored: entry.is_ignored,
1110 scan_id: 0,
1111 }));
1112 entries_by_path_edits.push(Edit::Insert(entry));
1113 }
1114
1115 self.entries_by_path.edit(entries_by_path_edits, &());
1116 self.entries_by_id.edit(entries_by_id_edits, &());
1117 self.scan_id = update.scan_id as usize;
1118 self.is_complete = update.is_last_update;
1119
1120 Ok(())
1121 }
1122
1123 pub fn file_count(&self) -> usize {
1124 self.entries_by_path.summary().file_count
1125 }
1126
1127 pub fn visible_file_count(&self) -> usize {
1128 self.entries_by_path.summary().visible_file_count
1129 }
1130
1131 fn traverse_from_offset(
1132 &self,
1133 include_dirs: bool,
1134 include_ignored: bool,
1135 start_offset: usize,
1136 ) -> Traversal {
1137 let mut cursor = self.entries_by_path.cursor();
1138 cursor.seek(
1139 &TraversalTarget::Count {
1140 count: start_offset,
1141 include_dirs,
1142 include_ignored,
1143 },
1144 Bias::Right,
1145 &(),
1146 );
1147 Traversal {
1148 cursor,
1149 include_dirs,
1150 include_ignored,
1151 }
1152 }
1153
1154 fn traverse_from_path(
1155 &self,
1156 include_dirs: bool,
1157 include_ignored: bool,
1158 path: &Path,
1159 ) -> Traversal {
1160 let mut cursor = self.entries_by_path.cursor();
1161 cursor.seek(&TraversalTarget::Path(path), Bias::Left, &());
1162 Traversal {
1163 cursor,
1164 include_dirs,
1165 include_ignored,
1166 }
1167 }
1168
1169 pub fn files(&self, include_ignored: bool, start: usize) -> Traversal {
1170 self.traverse_from_offset(false, include_ignored, start)
1171 }
1172
1173 pub fn entries(&self, include_ignored: bool) -> Traversal {
1174 self.traverse_from_offset(true, include_ignored, 0)
1175 }
1176
1177 pub fn paths(&self) -> impl Iterator<Item = &Arc<Path>> {
1178 let empty_path = Path::new("");
1179 self.entries_by_path
1180 .cursor::<()>()
1181 .filter(move |entry| entry.path.as_ref() != empty_path)
1182 .map(|entry| &entry.path)
1183 }
1184
1185 fn child_entries<'a>(&'a self, parent_path: &'a Path) -> ChildEntriesIter<'a> {
1186 let mut cursor = self.entries_by_path.cursor();
1187 cursor.seek(&TraversalTarget::Path(parent_path), Bias::Right, &());
1188 let traversal = Traversal {
1189 cursor,
1190 include_dirs: true,
1191 include_ignored: true,
1192 };
1193 ChildEntriesIter {
1194 traversal,
1195 parent_path,
1196 }
1197 }
1198
1199 pub fn root_entry(&self) -> Option<&Entry> {
1200 self.entry_for_path("")
1201 }
1202
1203 pub fn root_name(&self) -> &str {
1204 &self.root_name
1205 }
1206
1207 pub fn scan_id(&self) -> usize {
1208 self.scan_id
1209 }
1210
1211 pub fn entry_for_path(&self, path: impl AsRef<Path>) -> Option<&Entry> {
1212 let path = path.as_ref();
1213 self.traverse_from_path(true, true, path)
1214 .entry()
1215 .and_then(|entry| {
1216 if entry.path.as_ref() == path {
1217 Some(entry)
1218 } else {
1219 None
1220 }
1221 })
1222 }
1223
1224 pub fn entry_for_id(&self, id: ProjectEntryId) -> Option<&Entry> {
1225 let entry = self.entries_by_id.get(&id, &())?;
1226 self.entry_for_path(&entry.path)
1227 }
1228
1229 pub fn inode_for_path(&self, path: impl AsRef<Path>) -> Option<u64> {
1230 self.entry_for_path(path.as_ref()).map(|e| e.inode)
1231 }
1232}
1233
1234impl LocalSnapshot {
1235 pub fn abs_path(&self) -> &Arc<Path> {
1236 &self.abs_path
1237 }
1238
1239 #[cfg(test)]
1240 pub(crate) fn build_initial_update(&self, project_id: u64) -> proto::UpdateWorktree {
1241 let root_name = self.root_name.clone();
1242 proto::UpdateWorktree {
1243 project_id,
1244 worktree_id: self.id().to_proto(),
1245 root_name,
1246 updated_entries: self.entries_by_path.iter().map(Into::into).collect(),
1247 removed_entries: Default::default(),
1248 scan_id: self.scan_id as u64,
1249 is_last_update: true,
1250 }
1251 }
1252
1253 pub(crate) fn build_update(
1254 &self,
1255 other: &Self,
1256 project_id: u64,
1257 worktree_id: u64,
1258 include_ignored: bool,
1259 ) -> proto::UpdateWorktree {
1260 let mut updated_entries = Vec::new();
1261 let mut removed_entries = Vec::new();
1262 let mut self_entries = self
1263 .entries_by_id
1264 .cursor::<()>()
1265 .filter(|e| include_ignored || !e.is_ignored)
1266 .peekable();
1267 let mut other_entries = other
1268 .entries_by_id
1269 .cursor::<()>()
1270 .filter(|e| include_ignored || !e.is_ignored)
1271 .peekable();
1272 loop {
1273 match (self_entries.peek(), other_entries.peek()) {
1274 (Some(self_entry), Some(other_entry)) => {
1275 match Ord::cmp(&self_entry.id, &other_entry.id) {
1276 Ordering::Less => {
1277 let entry = self.entry_for_id(self_entry.id).unwrap().into();
1278 updated_entries.push(entry);
1279 self_entries.next();
1280 }
1281 Ordering::Equal => {
1282 if self_entry.scan_id != other_entry.scan_id {
1283 let entry = self.entry_for_id(self_entry.id).unwrap().into();
1284 updated_entries.push(entry);
1285 }
1286
1287 self_entries.next();
1288 other_entries.next();
1289 }
1290 Ordering::Greater => {
1291 removed_entries.push(other_entry.id.to_proto());
1292 other_entries.next();
1293 }
1294 }
1295 }
1296 (Some(self_entry), None) => {
1297 let entry = self.entry_for_id(self_entry.id).unwrap().into();
1298 updated_entries.push(entry);
1299 self_entries.next();
1300 }
1301 (None, Some(other_entry)) => {
1302 removed_entries.push(other_entry.id.to_proto());
1303 other_entries.next();
1304 }
1305 (None, None) => break,
1306 }
1307 }
1308
1309 proto::UpdateWorktree {
1310 project_id,
1311 worktree_id,
1312 root_name: self.root_name().to_string(),
1313 updated_entries,
1314 removed_entries,
1315 scan_id: self.scan_id as u64,
1316 is_last_update: true,
1317 }
1318 }
1319
1320 fn insert_entry(&mut self, mut entry: Entry, fs: &dyn Fs) -> Entry {
1321 if !entry.is_dir() && entry.path.file_name() == Some(&GITIGNORE) {
1322 let abs_path = self.abs_path.join(&entry.path);
1323 match build_gitignore(&abs_path, fs) {
1324 Ok(ignore) => {
1325 let ignore_dir_path = entry.path.parent().unwrap();
1326 self.ignores
1327 .insert(ignore_dir_path.into(), (Arc::new(ignore), self.scan_id));
1328 }
1329 Err(error) => {
1330 log::error!(
1331 "error loading .gitignore file {:?} - {:?}",
1332 &entry.path,
1333 error
1334 );
1335 }
1336 }
1337 }
1338
1339 self.reuse_entry_id(&mut entry);
1340 self.entries_by_path.insert_or_replace(entry.clone(), &());
1341 let scan_id = self.scan_id;
1342 self.entries_by_id.insert_or_replace(
1343 PathEntry {
1344 id: entry.id,
1345 path: entry.path.clone(),
1346 is_ignored: entry.is_ignored,
1347 scan_id,
1348 },
1349 &(),
1350 );
1351 entry
1352 }
1353
1354 fn populate_dir(
1355 &mut self,
1356 parent_path: Arc<Path>,
1357 entries: impl IntoIterator<Item = Entry>,
1358 ignore: Option<Arc<Gitignore>>,
1359 ) {
1360 let mut parent_entry = if let Some(parent_entry) =
1361 self.entries_by_path.get(&PathKey(parent_path.clone()), &())
1362 {
1363 parent_entry.clone()
1364 } else {
1365 log::warn!(
1366 "populating a directory {:?} that has been removed",
1367 parent_path
1368 );
1369 return;
1370 };
1371
1372 if let Some(ignore) = ignore {
1373 self.ignores.insert(parent_path, (ignore, self.scan_id));
1374 }
1375 if matches!(parent_entry.kind, EntryKind::PendingDir) {
1376 parent_entry.kind = EntryKind::Dir;
1377 } else {
1378 unreachable!();
1379 }
1380
1381 let mut entries_by_path_edits = vec![Edit::Insert(parent_entry)];
1382 let mut entries_by_id_edits = Vec::new();
1383
1384 for mut entry in entries {
1385 self.reuse_entry_id(&mut entry);
1386 entries_by_id_edits.push(Edit::Insert(PathEntry {
1387 id: entry.id,
1388 path: entry.path.clone(),
1389 is_ignored: entry.is_ignored,
1390 scan_id: self.scan_id,
1391 }));
1392 entries_by_path_edits.push(Edit::Insert(entry));
1393 }
1394
1395 self.entries_by_path.edit(entries_by_path_edits, &());
1396 self.entries_by_id.edit(entries_by_id_edits, &());
1397 }
1398
1399 fn reuse_entry_id(&mut self, entry: &mut Entry) {
1400 if let Some(removed_entry_id) = self.removed_entry_ids.remove(&entry.inode) {
1401 entry.id = removed_entry_id;
1402 } else if let Some(existing_entry) = self.entry_for_path(&entry.path) {
1403 entry.id = existing_entry.id;
1404 }
1405 }
1406
1407 fn remove_path(&mut self, path: &Path) {
1408 let mut new_entries;
1409 let removed_entries;
1410 {
1411 let mut cursor = self.entries_by_path.cursor::<TraversalProgress>();
1412 new_entries = cursor.slice(&TraversalTarget::Path(path), Bias::Left, &());
1413 removed_entries = cursor.slice(&TraversalTarget::PathSuccessor(path), Bias::Left, &());
1414 new_entries.push_tree(cursor.suffix(&()), &());
1415 }
1416 self.entries_by_path = new_entries;
1417
1418 let mut entries_by_id_edits = Vec::new();
1419 for entry in removed_entries.cursor::<()>() {
1420 let removed_entry_id = self
1421 .removed_entry_ids
1422 .entry(entry.inode)
1423 .or_insert(entry.id);
1424 *removed_entry_id = cmp::max(*removed_entry_id, entry.id);
1425 entries_by_id_edits.push(Edit::Remove(entry.id));
1426 }
1427 self.entries_by_id.edit(entries_by_id_edits, &());
1428
1429 if path.file_name() == Some(&GITIGNORE) {
1430 if let Some((_, scan_id)) = self.ignores.get_mut(path.parent().unwrap()) {
1431 *scan_id = self.snapshot.scan_id;
1432 }
1433 }
1434 }
1435
1436 fn ignore_stack_for_path(&self, path: &Path, is_dir: bool) -> Arc<IgnoreStack> {
1437 let mut new_ignores = Vec::new();
1438 for ancestor in path.ancestors().skip(1) {
1439 if let Some((ignore, _)) = self.ignores.get(ancestor) {
1440 new_ignores.push((ancestor, Some(ignore.clone())));
1441 } else {
1442 new_ignores.push((ancestor, None));
1443 }
1444 }
1445
1446 let mut ignore_stack = IgnoreStack::none();
1447 for (parent_path, ignore) in new_ignores.into_iter().rev() {
1448 if ignore_stack.is_path_ignored(&parent_path, true) {
1449 ignore_stack = IgnoreStack::all();
1450 break;
1451 } else if let Some(ignore) = ignore {
1452 ignore_stack = ignore_stack.append(Arc::from(parent_path), ignore);
1453 }
1454 }
1455
1456 if ignore_stack.is_path_ignored(path, is_dir) {
1457 ignore_stack = IgnoreStack::all();
1458 }
1459
1460 ignore_stack
1461 }
1462}
1463
1464fn build_gitignore(abs_path: &Path, fs: &dyn Fs) -> Result<Gitignore> {
1465 let contents = smol::block_on(fs.load(&abs_path))?;
1466 let parent = abs_path.parent().unwrap_or(Path::new("/"));
1467 let mut builder = GitignoreBuilder::new(parent);
1468 for line in contents.lines() {
1469 builder.add_line(Some(abs_path.into()), line)?;
1470 }
1471 Ok(builder.build()?)
1472}
1473
1474impl WorktreeId {
1475 pub fn from_usize(handle_id: usize) -> Self {
1476 Self(handle_id)
1477 }
1478
1479 pub(crate) fn from_proto(id: u64) -> Self {
1480 Self(id as usize)
1481 }
1482
1483 pub fn to_proto(&self) -> u64 {
1484 self.0 as u64
1485 }
1486
1487 pub fn to_usize(&self) -> usize {
1488 self.0
1489 }
1490}
1491
1492impl fmt::Display for WorktreeId {
1493 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1494 self.0.fmt(f)
1495 }
1496}
1497
1498impl Deref for Worktree {
1499 type Target = Snapshot;
1500
1501 fn deref(&self) -> &Self::Target {
1502 match self {
1503 Worktree::Local(worktree) => &worktree.snapshot,
1504 Worktree::Remote(worktree) => &worktree.snapshot,
1505 }
1506 }
1507}
1508
1509impl Deref for LocalWorktree {
1510 type Target = LocalSnapshot;
1511
1512 fn deref(&self) -> &Self::Target {
1513 &self.snapshot
1514 }
1515}
1516
1517impl Deref for RemoteWorktree {
1518 type Target = Snapshot;
1519
1520 fn deref(&self) -> &Self::Target {
1521 &self.snapshot
1522 }
1523}
1524
1525impl fmt::Debug for LocalWorktree {
1526 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1527 self.snapshot.fmt(f)
1528 }
1529}
1530
1531impl fmt::Debug for Snapshot {
1532 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1533 struct EntriesById<'a>(&'a SumTree<PathEntry>);
1534 struct EntriesByPath<'a>(&'a SumTree<Entry>);
1535
1536 impl<'a> fmt::Debug for EntriesByPath<'a> {
1537 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1538 f.debug_map()
1539 .entries(self.0.iter().map(|entry| (&entry.path, entry.id)))
1540 .finish()
1541 }
1542 }
1543
1544 impl<'a> fmt::Debug for EntriesById<'a> {
1545 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1546 f.debug_list().entries(self.0.iter()).finish()
1547 }
1548 }
1549
1550 f.debug_struct("Snapshot")
1551 .field("id", &self.id)
1552 .field("root_name", &self.root_name)
1553 .field("entries_by_path", &EntriesByPath(&self.entries_by_path))
1554 .field("entries_by_id", &EntriesById(&self.entries_by_id))
1555 .finish()
1556 }
1557}
1558
1559#[derive(Clone, PartialEq)]
1560pub struct File {
1561 pub worktree: ModelHandle<Worktree>,
1562 pub path: Arc<Path>,
1563 pub mtime: SystemTime,
1564 pub(crate) entry_id: Option<ProjectEntryId>,
1565 pub(crate) is_local: bool,
1566}
1567
1568impl language::File for File {
1569 fn as_local(&self) -> Option<&dyn language::LocalFile> {
1570 if self.is_local {
1571 Some(self)
1572 } else {
1573 None
1574 }
1575 }
1576
1577 fn mtime(&self) -> SystemTime {
1578 self.mtime
1579 }
1580
1581 fn path(&self) -> &Arc<Path> {
1582 &self.path
1583 }
1584
1585 fn full_path(&self, cx: &AppContext) -> PathBuf {
1586 let mut full_path = PathBuf::new();
1587 full_path.push(self.worktree.read(cx).root_name());
1588 if self.path.components().next().is_some() {
1589 full_path.push(&self.path);
1590 }
1591 full_path
1592 }
1593
1594 /// Returns the last component of this handle's absolute path. If this handle refers to the root
1595 /// of its worktree, then this method will return the name of the worktree itself.
1596 fn file_name(&self, cx: &AppContext) -> OsString {
1597 self.path
1598 .file_name()
1599 .map(|name| name.into())
1600 .unwrap_or_else(|| OsString::from(&self.worktree.read(cx).root_name))
1601 }
1602
1603 fn is_deleted(&self) -> bool {
1604 self.entry_id.is_none()
1605 }
1606
1607 fn save(
1608 &self,
1609 buffer_id: u64,
1610 text: Rope,
1611 version: clock::Global,
1612 cx: &mut MutableAppContext,
1613 ) -> Task<Result<(clock::Global, String, SystemTime)>> {
1614 self.worktree.update(cx, |worktree, cx| match worktree {
1615 Worktree::Local(worktree) => {
1616 let rpc = worktree.client.clone();
1617 let project_id = worktree.share.as_ref().map(|share| share.project_id);
1618 let fingerprint = text.fingerprint();
1619 let save = worktree.write_file(self.path.clone(), text, cx);
1620 cx.background().spawn(async move {
1621 let entry = save.await?;
1622 if let Some(project_id) = project_id {
1623 rpc.send(proto::BufferSaved {
1624 project_id,
1625 buffer_id,
1626 version: serialize_version(&version),
1627 mtime: Some(entry.mtime.into()),
1628 fingerprint: fingerprint.clone(),
1629 })?;
1630 }
1631 Ok((version, fingerprint, entry.mtime))
1632 })
1633 }
1634 Worktree::Remote(worktree) => {
1635 let rpc = worktree.client.clone();
1636 let project_id = worktree.project_id;
1637 cx.foreground().spawn(async move {
1638 let response = rpc
1639 .request(proto::SaveBuffer {
1640 project_id,
1641 buffer_id,
1642 version: serialize_version(&version),
1643 })
1644 .await?;
1645 let version = deserialize_version(response.version);
1646 let mtime = response
1647 .mtime
1648 .ok_or_else(|| anyhow!("missing mtime"))?
1649 .into();
1650 Ok((version, response.fingerprint, mtime))
1651 })
1652 }
1653 })
1654 }
1655
1656 fn as_any(&self) -> &dyn Any {
1657 self
1658 }
1659
1660 fn to_proto(&self) -> rpc::proto::File {
1661 rpc::proto::File {
1662 worktree_id: self.worktree.id() as u64,
1663 entry_id: self.entry_id.map(|entry_id| entry_id.to_proto()),
1664 path: self.path.to_string_lossy().into(),
1665 mtime: Some(self.mtime.into()),
1666 }
1667 }
1668}
1669
1670impl language::LocalFile for File {
1671 fn abs_path(&self, cx: &AppContext) -> PathBuf {
1672 self.worktree
1673 .read(cx)
1674 .as_local()
1675 .unwrap()
1676 .abs_path
1677 .join(&self.path)
1678 }
1679
1680 fn load(&self, cx: &AppContext) -> Task<Result<String>> {
1681 let worktree = self.worktree.read(cx).as_local().unwrap();
1682 let abs_path = worktree.absolutize(&self.path);
1683 let fs = worktree.fs.clone();
1684 cx.background()
1685 .spawn(async move { fs.load(&abs_path).await })
1686 }
1687
1688 fn buffer_reloaded(
1689 &self,
1690 buffer_id: u64,
1691 version: &clock::Global,
1692 fingerprint: String,
1693 mtime: SystemTime,
1694 cx: &mut MutableAppContext,
1695 ) {
1696 let worktree = self.worktree.read(cx).as_local().unwrap();
1697 if let Some(project_id) = worktree.share.as_ref().map(|share| share.project_id) {
1698 worktree
1699 .client
1700 .send(proto::BufferReloaded {
1701 project_id,
1702 buffer_id,
1703 version: serialize_version(&version),
1704 mtime: Some(mtime.into()),
1705 fingerprint,
1706 })
1707 .log_err();
1708 }
1709 }
1710}
1711
1712impl File {
1713 pub fn from_proto(
1714 proto: rpc::proto::File,
1715 worktree: ModelHandle<Worktree>,
1716 cx: &AppContext,
1717 ) -> Result<Self> {
1718 let worktree_id = worktree
1719 .read(cx)
1720 .as_remote()
1721 .ok_or_else(|| anyhow!("not remote"))?
1722 .id();
1723
1724 if worktree_id.to_proto() != proto.worktree_id {
1725 return Err(anyhow!("worktree id does not match file"));
1726 }
1727
1728 Ok(Self {
1729 worktree,
1730 path: Path::new(&proto.path).into(),
1731 mtime: proto.mtime.ok_or_else(|| anyhow!("no timestamp"))?.into(),
1732 entry_id: proto.entry_id.map(ProjectEntryId::from_proto),
1733 is_local: false,
1734 })
1735 }
1736
1737 pub fn from_dyn(file: Option<&dyn language::File>) -> Option<&Self> {
1738 file.and_then(|f| f.as_any().downcast_ref())
1739 }
1740
1741 pub fn worktree_id(&self, cx: &AppContext) -> WorktreeId {
1742 self.worktree.read(cx).id()
1743 }
1744
1745 pub fn project_entry_id(&self, _: &AppContext) -> Option<ProjectEntryId> {
1746 self.entry_id
1747 }
1748}
1749
1750#[derive(Clone, Debug, PartialEq, Eq)]
1751pub struct Entry {
1752 pub id: ProjectEntryId,
1753 pub kind: EntryKind,
1754 pub path: Arc<Path>,
1755 pub inode: u64,
1756 pub mtime: SystemTime,
1757 pub is_symlink: bool,
1758 pub is_ignored: bool,
1759}
1760
1761#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1762pub enum EntryKind {
1763 PendingDir,
1764 Dir,
1765 File(CharBag),
1766}
1767
1768impl Entry {
1769 fn new(
1770 path: Arc<Path>,
1771 metadata: &fs::Metadata,
1772 next_entry_id: &AtomicUsize,
1773 root_char_bag: CharBag,
1774 ) -> Self {
1775 Self {
1776 id: ProjectEntryId::new(next_entry_id),
1777 kind: if metadata.is_dir {
1778 EntryKind::PendingDir
1779 } else {
1780 EntryKind::File(char_bag_for_path(root_char_bag, &path))
1781 },
1782 path,
1783 inode: metadata.inode,
1784 mtime: metadata.mtime,
1785 is_symlink: metadata.is_symlink,
1786 is_ignored: false,
1787 }
1788 }
1789
1790 pub fn is_dir(&self) -> bool {
1791 matches!(self.kind, EntryKind::Dir | EntryKind::PendingDir)
1792 }
1793
1794 pub fn is_file(&self) -> bool {
1795 matches!(self.kind, EntryKind::File(_))
1796 }
1797}
1798
1799impl sum_tree::Item for Entry {
1800 type Summary = EntrySummary;
1801
1802 fn summary(&self) -> Self::Summary {
1803 let visible_count = if self.is_ignored { 0 } else { 1 };
1804 let file_count;
1805 let visible_file_count;
1806 if self.is_file() {
1807 file_count = 1;
1808 visible_file_count = visible_count;
1809 } else {
1810 file_count = 0;
1811 visible_file_count = 0;
1812 }
1813
1814 EntrySummary {
1815 max_path: self.path.clone(),
1816 count: 1,
1817 visible_count,
1818 file_count,
1819 visible_file_count,
1820 }
1821 }
1822}
1823
1824impl sum_tree::KeyedItem for Entry {
1825 type Key = PathKey;
1826
1827 fn key(&self) -> Self::Key {
1828 PathKey(self.path.clone())
1829 }
1830}
1831
1832#[derive(Clone, Debug)]
1833pub struct EntrySummary {
1834 max_path: Arc<Path>,
1835 count: usize,
1836 visible_count: usize,
1837 file_count: usize,
1838 visible_file_count: usize,
1839}
1840
1841impl Default for EntrySummary {
1842 fn default() -> Self {
1843 Self {
1844 max_path: Arc::from(Path::new("")),
1845 count: 0,
1846 visible_count: 0,
1847 file_count: 0,
1848 visible_file_count: 0,
1849 }
1850 }
1851}
1852
1853impl sum_tree::Summary for EntrySummary {
1854 type Context = ();
1855
1856 fn add_summary(&mut self, rhs: &Self, _: &()) {
1857 self.max_path = rhs.max_path.clone();
1858 self.count += rhs.count;
1859 self.visible_count += rhs.visible_count;
1860 self.file_count += rhs.file_count;
1861 self.visible_file_count += rhs.visible_file_count;
1862 }
1863}
1864
1865#[derive(Clone, Debug)]
1866struct PathEntry {
1867 id: ProjectEntryId,
1868 path: Arc<Path>,
1869 is_ignored: bool,
1870 scan_id: usize,
1871}
1872
1873impl sum_tree::Item for PathEntry {
1874 type Summary = PathEntrySummary;
1875
1876 fn summary(&self) -> Self::Summary {
1877 PathEntrySummary { max_id: self.id }
1878 }
1879}
1880
1881impl sum_tree::KeyedItem for PathEntry {
1882 type Key = ProjectEntryId;
1883
1884 fn key(&self) -> Self::Key {
1885 self.id
1886 }
1887}
1888
1889#[derive(Clone, Debug, Default)]
1890struct PathEntrySummary {
1891 max_id: ProjectEntryId,
1892}
1893
1894impl sum_tree::Summary for PathEntrySummary {
1895 type Context = ();
1896
1897 fn add_summary(&mut self, summary: &Self, _: &Self::Context) {
1898 self.max_id = summary.max_id;
1899 }
1900}
1901
1902impl<'a> sum_tree::Dimension<'a, PathEntrySummary> for ProjectEntryId {
1903 fn add_summary(&mut self, summary: &'a PathEntrySummary, _: &()) {
1904 *self = summary.max_id;
1905 }
1906}
1907
1908#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
1909pub struct PathKey(Arc<Path>);
1910
1911impl Default for PathKey {
1912 fn default() -> Self {
1913 Self(Path::new("").into())
1914 }
1915}
1916
1917impl<'a> sum_tree::Dimension<'a, EntrySummary> for PathKey {
1918 fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
1919 self.0 = summary.max_path.clone();
1920 }
1921}
1922
1923struct BackgroundScanner {
1924 fs: Arc<dyn Fs>,
1925 snapshot: Arc<Mutex<LocalSnapshot>>,
1926 notify: UnboundedSender<ScanState>,
1927 executor: Arc<executor::Background>,
1928}
1929
1930impl BackgroundScanner {
1931 fn new(
1932 snapshot: Arc<Mutex<LocalSnapshot>>,
1933 notify: UnboundedSender<ScanState>,
1934 fs: Arc<dyn Fs>,
1935 executor: Arc<executor::Background>,
1936 ) -> Self {
1937 Self {
1938 fs,
1939 snapshot,
1940 notify,
1941 executor,
1942 }
1943 }
1944
1945 fn abs_path(&self) -> Arc<Path> {
1946 self.snapshot.lock().abs_path.clone()
1947 }
1948
1949 fn snapshot(&self) -> LocalSnapshot {
1950 self.snapshot.lock().clone()
1951 }
1952
1953 async fn run(mut self, events_rx: impl Stream<Item = Vec<fsevent::Event>>) {
1954 if self.notify.unbounded_send(ScanState::Initializing).is_err() {
1955 return;
1956 }
1957
1958 if let Err(err) = self.scan_dirs().await {
1959 if self
1960 .notify
1961 .unbounded_send(ScanState::Err(Arc::new(err)))
1962 .is_err()
1963 {
1964 return;
1965 }
1966 }
1967
1968 if self.notify.unbounded_send(ScanState::Idle).is_err() {
1969 return;
1970 }
1971
1972 futures::pin_mut!(events_rx);
1973
1974 while let Some(mut events) = events_rx.next().await {
1975 while let Poll::Ready(Some(additional_events)) = futures::poll!(events_rx.next()) {
1976 events.extend(additional_events);
1977 }
1978
1979 if self.notify.unbounded_send(ScanState::Updating).is_err() {
1980 break;
1981 }
1982
1983 if !self.process_events(events).await {
1984 break;
1985 }
1986
1987 if self.notify.unbounded_send(ScanState::Idle).is_err() {
1988 break;
1989 }
1990 }
1991 }
1992
1993 async fn scan_dirs(&mut self) -> Result<()> {
1994 let root_char_bag;
1995 let next_entry_id;
1996 let is_dir;
1997 {
1998 let snapshot = self.snapshot.lock();
1999 root_char_bag = snapshot.root_char_bag;
2000 next_entry_id = snapshot.next_entry_id.clone();
2001 is_dir = snapshot.root_entry().map_or(false, |e| e.is_dir())
2002 };
2003
2004 if is_dir {
2005 let path: Arc<Path> = Arc::from(Path::new(""));
2006 let abs_path = self.abs_path();
2007 let (tx, rx) = channel::unbounded();
2008 self.executor
2009 .block(tx.send(ScanJob {
2010 abs_path: abs_path.to_path_buf(),
2011 path,
2012 ignore_stack: IgnoreStack::none(),
2013 scan_queue: tx.clone(),
2014 }))
2015 .unwrap();
2016 drop(tx);
2017
2018 self.executor
2019 .scoped(|scope| {
2020 for _ in 0..self.executor.num_cpus() {
2021 scope.spawn(async {
2022 while let Ok(job) = rx.recv().await {
2023 if let Err(err) = self
2024 .scan_dir(root_char_bag, next_entry_id.clone(), &job)
2025 .await
2026 {
2027 log::error!("error scanning {:?}: {}", job.abs_path, err);
2028 }
2029 }
2030 });
2031 }
2032 })
2033 .await;
2034 }
2035
2036 Ok(())
2037 }
2038
2039 async fn scan_dir(
2040 &self,
2041 root_char_bag: CharBag,
2042 next_entry_id: Arc<AtomicUsize>,
2043 job: &ScanJob,
2044 ) -> Result<()> {
2045 let mut new_entries: Vec<Entry> = Vec::new();
2046 let mut new_jobs: Vec<ScanJob> = Vec::new();
2047 let mut ignore_stack = job.ignore_stack.clone();
2048 let mut new_ignore = None;
2049
2050 let mut child_paths = self.fs.read_dir(&job.abs_path).await?;
2051 while let Some(child_abs_path) = child_paths.next().await {
2052 let child_abs_path = match child_abs_path {
2053 Ok(child_abs_path) => child_abs_path,
2054 Err(error) => {
2055 log::error!("error processing entry {:?}", error);
2056 continue;
2057 }
2058 };
2059 let child_name = child_abs_path.file_name().unwrap();
2060 let child_path: Arc<Path> = job.path.join(child_name).into();
2061 let child_metadata = match self.fs.metadata(&child_abs_path).await {
2062 Ok(Some(metadata)) => metadata,
2063 Ok(None) => continue,
2064 Err(err) => {
2065 log::error!("error processing {:?}: {:?}", child_abs_path, err);
2066 continue;
2067 }
2068 };
2069
2070 // If we find a .gitignore, add it to the stack of ignores used to determine which paths are ignored
2071 if child_name == *GITIGNORE {
2072 match build_gitignore(&child_abs_path, self.fs.as_ref()) {
2073 Ok(ignore) => {
2074 let ignore = Arc::new(ignore);
2075 ignore_stack = ignore_stack.append(job.path.clone(), ignore.clone());
2076 new_ignore = Some(ignore);
2077 }
2078 Err(error) => {
2079 log::error!(
2080 "error loading .gitignore file {:?} - {:?}",
2081 child_name,
2082 error
2083 );
2084 }
2085 }
2086
2087 // Update ignore status of any child entries we've already processed to reflect the
2088 // ignore file in the current directory. Because `.gitignore` starts with a `.`,
2089 // there should rarely be too numerous. Update the ignore stack associated with any
2090 // new jobs as well.
2091 let mut new_jobs = new_jobs.iter_mut();
2092 for entry in &mut new_entries {
2093 entry.is_ignored = ignore_stack.is_path_ignored(&entry.path, entry.is_dir());
2094 if entry.is_dir() {
2095 new_jobs.next().unwrap().ignore_stack = if entry.is_ignored {
2096 IgnoreStack::all()
2097 } else {
2098 ignore_stack.clone()
2099 };
2100 }
2101 }
2102 }
2103
2104 let mut child_entry = Entry::new(
2105 child_path.clone(),
2106 &child_metadata,
2107 &next_entry_id,
2108 root_char_bag,
2109 );
2110
2111 if child_metadata.is_dir {
2112 let is_ignored = ignore_stack.is_path_ignored(&child_path, true);
2113 child_entry.is_ignored = is_ignored;
2114 new_entries.push(child_entry);
2115 new_jobs.push(ScanJob {
2116 abs_path: child_abs_path,
2117 path: child_path,
2118 ignore_stack: if is_ignored {
2119 IgnoreStack::all()
2120 } else {
2121 ignore_stack.clone()
2122 },
2123 scan_queue: job.scan_queue.clone(),
2124 });
2125 } else {
2126 child_entry.is_ignored = ignore_stack.is_path_ignored(&child_path, false);
2127 new_entries.push(child_entry);
2128 };
2129 }
2130
2131 self.snapshot
2132 .lock()
2133 .populate_dir(job.path.clone(), new_entries, new_ignore);
2134 for new_job in new_jobs {
2135 job.scan_queue.send(new_job).await.unwrap();
2136 }
2137
2138 Ok(())
2139 }
2140
2141 async fn process_events(&mut self, mut events: Vec<fsevent::Event>) -> bool {
2142 events.sort_unstable_by(|a, b| a.path.cmp(&b.path));
2143 events.dedup_by(|a, b| a.path.starts_with(&b.path));
2144
2145 let root_char_bag;
2146 let root_abs_path;
2147 let next_entry_id;
2148 {
2149 let snapshot = self.snapshot.lock();
2150 root_char_bag = snapshot.root_char_bag;
2151 root_abs_path = snapshot.abs_path.clone();
2152 next_entry_id = snapshot.next_entry_id.clone();
2153 }
2154
2155 let root_abs_path = if let Ok(abs_path) = self.fs.canonicalize(&root_abs_path).await {
2156 abs_path
2157 } else {
2158 return false;
2159 };
2160 let metadata = futures::future::join_all(
2161 events
2162 .iter()
2163 .map(|event| self.fs.metadata(&event.path))
2164 .collect::<Vec<_>>(),
2165 )
2166 .await;
2167
2168 // Hold the snapshot lock while clearing and re-inserting the root entries
2169 // for each event. This way, the snapshot is not observable to the foreground
2170 // thread while this operation is in-progress.
2171 let (scan_queue_tx, scan_queue_rx) = channel::unbounded();
2172 {
2173 let mut snapshot = self.snapshot.lock();
2174 snapshot.scan_id += 1;
2175 for event in &events {
2176 if let Ok(path) = event.path.strip_prefix(&root_abs_path) {
2177 snapshot.remove_path(&path);
2178 }
2179 }
2180
2181 for (event, metadata) in events.into_iter().zip(metadata.into_iter()) {
2182 let path: Arc<Path> = match event.path.strip_prefix(&root_abs_path) {
2183 Ok(path) => Arc::from(path.to_path_buf()),
2184 Err(_) => {
2185 log::error!(
2186 "unexpected event {:?} for root path {:?}",
2187 event.path,
2188 root_abs_path
2189 );
2190 continue;
2191 }
2192 };
2193
2194 match metadata {
2195 Ok(Some(metadata)) => {
2196 let ignore_stack = snapshot.ignore_stack_for_path(&path, metadata.is_dir);
2197 let mut fs_entry = Entry::new(
2198 path.clone(),
2199 &metadata,
2200 snapshot.next_entry_id.as_ref(),
2201 snapshot.root_char_bag,
2202 );
2203 fs_entry.is_ignored = ignore_stack.is_all();
2204 snapshot.insert_entry(fs_entry, self.fs.as_ref());
2205 if metadata.is_dir {
2206 self.executor
2207 .block(scan_queue_tx.send(ScanJob {
2208 abs_path: event.path,
2209 path,
2210 ignore_stack,
2211 scan_queue: scan_queue_tx.clone(),
2212 }))
2213 .unwrap();
2214 }
2215 }
2216 Ok(None) => {}
2217 Err(err) => {
2218 // TODO - create a special 'error' entry in the entries tree to mark this
2219 log::error!("error reading file on event {:?}", err);
2220 }
2221 }
2222 }
2223 drop(scan_queue_tx);
2224 }
2225
2226 // Scan any directories that were created as part of this event batch.
2227 self.executor
2228 .scoped(|scope| {
2229 for _ in 0..self.executor.num_cpus() {
2230 scope.spawn(async {
2231 while let Ok(job) = scan_queue_rx.recv().await {
2232 if let Err(err) = self
2233 .scan_dir(root_char_bag, next_entry_id.clone(), &job)
2234 .await
2235 {
2236 log::error!("error scanning {:?}: {}", job.abs_path, err);
2237 }
2238 }
2239 });
2240 }
2241 })
2242 .await;
2243
2244 // Attempt to detect renames only over a single batch of file-system events.
2245 self.snapshot.lock().removed_entry_ids.clear();
2246
2247 self.update_ignore_statuses().await;
2248 true
2249 }
2250
2251 async fn update_ignore_statuses(&self) {
2252 let mut snapshot = self.snapshot();
2253
2254 let mut ignores_to_update = Vec::new();
2255 let mut ignores_to_delete = Vec::new();
2256 for (parent_path, (_, scan_id)) in &snapshot.ignores {
2257 if *scan_id == snapshot.scan_id && snapshot.entry_for_path(parent_path).is_some() {
2258 ignores_to_update.push(parent_path.clone());
2259 }
2260
2261 let ignore_path = parent_path.join(&*GITIGNORE);
2262 if snapshot.entry_for_path(ignore_path).is_none() {
2263 ignores_to_delete.push(parent_path.clone());
2264 }
2265 }
2266
2267 for parent_path in ignores_to_delete {
2268 snapshot.ignores.remove(&parent_path);
2269 self.snapshot.lock().ignores.remove(&parent_path);
2270 }
2271
2272 let (ignore_queue_tx, ignore_queue_rx) = channel::unbounded();
2273 ignores_to_update.sort_unstable();
2274 let mut ignores_to_update = ignores_to_update.into_iter().peekable();
2275 while let Some(parent_path) = ignores_to_update.next() {
2276 while ignores_to_update
2277 .peek()
2278 .map_or(false, |p| p.starts_with(&parent_path))
2279 {
2280 ignores_to_update.next().unwrap();
2281 }
2282
2283 let ignore_stack = snapshot.ignore_stack_for_path(&parent_path, true);
2284 ignore_queue_tx
2285 .send(UpdateIgnoreStatusJob {
2286 path: parent_path,
2287 ignore_stack,
2288 ignore_queue: ignore_queue_tx.clone(),
2289 })
2290 .await
2291 .unwrap();
2292 }
2293 drop(ignore_queue_tx);
2294
2295 self.executor
2296 .scoped(|scope| {
2297 for _ in 0..self.executor.num_cpus() {
2298 scope.spawn(async {
2299 while let Ok(job) = ignore_queue_rx.recv().await {
2300 self.update_ignore_status(job, &snapshot).await;
2301 }
2302 });
2303 }
2304 })
2305 .await;
2306 }
2307
2308 async fn update_ignore_status(&self, job: UpdateIgnoreStatusJob, snapshot: &LocalSnapshot) {
2309 let mut ignore_stack = job.ignore_stack;
2310 if let Some((ignore, _)) = snapshot.ignores.get(&job.path) {
2311 ignore_stack = ignore_stack.append(job.path.clone(), ignore.clone());
2312 }
2313
2314 let mut entries_by_id_edits = Vec::new();
2315 let mut entries_by_path_edits = Vec::new();
2316 for mut entry in snapshot.child_entries(&job.path).cloned() {
2317 let was_ignored = entry.is_ignored;
2318 entry.is_ignored = ignore_stack.is_path_ignored(&entry.path, entry.is_dir());
2319 if entry.is_dir() {
2320 let child_ignore_stack = if entry.is_ignored {
2321 IgnoreStack::all()
2322 } else {
2323 ignore_stack.clone()
2324 };
2325 job.ignore_queue
2326 .send(UpdateIgnoreStatusJob {
2327 path: entry.path.clone(),
2328 ignore_stack: child_ignore_stack,
2329 ignore_queue: job.ignore_queue.clone(),
2330 })
2331 .await
2332 .unwrap();
2333 }
2334
2335 if entry.is_ignored != was_ignored {
2336 let mut path_entry = snapshot.entries_by_id.get(&entry.id, &()).unwrap().clone();
2337 path_entry.scan_id = snapshot.scan_id;
2338 path_entry.is_ignored = entry.is_ignored;
2339 entries_by_id_edits.push(Edit::Insert(path_entry));
2340 entries_by_path_edits.push(Edit::Insert(entry));
2341 }
2342 }
2343
2344 let mut snapshot = self.snapshot.lock();
2345 snapshot.entries_by_path.edit(entries_by_path_edits, &());
2346 snapshot.entries_by_id.edit(entries_by_id_edits, &());
2347 }
2348}
2349
2350fn char_bag_for_path(root_char_bag: CharBag, path: &Path) -> CharBag {
2351 let mut result = root_char_bag;
2352 result.extend(
2353 path.to_string_lossy()
2354 .chars()
2355 .map(|c| c.to_ascii_lowercase()),
2356 );
2357 result
2358}
2359
2360struct ScanJob {
2361 abs_path: PathBuf,
2362 path: Arc<Path>,
2363 ignore_stack: Arc<IgnoreStack>,
2364 scan_queue: Sender<ScanJob>,
2365}
2366
2367struct UpdateIgnoreStatusJob {
2368 path: Arc<Path>,
2369 ignore_stack: Arc<IgnoreStack>,
2370 ignore_queue: Sender<UpdateIgnoreStatusJob>,
2371}
2372
2373pub trait WorktreeHandle {
2374 #[cfg(any(test, feature = "test-support"))]
2375 fn flush_fs_events<'a>(
2376 &self,
2377 cx: &'a gpui::TestAppContext,
2378 ) -> futures::future::LocalBoxFuture<'a, ()>;
2379}
2380
2381impl WorktreeHandle for ModelHandle<Worktree> {
2382 // When the worktree's FS event stream sometimes delivers "redundant" events for FS changes that
2383 // occurred before the worktree was constructed. These events can cause the worktree to perfrom
2384 // extra directory scans, and emit extra scan-state notifications.
2385 //
2386 // This function mutates the worktree's directory and waits for those mutations to be picked up,
2387 // to ensure that all redundant FS events have already been processed.
2388 #[cfg(any(test, feature = "test-support"))]
2389 fn flush_fs_events<'a>(
2390 &self,
2391 cx: &'a gpui::TestAppContext,
2392 ) -> futures::future::LocalBoxFuture<'a, ()> {
2393 use smol::future::FutureExt;
2394
2395 let filename = "fs-event-sentinel";
2396 let tree = self.clone();
2397 let (fs, root_path) = self.read_with(cx, |tree, _| {
2398 let tree = tree.as_local().unwrap();
2399 (tree.fs.clone(), tree.abs_path().clone())
2400 });
2401
2402 async move {
2403 fs.create_file(&root_path.join(filename), Default::default())
2404 .await
2405 .unwrap();
2406 tree.condition(&cx, |tree, _| tree.entry_for_path(filename).is_some())
2407 .await;
2408
2409 fs.remove_file(&root_path.join(filename), Default::default())
2410 .await
2411 .unwrap();
2412 tree.condition(&cx, |tree, _| tree.entry_for_path(filename).is_none())
2413 .await;
2414
2415 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2416 .await;
2417 }
2418 .boxed_local()
2419 }
2420}
2421
2422#[derive(Clone, Debug)]
2423struct TraversalProgress<'a> {
2424 max_path: &'a Path,
2425 count: usize,
2426 visible_count: usize,
2427 file_count: usize,
2428 visible_file_count: usize,
2429}
2430
2431impl<'a> TraversalProgress<'a> {
2432 fn count(&self, include_dirs: bool, include_ignored: bool) -> usize {
2433 match (include_ignored, include_dirs) {
2434 (true, true) => self.count,
2435 (true, false) => self.file_count,
2436 (false, true) => self.visible_count,
2437 (false, false) => self.visible_file_count,
2438 }
2439 }
2440}
2441
2442impl<'a> sum_tree::Dimension<'a, EntrySummary> for TraversalProgress<'a> {
2443 fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
2444 self.max_path = summary.max_path.as_ref();
2445 self.count += summary.count;
2446 self.visible_count += summary.visible_count;
2447 self.file_count += summary.file_count;
2448 self.visible_file_count += summary.visible_file_count;
2449 }
2450}
2451
2452impl<'a> Default for TraversalProgress<'a> {
2453 fn default() -> Self {
2454 Self {
2455 max_path: Path::new(""),
2456 count: 0,
2457 visible_count: 0,
2458 file_count: 0,
2459 visible_file_count: 0,
2460 }
2461 }
2462}
2463
2464pub struct Traversal<'a> {
2465 cursor: sum_tree::Cursor<'a, Entry, TraversalProgress<'a>>,
2466 include_ignored: bool,
2467 include_dirs: bool,
2468}
2469
2470impl<'a> Traversal<'a> {
2471 pub fn advance(&mut self) -> bool {
2472 self.advance_to_offset(self.offset() + 1)
2473 }
2474
2475 pub fn advance_to_offset(&mut self, offset: usize) -> bool {
2476 self.cursor.seek_forward(
2477 &TraversalTarget::Count {
2478 count: offset,
2479 include_dirs: self.include_dirs,
2480 include_ignored: self.include_ignored,
2481 },
2482 Bias::Right,
2483 &(),
2484 )
2485 }
2486
2487 pub fn advance_to_sibling(&mut self) -> bool {
2488 while let Some(entry) = self.cursor.item() {
2489 self.cursor.seek_forward(
2490 &TraversalTarget::PathSuccessor(&entry.path),
2491 Bias::Left,
2492 &(),
2493 );
2494 if let Some(entry) = self.cursor.item() {
2495 if (self.include_dirs || !entry.is_dir())
2496 && (self.include_ignored || !entry.is_ignored)
2497 {
2498 return true;
2499 }
2500 }
2501 }
2502 false
2503 }
2504
2505 pub fn entry(&self) -> Option<&'a Entry> {
2506 self.cursor.item()
2507 }
2508
2509 pub fn offset(&self) -> usize {
2510 self.cursor
2511 .start()
2512 .count(self.include_dirs, self.include_ignored)
2513 }
2514}
2515
2516impl<'a> Iterator for Traversal<'a> {
2517 type Item = &'a Entry;
2518
2519 fn next(&mut self) -> Option<Self::Item> {
2520 if let Some(item) = self.entry() {
2521 self.advance();
2522 Some(item)
2523 } else {
2524 None
2525 }
2526 }
2527}
2528
2529#[derive(Debug)]
2530enum TraversalTarget<'a> {
2531 Path(&'a Path),
2532 PathSuccessor(&'a Path),
2533 Count {
2534 count: usize,
2535 include_ignored: bool,
2536 include_dirs: bool,
2537 },
2538}
2539
2540impl<'a, 'b> SeekTarget<'a, EntrySummary, TraversalProgress<'a>> for TraversalTarget<'b> {
2541 fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: &()) -> Ordering {
2542 match self {
2543 TraversalTarget::Path(path) => path.cmp(&cursor_location.max_path),
2544 TraversalTarget::PathSuccessor(path) => {
2545 if !cursor_location.max_path.starts_with(path) {
2546 Ordering::Equal
2547 } else {
2548 Ordering::Greater
2549 }
2550 }
2551 TraversalTarget::Count {
2552 count,
2553 include_dirs,
2554 include_ignored,
2555 } => Ord::cmp(
2556 count,
2557 &cursor_location.count(*include_dirs, *include_ignored),
2558 ),
2559 }
2560 }
2561}
2562
2563struct ChildEntriesIter<'a> {
2564 parent_path: &'a Path,
2565 traversal: Traversal<'a>,
2566}
2567
2568impl<'a> Iterator for ChildEntriesIter<'a> {
2569 type Item = &'a Entry;
2570
2571 fn next(&mut self) -> Option<Self::Item> {
2572 if let Some(item) = self.traversal.entry() {
2573 if item.path.starts_with(&self.parent_path) {
2574 self.traversal.advance_to_sibling();
2575 return Some(item);
2576 }
2577 }
2578 None
2579 }
2580}
2581
2582impl<'a> From<&'a Entry> for proto::Entry {
2583 fn from(entry: &'a Entry) -> Self {
2584 Self {
2585 id: entry.id.to_proto(),
2586 is_dir: entry.is_dir(),
2587 path: entry.path.as_os_str().as_bytes().to_vec(),
2588 inode: entry.inode,
2589 mtime: Some(entry.mtime.into()),
2590 is_symlink: entry.is_symlink,
2591 is_ignored: entry.is_ignored,
2592 }
2593 }
2594}
2595
2596impl<'a> TryFrom<(&'a CharBag, proto::Entry)> for Entry {
2597 type Error = anyhow::Error;
2598
2599 fn try_from((root_char_bag, entry): (&'a CharBag, proto::Entry)) -> Result<Self> {
2600 if let Some(mtime) = entry.mtime {
2601 let kind = if entry.is_dir {
2602 EntryKind::Dir
2603 } else {
2604 let mut char_bag = root_char_bag.clone();
2605 char_bag.extend(
2606 String::from_utf8_lossy(&entry.path)
2607 .chars()
2608 .map(|c| c.to_ascii_lowercase()),
2609 );
2610 EntryKind::File(char_bag)
2611 };
2612 let path: Arc<Path> = PathBuf::from(OsString::from_vec(entry.path)).into();
2613 Ok(Entry {
2614 id: ProjectEntryId::from_proto(entry.id),
2615 kind,
2616 path: path.clone(),
2617 inode: entry.inode,
2618 mtime: mtime.into(),
2619 is_symlink: entry.is_symlink,
2620 is_ignored: entry.is_ignored,
2621 })
2622 } else {
2623 Err(anyhow!(
2624 "missing mtime in remote worktree entry {:?}",
2625 entry.path
2626 ))
2627 }
2628 }
2629}
2630
2631async fn send_worktree_update(client: &Arc<Client>, update: proto::UpdateWorktree) -> Result<()> {
2632 #[cfg(any(test, feature = "test-support"))]
2633 const MAX_CHUNK_SIZE: usize = 2;
2634 #[cfg(not(any(test, feature = "test-support")))]
2635 const MAX_CHUNK_SIZE: usize = 256;
2636
2637 for update in proto::split_worktree_update(update, MAX_CHUNK_SIZE) {
2638 client.request(update).await?;
2639 }
2640
2641 Ok(())
2642}
2643
2644#[cfg(test)]
2645mod tests {
2646 use super::*;
2647 use crate::fs::FakeFs;
2648 use anyhow::Result;
2649 use client::test::FakeHttpClient;
2650 use fs::RealFs;
2651 use gpui::TestAppContext;
2652 use rand::prelude::*;
2653 use serde_json::json;
2654 use std::{
2655 env,
2656 fmt::Write,
2657 time::{SystemTime, UNIX_EPOCH},
2658 };
2659 use util::test::temp_tree;
2660
2661 #[gpui::test]
2662 async fn test_traversal(cx: &mut TestAppContext) {
2663 let fs = FakeFs::new(cx.background());
2664 fs.insert_tree(
2665 "/root",
2666 json!({
2667 ".gitignore": "a/b\n",
2668 "a": {
2669 "b": "",
2670 "c": "",
2671 }
2672 }),
2673 )
2674 .await;
2675
2676 let http_client = FakeHttpClient::with_404_response();
2677 let client = Client::new(http_client);
2678
2679 let tree = Worktree::local(
2680 client,
2681 Arc::from(Path::new("/root")),
2682 true,
2683 fs,
2684 Default::default(),
2685 &mut cx.to_async(),
2686 )
2687 .await
2688 .unwrap();
2689 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2690 .await;
2691
2692 tree.read_with(cx, |tree, _| {
2693 assert_eq!(
2694 tree.entries(false)
2695 .map(|entry| entry.path.as_ref())
2696 .collect::<Vec<_>>(),
2697 vec![
2698 Path::new(""),
2699 Path::new(".gitignore"),
2700 Path::new("a"),
2701 Path::new("a/c"),
2702 ]
2703 );
2704 assert_eq!(
2705 tree.entries(true)
2706 .map(|entry| entry.path.as_ref())
2707 .collect::<Vec<_>>(),
2708 vec![
2709 Path::new(""),
2710 Path::new(".gitignore"),
2711 Path::new("a"),
2712 Path::new("a/b"),
2713 Path::new("a/c"),
2714 ]
2715 );
2716 })
2717 }
2718
2719 #[gpui::test]
2720 async fn test_rescan_with_gitignore(cx: &mut TestAppContext) {
2721 let dir = temp_tree(json!({
2722 ".git": {},
2723 ".gitignore": "ignored-dir\n",
2724 "tracked-dir": {
2725 "tracked-file1": "tracked contents",
2726 },
2727 "ignored-dir": {
2728 "ignored-file1": "ignored contents",
2729 }
2730 }));
2731
2732 let http_client = FakeHttpClient::with_404_response();
2733 let client = Client::new(http_client.clone());
2734
2735 let tree = Worktree::local(
2736 client,
2737 dir.path(),
2738 true,
2739 Arc::new(RealFs),
2740 Default::default(),
2741 &mut cx.to_async(),
2742 )
2743 .await
2744 .unwrap();
2745 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2746 .await;
2747 tree.flush_fs_events(&cx).await;
2748 cx.read(|cx| {
2749 let tree = tree.read(cx);
2750 let tracked = tree.entry_for_path("tracked-dir/tracked-file1").unwrap();
2751 let ignored = tree.entry_for_path("ignored-dir/ignored-file1").unwrap();
2752 assert_eq!(tracked.is_ignored, false);
2753 assert_eq!(ignored.is_ignored, true);
2754 });
2755
2756 std::fs::write(dir.path().join("tracked-dir/tracked-file2"), "").unwrap();
2757 std::fs::write(dir.path().join("ignored-dir/ignored-file2"), "").unwrap();
2758 tree.flush_fs_events(&cx).await;
2759 cx.read(|cx| {
2760 let tree = tree.read(cx);
2761 let dot_git = tree.entry_for_path(".git").unwrap();
2762 let tracked = tree.entry_for_path("tracked-dir/tracked-file2").unwrap();
2763 let ignored = tree.entry_for_path("ignored-dir/ignored-file2").unwrap();
2764 assert_eq!(tracked.is_ignored, false);
2765 assert_eq!(ignored.is_ignored, true);
2766 assert_eq!(dot_git.is_ignored, true);
2767 });
2768 }
2769
2770 #[gpui::test]
2771 async fn test_write_file(cx: &mut TestAppContext) {
2772 let dir = temp_tree(json!({
2773 ".git": {},
2774 ".gitignore": "ignored-dir\n",
2775 "tracked-dir": {},
2776 "ignored-dir": {}
2777 }));
2778
2779 let http_client = FakeHttpClient::with_404_response();
2780 let client = Client::new(http_client.clone());
2781
2782 let tree = Worktree::local(
2783 client,
2784 dir.path(),
2785 true,
2786 Arc::new(RealFs),
2787 Default::default(),
2788 &mut cx.to_async(),
2789 )
2790 .await
2791 .unwrap();
2792 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2793 .await;
2794 tree.flush_fs_events(&cx).await;
2795
2796 tree.update(cx, |tree, cx| {
2797 tree.as_local().unwrap().write_file(
2798 Path::new("tracked-dir/file.txt"),
2799 "hello".into(),
2800 cx,
2801 )
2802 })
2803 .await
2804 .unwrap();
2805 tree.update(cx, |tree, cx| {
2806 tree.as_local().unwrap().write_file(
2807 Path::new("ignored-dir/file.txt"),
2808 "world".into(),
2809 cx,
2810 )
2811 })
2812 .await
2813 .unwrap();
2814
2815 tree.read_with(cx, |tree, _| {
2816 let tracked = tree.entry_for_path("tracked-dir/file.txt").unwrap();
2817 let ignored = tree.entry_for_path("ignored-dir/file.txt").unwrap();
2818 assert_eq!(tracked.is_ignored, false);
2819 assert_eq!(ignored.is_ignored, true);
2820 });
2821 }
2822
2823 #[gpui::test(iterations = 100)]
2824 fn test_random(mut rng: StdRng) {
2825 let operations = env::var("OPERATIONS")
2826 .map(|o| o.parse().unwrap())
2827 .unwrap_or(40);
2828 let initial_entries = env::var("INITIAL_ENTRIES")
2829 .map(|o| o.parse().unwrap())
2830 .unwrap_or(20);
2831
2832 let root_dir = tempdir::TempDir::new("worktree-test").unwrap();
2833 for _ in 0..initial_entries {
2834 randomly_mutate_tree(root_dir.path(), 1.0, &mut rng).unwrap();
2835 }
2836 log::info!("Generated initial tree");
2837
2838 let (notify_tx, _notify_rx) = mpsc::unbounded();
2839 let fs = Arc::new(RealFs);
2840 let next_entry_id = Arc::new(AtomicUsize::new(0));
2841 let mut initial_snapshot = LocalSnapshot {
2842 abs_path: root_dir.path().into(),
2843 removed_entry_ids: Default::default(),
2844 ignores: Default::default(),
2845 next_entry_id: next_entry_id.clone(),
2846 snapshot: Snapshot {
2847 id: WorktreeId::from_usize(0),
2848 entries_by_path: Default::default(),
2849 entries_by_id: Default::default(),
2850 root_name: Default::default(),
2851 root_char_bag: Default::default(),
2852 scan_id: 0,
2853 is_complete: true,
2854 },
2855 };
2856 initial_snapshot.insert_entry(
2857 Entry::new(
2858 Path::new("").into(),
2859 &smol::block_on(fs.metadata(root_dir.path()))
2860 .unwrap()
2861 .unwrap(),
2862 &next_entry_id,
2863 Default::default(),
2864 ),
2865 fs.as_ref(),
2866 );
2867 let mut scanner = BackgroundScanner::new(
2868 Arc::new(Mutex::new(initial_snapshot.clone())),
2869 notify_tx,
2870 fs.clone(),
2871 Arc::new(gpui::executor::Background::new()),
2872 );
2873 smol::block_on(scanner.scan_dirs()).unwrap();
2874 scanner.snapshot().check_invariants();
2875
2876 let mut events = Vec::new();
2877 let mut snapshots = Vec::new();
2878 let mut mutations_len = operations;
2879 while mutations_len > 1 {
2880 if !events.is_empty() && rng.gen_bool(0.4) {
2881 let len = rng.gen_range(0..=events.len());
2882 let to_deliver = events.drain(0..len).collect::<Vec<_>>();
2883 log::info!("Delivering events: {:#?}", to_deliver);
2884 smol::block_on(scanner.process_events(to_deliver));
2885 scanner.snapshot().check_invariants();
2886 } else {
2887 events.extend(randomly_mutate_tree(root_dir.path(), 0.6, &mut rng).unwrap());
2888 mutations_len -= 1;
2889 }
2890
2891 if rng.gen_bool(0.2) {
2892 snapshots.push(scanner.snapshot());
2893 }
2894 }
2895 log::info!("Quiescing: {:#?}", events);
2896 smol::block_on(scanner.process_events(events));
2897 scanner.snapshot().check_invariants();
2898
2899 let (notify_tx, _notify_rx) = mpsc::unbounded();
2900 let mut new_scanner = BackgroundScanner::new(
2901 Arc::new(Mutex::new(initial_snapshot)),
2902 notify_tx,
2903 scanner.fs.clone(),
2904 scanner.executor.clone(),
2905 );
2906 smol::block_on(new_scanner.scan_dirs()).unwrap();
2907 assert_eq!(
2908 scanner.snapshot().to_vec(true),
2909 new_scanner.snapshot().to_vec(true)
2910 );
2911
2912 for mut prev_snapshot in snapshots {
2913 let include_ignored = rng.gen::<bool>();
2914 if !include_ignored {
2915 let mut entries_by_path_edits = Vec::new();
2916 let mut entries_by_id_edits = Vec::new();
2917 for entry in prev_snapshot
2918 .entries_by_id
2919 .cursor::<()>()
2920 .filter(|e| e.is_ignored)
2921 {
2922 entries_by_path_edits.push(Edit::Remove(PathKey(entry.path.clone())));
2923 entries_by_id_edits.push(Edit::Remove(entry.id));
2924 }
2925
2926 prev_snapshot
2927 .entries_by_path
2928 .edit(entries_by_path_edits, &());
2929 prev_snapshot.entries_by_id.edit(entries_by_id_edits, &());
2930 }
2931
2932 let update = scanner
2933 .snapshot()
2934 .build_update(&prev_snapshot, 0, 0, include_ignored);
2935 prev_snapshot.apply_remote_update(update).unwrap();
2936 assert_eq!(
2937 prev_snapshot.to_vec(true),
2938 scanner.snapshot().to_vec(include_ignored)
2939 );
2940 }
2941 }
2942
2943 fn randomly_mutate_tree(
2944 root_path: &Path,
2945 insertion_probability: f64,
2946 rng: &mut impl Rng,
2947 ) -> Result<Vec<fsevent::Event>> {
2948 let root_path = root_path.canonicalize().unwrap();
2949 let (dirs, files) = read_dir_recursive(root_path.clone());
2950
2951 let mut events = Vec::new();
2952 let mut record_event = |path: PathBuf| {
2953 events.push(fsevent::Event {
2954 event_id: SystemTime::now()
2955 .duration_since(UNIX_EPOCH)
2956 .unwrap()
2957 .as_secs(),
2958 flags: fsevent::StreamFlags::empty(),
2959 path,
2960 });
2961 };
2962
2963 if (files.is_empty() && dirs.len() == 1) || rng.gen_bool(insertion_probability) {
2964 let path = dirs.choose(rng).unwrap();
2965 let new_path = path.join(gen_name(rng));
2966
2967 if rng.gen() {
2968 log::info!("Creating dir {:?}", new_path.strip_prefix(root_path)?);
2969 std::fs::create_dir(&new_path)?;
2970 } else {
2971 log::info!("Creating file {:?}", new_path.strip_prefix(root_path)?);
2972 std::fs::write(&new_path, "")?;
2973 }
2974 record_event(new_path);
2975 } else if rng.gen_bool(0.05) {
2976 let ignore_dir_path = dirs.choose(rng).unwrap();
2977 let ignore_path = ignore_dir_path.join(&*GITIGNORE);
2978
2979 let (subdirs, subfiles) = read_dir_recursive(ignore_dir_path.clone());
2980 let files_to_ignore = {
2981 let len = rng.gen_range(0..=subfiles.len());
2982 subfiles.choose_multiple(rng, len)
2983 };
2984 let dirs_to_ignore = {
2985 let len = rng.gen_range(0..subdirs.len());
2986 subdirs.choose_multiple(rng, len)
2987 };
2988
2989 let mut ignore_contents = String::new();
2990 for path_to_ignore in files_to_ignore.chain(dirs_to_ignore) {
2991 write!(
2992 ignore_contents,
2993 "{}\n",
2994 path_to_ignore
2995 .strip_prefix(&ignore_dir_path)?
2996 .to_str()
2997 .unwrap()
2998 )
2999 .unwrap();
3000 }
3001 log::info!(
3002 "Creating {:?} with contents:\n{}",
3003 ignore_path.strip_prefix(&root_path)?,
3004 ignore_contents
3005 );
3006 std::fs::write(&ignore_path, ignore_contents).unwrap();
3007 record_event(ignore_path);
3008 } else {
3009 let old_path = {
3010 let file_path = files.choose(rng);
3011 let dir_path = dirs[1..].choose(rng);
3012 file_path.into_iter().chain(dir_path).choose(rng).unwrap()
3013 };
3014
3015 let is_rename = rng.gen();
3016 if is_rename {
3017 let new_path_parent = dirs
3018 .iter()
3019 .filter(|d| !d.starts_with(old_path))
3020 .choose(rng)
3021 .unwrap();
3022
3023 let overwrite_existing_dir =
3024 !old_path.starts_with(&new_path_parent) && rng.gen_bool(0.3);
3025 let new_path = if overwrite_existing_dir {
3026 std::fs::remove_dir_all(&new_path_parent).ok();
3027 new_path_parent.to_path_buf()
3028 } else {
3029 new_path_parent.join(gen_name(rng))
3030 };
3031
3032 log::info!(
3033 "Renaming {:?} to {}{:?}",
3034 old_path.strip_prefix(&root_path)?,
3035 if overwrite_existing_dir {
3036 "overwrite "
3037 } else {
3038 ""
3039 },
3040 new_path.strip_prefix(&root_path)?
3041 );
3042 std::fs::rename(&old_path, &new_path)?;
3043 record_event(old_path.clone());
3044 record_event(new_path);
3045 } else if old_path.is_dir() {
3046 let (dirs, files) = read_dir_recursive(old_path.clone());
3047
3048 log::info!("Deleting dir {:?}", old_path.strip_prefix(&root_path)?);
3049 std::fs::remove_dir_all(&old_path).unwrap();
3050 for file in files {
3051 record_event(file);
3052 }
3053 for dir in dirs {
3054 record_event(dir);
3055 }
3056 } else {
3057 log::info!("Deleting file {:?}", old_path.strip_prefix(&root_path)?);
3058 std::fs::remove_file(old_path).unwrap();
3059 record_event(old_path.clone());
3060 }
3061 }
3062
3063 Ok(events)
3064 }
3065
3066 fn read_dir_recursive(path: PathBuf) -> (Vec<PathBuf>, Vec<PathBuf>) {
3067 let child_entries = std::fs::read_dir(&path).unwrap();
3068 let mut dirs = vec![path];
3069 let mut files = Vec::new();
3070 for child_entry in child_entries {
3071 let child_path = child_entry.unwrap().path();
3072 if child_path.is_dir() {
3073 let (child_dirs, child_files) = read_dir_recursive(child_path);
3074 dirs.extend(child_dirs);
3075 files.extend(child_files);
3076 } else {
3077 files.push(child_path);
3078 }
3079 }
3080 (dirs, files)
3081 }
3082
3083 fn gen_name(rng: &mut impl Rng) -> String {
3084 (0..6)
3085 .map(|_| rng.sample(rand::distributions::Alphanumeric))
3086 .map(char::from)
3087 .collect()
3088 }
3089
3090 impl LocalSnapshot {
3091 fn check_invariants(&self) {
3092 let mut files = self.files(true, 0);
3093 let mut visible_files = self.files(false, 0);
3094 for entry in self.entries_by_path.cursor::<()>() {
3095 if entry.is_file() {
3096 assert_eq!(files.next().unwrap().inode, entry.inode);
3097 if !entry.is_ignored {
3098 assert_eq!(visible_files.next().unwrap().inode, entry.inode);
3099 }
3100 }
3101 }
3102 assert!(files.next().is_none());
3103 assert!(visible_files.next().is_none());
3104
3105 let mut bfs_paths = Vec::new();
3106 let mut stack = vec![Path::new("")];
3107 while let Some(path) = stack.pop() {
3108 bfs_paths.push(path);
3109 let ix = stack.len();
3110 for child_entry in self.child_entries(path) {
3111 stack.insert(ix, &child_entry.path);
3112 }
3113 }
3114
3115 let dfs_paths_via_iter = self
3116 .entries_by_path
3117 .cursor::<()>()
3118 .map(|e| e.path.as_ref())
3119 .collect::<Vec<_>>();
3120 assert_eq!(bfs_paths, dfs_paths_via_iter);
3121
3122 let dfs_paths_via_traversal = self
3123 .entries(true)
3124 .map(|e| e.path.as_ref())
3125 .collect::<Vec<_>>();
3126 assert_eq!(dfs_paths_via_traversal, dfs_paths_via_iter);
3127
3128 for (ignore_parent_path, _) in &self.ignores {
3129 assert!(self.entry_for_path(ignore_parent_path).is_some());
3130 assert!(self
3131 .entry_for_path(ignore_parent_path.join(&*GITIGNORE))
3132 .is_some());
3133 }
3134 }
3135
3136 fn to_vec(&self, include_ignored: bool) -> Vec<(&Path, u64, bool)> {
3137 let mut paths = Vec::new();
3138 for entry in self.entries_by_path.cursor::<()>() {
3139 if include_ignored || !entry.is_ignored {
3140 paths.push((entry.path.as_ref(), entry.inode, entry.is_ignored));
3141 }
3142 }
3143 paths.sort_by(|a, b| a.0.cmp(&b.0));
3144 paths
3145 }
3146 }
3147}