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