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