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