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