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