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