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 pub fn send_extension_counts(&self, project_id: u64) {
1042 let mut extensions = Vec::new();
1043 let mut counts = Vec::new();
1044
1045 for (extension, count) in self.extension_counts() {
1046 extensions.push(extension.to_string_lossy().to_string());
1047 counts.push(*count as u32);
1048 }
1049
1050 self.client
1051 .send(proto::UpdateWorktreeExtensions {
1052 project_id,
1053 worktree_id: self.id().to_proto(),
1054 extensions,
1055 counts,
1056 })
1057 .log_err();
1058 }
1059}
1060
1061impl RemoteWorktree {
1062 fn snapshot(&self) -> Snapshot {
1063 self.snapshot.clone()
1064 }
1065
1066 pub fn disconnected_from_host(&mut self) {
1067 self.updates_tx.take();
1068 }
1069
1070 pub fn update_from_remote(
1071 &mut self,
1072 envelope: TypedEnvelope<proto::UpdateWorktree>,
1073 ) -> Result<()> {
1074 if let Some(updates_tx) = &self.updates_tx {
1075 updates_tx
1076 .unbounded_send(envelope.payload)
1077 .expect("consumer runs to completion");
1078 }
1079 Ok(())
1080 }
1081
1082 fn wait_for_snapshot(&self, scan_id: usize) -> impl Future<Output = ()> {
1083 let mut rx = self.last_scan_id_rx.clone();
1084 async move {
1085 while let Some(applied_scan_id) = rx.next().await {
1086 if applied_scan_id >= scan_id {
1087 return;
1088 }
1089 }
1090 }
1091 }
1092
1093 pub fn update_diagnostic_summary(
1094 &mut self,
1095 path: Arc<Path>,
1096 summary: &proto::DiagnosticSummary,
1097 ) {
1098 let summary = DiagnosticSummary {
1099 language_server_id: summary.language_server_id as usize,
1100 error_count: summary.error_count as usize,
1101 warning_count: summary.warning_count as usize,
1102 };
1103 if summary.is_empty() {
1104 self.diagnostic_summaries.remove(&PathKey(path.clone()));
1105 } else {
1106 self.diagnostic_summaries
1107 .insert(PathKey(path.clone()), summary);
1108 }
1109 }
1110
1111 pub fn insert_entry(
1112 &self,
1113 entry: proto::Entry,
1114 scan_id: usize,
1115 cx: &mut ModelContext<Worktree>,
1116 ) -> Task<Result<Entry>> {
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 let entry = snapshot.insert_entry(entry);
1124 worktree.snapshot = snapshot.clone();
1125 entry
1126 })
1127 })
1128 }
1129
1130 pub(crate) fn delete_entry(
1131 &self,
1132 id: ProjectEntryId,
1133 scan_id: usize,
1134 cx: &mut ModelContext<Worktree>,
1135 ) -> Task<Result<()>> {
1136 let wait_for_snapshot = self.wait_for_snapshot(scan_id);
1137 cx.spawn(|this, mut cx| async move {
1138 wait_for_snapshot.await;
1139 this.update(&mut cx, |worktree, _| {
1140 let worktree = worktree.as_remote_mut().unwrap();
1141 let mut snapshot = worktree.background_snapshot.lock();
1142 snapshot.delete_entry(id);
1143 worktree.snapshot = snapshot.clone();
1144 });
1145 Ok(())
1146 })
1147 }
1148}
1149
1150impl Snapshot {
1151 pub fn id(&self) -> WorktreeId {
1152 self.id
1153 }
1154
1155 pub fn contains_entry(&self, entry_id: ProjectEntryId) -> bool {
1156 self.entries_by_id.get(&entry_id, &()).is_some()
1157 }
1158
1159 pub(crate) fn insert_entry(&mut self, entry: proto::Entry) -> Result<Entry> {
1160 let entry = Entry::try_from((&self.root_char_bag, entry))?;
1161 let old_entry = self.entries_by_id.insert_or_replace(
1162 PathEntry {
1163 id: entry.id,
1164 path: entry.path.clone(),
1165 is_ignored: entry.is_ignored,
1166 scan_id: 0,
1167 },
1168 &(),
1169 );
1170 if let Some(old_entry) = old_entry {
1171 self.entries_by_path.remove(&PathKey(old_entry.path), &());
1172 }
1173 self.entries_by_path.insert_or_replace(entry.clone(), &());
1174 Ok(entry)
1175 }
1176
1177 fn delete_entry(&mut self, entry_id: ProjectEntryId) -> bool {
1178 if let Some(removed_entry) = self.entries_by_id.remove(&entry_id, &()) {
1179 self.entries_by_path = {
1180 let mut cursor = self.entries_by_path.cursor();
1181 let mut new_entries_by_path =
1182 cursor.slice(&TraversalTarget::Path(&removed_entry.path), Bias::Left, &());
1183 while let Some(entry) = cursor.item() {
1184 if entry.path.starts_with(&removed_entry.path) {
1185 self.entries_by_id.remove(&entry.id, &());
1186 cursor.next(&());
1187 } else {
1188 break;
1189 }
1190 }
1191 new_entries_by_path.push_tree(cursor.suffix(&()), &());
1192 new_entries_by_path
1193 };
1194
1195 true
1196 } else {
1197 false
1198 }
1199 }
1200
1201 pub(crate) fn apply_remote_update(&mut self, update: proto::UpdateWorktree) -> Result<()> {
1202 let mut entries_by_path_edits = Vec::new();
1203 let mut entries_by_id_edits = Vec::new();
1204 for entry_id in update.removed_entries {
1205 let entry = self
1206 .entry_for_id(ProjectEntryId::from_proto(entry_id))
1207 .ok_or_else(|| anyhow!("unknown entry"))?;
1208 entries_by_path_edits.push(Edit::Remove(PathKey(entry.path.clone())));
1209 entries_by_id_edits.push(Edit::Remove(entry.id));
1210 }
1211
1212 for entry in update.updated_entries {
1213 let entry = Entry::try_from((&self.root_char_bag, entry))?;
1214 if let Some(PathEntry { path, .. }) = self.entries_by_id.get(&entry.id, &()) {
1215 entries_by_path_edits.push(Edit::Remove(PathKey(path.clone())));
1216 }
1217 entries_by_id_edits.push(Edit::Insert(PathEntry {
1218 id: entry.id,
1219 path: entry.path.clone(),
1220 is_ignored: entry.is_ignored,
1221 scan_id: 0,
1222 }));
1223 entries_by_path_edits.push(Edit::Insert(entry));
1224 }
1225
1226 self.entries_by_path.edit(entries_by_path_edits, &());
1227 self.entries_by_id.edit(entries_by_id_edits, &());
1228 self.scan_id = update.scan_id as usize;
1229
1230 Ok(())
1231 }
1232
1233 pub fn file_count(&self) -> usize {
1234 self.entries_by_path.summary().file_count
1235 }
1236
1237 pub fn visible_file_count(&self) -> usize {
1238 self.entries_by_path.summary().visible_file_count
1239 }
1240
1241 fn traverse_from_offset(
1242 &self,
1243 include_dirs: bool,
1244 include_ignored: bool,
1245 start_offset: usize,
1246 ) -> Traversal {
1247 let mut cursor = self.entries_by_path.cursor();
1248 cursor.seek(
1249 &TraversalTarget::Count {
1250 count: start_offset,
1251 include_dirs,
1252 include_ignored,
1253 },
1254 Bias::Right,
1255 &(),
1256 );
1257 Traversal {
1258 cursor,
1259 include_dirs,
1260 include_ignored,
1261 }
1262 }
1263
1264 fn traverse_from_path(
1265 &self,
1266 include_dirs: bool,
1267 include_ignored: bool,
1268 path: &Path,
1269 ) -> Traversal {
1270 let mut cursor = self.entries_by_path.cursor();
1271 cursor.seek(&TraversalTarget::Path(path), Bias::Left, &());
1272 Traversal {
1273 cursor,
1274 include_dirs,
1275 include_ignored,
1276 }
1277 }
1278
1279 pub fn files(&self, include_ignored: bool, start: usize) -> Traversal {
1280 self.traverse_from_offset(false, include_ignored, start)
1281 }
1282
1283 pub fn entries(&self, include_ignored: bool) -> Traversal {
1284 self.traverse_from_offset(true, include_ignored, 0)
1285 }
1286
1287 pub fn paths(&self) -> impl Iterator<Item = &Arc<Path>> {
1288 let empty_path = Path::new("");
1289 self.entries_by_path
1290 .cursor::<()>()
1291 .filter(move |entry| entry.path.as_ref() != empty_path)
1292 .map(|entry| &entry.path)
1293 }
1294
1295 fn child_entries<'a>(&'a self, parent_path: &'a Path) -> ChildEntriesIter<'a> {
1296 let mut cursor = self.entries_by_path.cursor();
1297 cursor.seek(&TraversalTarget::Path(parent_path), Bias::Right, &());
1298 let traversal = Traversal {
1299 cursor,
1300 include_dirs: true,
1301 include_ignored: true,
1302 };
1303 ChildEntriesIter {
1304 traversal,
1305 parent_path,
1306 }
1307 }
1308
1309 pub fn root_entry(&self) -> Option<&Entry> {
1310 self.entry_for_path("")
1311 }
1312
1313 pub fn root_name(&self) -> &str {
1314 &self.root_name
1315 }
1316
1317 pub fn scan_id(&self) -> usize {
1318 self.scan_id
1319 }
1320
1321 pub fn entry_for_path(&self, path: impl AsRef<Path>) -> Option<&Entry> {
1322 let path = path.as_ref();
1323 self.traverse_from_path(true, true, path)
1324 .entry()
1325 .and_then(|entry| {
1326 if entry.path.as_ref() == path {
1327 Some(entry)
1328 } else {
1329 None
1330 }
1331 })
1332 }
1333
1334 pub fn entry_for_id(&self, id: ProjectEntryId) -> Option<&Entry> {
1335 let entry = self.entries_by_id.get(&id, &())?;
1336 self.entry_for_path(&entry.path)
1337 }
1338
1339 pub fn inode_for_path(&self, path: impl AsRef<Path>) -> Option<u64> {
1340 self.entry_for_path(path.as_ref()).map(|e| e.inode)
1341 }
1342}
1343
1344impl LocalSnapshot {
1345 pub fn abs_path(&self) -> &Arc<Path> {
1346 &self.abs_path
1347 }
1348
1349 pub fn extension_counts(&self) -> &HashMap<OsString, usize> {
1350 &self.extension_counts
1351 }
1352
1353 #[cfg(test)]
1354 pub(crate) fn to_proto(
1355 &self,
1356 diagnostic_summaries: &TreeMap<PathKey, DiagnosticSummary>,
1357 visible: bool,
1358 ) -> proto::Worktree {
1359 let root_name = self.root_name.clone();
1360 proto::Worktree {
1361 id: self.id.0 as u64,
1362 root_name,
1363 entries: self
1364 .entries_by_path
1365 .iter()
1366 .filter(|e| !e.is_ignored)
1367 .map(Into::into)
1368 .collect(),
1369 diagnostic_summaries: diagnostic_summaries
1370 .iter()
1371 .map(|(path, summary)| summary.to_proto(&path.0))
1372 .collect(),
1373 visible,
1374 scan_id: self.scan_id as u64,
1375 }
1376 }
1377
1378 pub(crate) fn build_update(
1379 &self,
1380 other: &Self,
1381 project_id: u64,
1382 worktree_id: u64,
1383 include_ignored: bool,
1384 ) -> proto::UpdateWorktree {
1385 let mut updated_entries = Vec::new();
1386 let mut removed_entries = Vec::new();
1387 let mut self_entries = self
1388 .entries_by_id
1389 .cursor::<()>()
1390 .filter(|e| include_ignored || !e.is_ignored)
1391 .peekable();
1392 let mut other_entries = other
1393 .entries_by_id
1394 .cursor::<()>()
1395 .filter(|e| include_ignored || !e.is_ignored)
1396 .peekable();
1397 loop {
1398 match (self_entries.peek(), other_entries.peek()) {
1399 (Some(self_entry), Some(other_entry)) => {
1400 match Ord::cmp(&self_entry.id, &other_entry.id) {
1401 Ordering::Less => {
1402 let entry = self.entry_for_id(self_entry.id).unwrap().into();
1403 updated_entries.push(entry);
1404 self_entries.next();
1405 }
1406 Ordering::Equal => {
1407 if self_entry.scan_id != other_entry.scan_id {
1408 let entry = self.entry_for_id(self_entry.id).unwrap().into();
1409 updated_entries.push(entry);
1410 }
1411
1412 self_entries.next();
1413 other_entries.next();
1414 }
1415 Ordering::Greater => {
1416 removed_entries.push(other_entry.id.to_proto());
1417 other_entries.next();
1418 }
1419 }
1420 }
1421 (Some(self_entry), None) => {
1422 let entry = self.entry_for_id(self_entry.id).unwrap().into();
1423 updated_entries.push(entry);
1424 self_entries.next();
1425 }
1426 (None, Some(other_entry)) => {
1427 removed_entries.push(other_entry.id.to_proto());
1428 other_entries.next();
1429 }
1430 (None, None) => break,
1431 }
1432 }
1433
1434 proto::UpdateWorktree {
1435 project_id,
1436 worktree_id,
1437 root_name: self.root_name().to_string(),
1438 updated_entries,
1439 removed_entries,
1440 scan_id: self.scan_id as u64,
1441 }
1442 }
1443
1444 fn insert_entry(&mut self, mut entry: Entry, fs: &dyn Fs) -> Entry {
1445 if !entry.is_dir() && entry.path.file_name() == Some(&GITIGNORE) {
1446 let abs_path = self.abs_path.join(&entry.path);
1447 match build_gitignore(&abs_path, fs) {
1448 Ok(ignore) => {
1449 let ignore_dir_path = entry.path.parent().unwrap();
1450 self.ignores
1451 .insert(ignore_dir_path.into(), (Arc::new(ignore), self.scan_id));
1452 }
1453 Err(error) => {
1454 log::error!(
1455 "error loading .gitignore file {:?} - {:?}",
1456 &entry.path,
1457 error
1458 );
1459 }
1460 }
1461 }
1462
1463 self.reuse_entry_id(&mut entry);
1464 self.entries_by_path.insert_or_replace(entry.clone(), &());
1465 let scan_id = self.scan_id;
1466 let removed_entry = self.entries_by_id.insert_or_replace(
1467 PathEntry {
1468 id: entry.id,
1469 path: entry.path.clone(),
1470 is_ignored: entry.is_ignored,
1471 scan_id,
1472 },
1473 &(),
1474 );
1475
1476 if let Some(removed_entry) = removed_entry {
1477 self.dec_extension_count(&removed_entry.path, removed_entry.is_ignored);
1478 }
1479 self.inc_extension_count(&entry.path, entry.is_ignored);
1480
1481 entry
1482 }
1483
1484 fn populate_dir(
1485 &mut self,
1486 parent_path: Arc<Path>,
1487 entries: impl IntoIterator<Item = Entry>,
1488 ignore: Option<Arc<Gitignore>>,
1489 ) {
1490 let mut parent_entry = if let Some(parent_entry) =
1491 self.entries_by_path.get(&PathKey(parent_path.clone()), &())
1492 {
1493 parent_entry.clone()
1494 } else {
1495 log::warn!(
1496 "populating a directory {:?} that has been removed",
1497 parent_path
1498 );
1499 return;
1500 };
1501
1502 if let Some(ignore) = ignore {
1503 self.ignores.insert(parent_path, (ignore, self.scan_id));
1504 }
1505 if matches!(parent_entry.kind, EntryKind::PendingDir) {
1506 parent_entry.kind = EntryKind::Dir;
1507 } else {
1508 unreachable!();
1509 }
1510
1511 let mut entries_by_path_edits = vec![Edit::Insert(parent_entry)];
1512 let mut entries_by_id_edits = Vec::new();
1513
1514 for mut entry in entries {
1515 self.reuse_entry_id(&mut entry);
1516 self.inc_extension_count(&entry.path, entry.is_ignored);
1517 entries_by_id_edits.push(Edit::Insert(PathEntry {
1518 id: entry.id,
1519 path: entry.path.clone(),
1520 is_ignored: entry.is_ignored,
1521 scan_id: self.scan_id,
1522 }));
1523 entries_by_path_edits.push(Edit::Insert(entry));
1524 }
1525
1526 self.entries_by_path.edit(entries_by_path_edits, &());
1527 let removed_entries = self.entries_by_id.edit(entries_by_id_edits, &());
1528
1529 for removed_entry in removed_entries {
1530 self.dec_extension_count(&removed_entry.path, removed_entry.is_ignored);
1531 }
1532 }
1533
1534 fn inc_extension_count(&mut self, path: &Path, ignored: bool) {
1535 if !ignored {
1536 if let Some(extension) = path.extension() {
1537 if let Some(count) = self.extension_counts.get_mut(extension) {
1538 *count += 1;
1539 } else {
1540 self.extension_counts.insert(extension.into(), 1);
1541 }
1542 }
1543 }
1544 }
1545
1546 fn dec_extension_count(&mut self, path: &Path, ignored: bool) {
1547 if !ignored {
1548 if let Some(extension) = path.extension() {
1549 if let Some(count) = self.extension_counts.get_mut(extension) {
1550 *count -= 1;
1551 }
1552 }
1553 }
1554 }
1555
1556 fn reuse_entry_id(&mut self, entry: &mut Entry) {
1557 if let Some(removed_entry_id) = self.removed_entry_ids.remove(&entry.inode) {
1558 entry.id = removed_entry_id;
1559 } else if let Some(existing_entry) = self.entry_for_path(&entry.path) {
1560 entry.id = existing_entry.id;
1561 }
1562 }
1563
1564 fn remove_path(&mut self, path: &Path) {
1565 let mut new_entries;
1566 let removed_entries;
1567 {
1568 let mut cursor = self.entries_by_path.cursor::<TraversalProgress>();
1569 new_entries = cursor.slice(&TraversalTarget::Path(path), Bias::Left, &());
1570 removed_entries = cursor.slice(&TraversalTarget::PathSuccessor(path), Bias::Left, &());
1571 new_entries.push_tree(cursor.suffix(&()), &());
1572 }
1573 self.entries_by_path = new_entries;
1574
1575 let mut entries_by_id_edits = Vec::new();
1576 for entry in removed_entries.cursor::<()>() {
1577 let removed_entry_id = self
1578 .removed_entry_ids
1579 .entry(entry.inode)
1580 .or_insert(entry.id);
1581 *removed_entry_id = cmp::max(*removed_entry_id, entry.id);
1582 entries_by_id_edits.push(Edit::Remove(entry.id));
1583 self.dec_extension_count(&entry.path, entry.is_ignored);
1584 }
1585 self.entries_by_id.edit(entries_by_id_edits, &());
1586
1587 if path.file_name() == Some(&GITIGNORE) {
1588 if let Some((_, scan_id)) = self.ignores.get_mut(path.parent().unwrap()) {
1589 *scan_id = self.snapshot.scan_id;
1590 }
1591 }
1592 }
1593
1594 fn ignore_stack_for_path(&self, path: &Path, is_dir: bool) -> Arc<IgnoreStack> {
1595 let mut new_ignores = Vec::new();
1596 for ancestor in path.ancestors().skip(1) {
1597 if let Some((ignore, _)) = self.ignores.get(ancestor) {
1598 new_ignores.push((ancestor, Some(ignore.clone())));
1599 } else {
1600 new_ignores.push((ancestor, None));
1601 }
1602 }
1603
1604 let mut ignore_stack = IgnoreStack::none();
1605 for (parent_path, ignore) in new_ignores.into_iter().rev() {
1606 if ignore_stack.is_path_ignored(&parent_path, true) {
1607 ignore_stack = IgnoreStack::all();
1608 break;
1609 } else if let Some(ignore) = ignore {
1610 ignore_stack = ignore_stack.append(Arc::from(parent_path), ignore);
1611 }
1612 }
1613
1614 if ignore_stack.is_path_ignored(path, is_dir) {
1615 ignore_stack = IgnoreStack::all();
1616 }
1617
1618 ignore_stack
1619 }
1620}
1621
1622fn build_gitignore(abs_path: &Path, fs: &dyn Fs) -> Result<Gitignore> {
1623 let contents = smol::block_on(fs.load(&abs_path))?;
1624 let parent = abs_path.parent().unwrap_or(Path::new("/"));
1625 let mut builder = GitignoreBuilder::new(parent);
1626 for line in contents.lines() {
1627 builder.add_line(Some(abs_path.into()), line)?;
1628 }
1629 Ok(builder.build()?)
1630}
1631
1632impl WorktreeId {
1633 pub fn from_usize(handle_id: usize) -> Self {
1634 Self(handle_id)
1635 }
1636
1637 pub(crate) fn from_proto(id: u64) -> Self {
1638 Self(id as usize)
1639 }
1640
1641 pub fn to_proto(&self) -> u64 {
1642 self.0 as u64
1643 }
1644
1645 pub fn to_usize(&self) -> usize {
1646 self.0
1647 }
1648}
1649
1650impl fmt::Display for WorktreeId {
1651 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1652 self.0.fmt(f)
1653 }
1654}
1655
1656impl Deref for Worktree {
1657 type Target = Snapshot;
1658
1659 fn deref(&self) -> &Self::Target {
1660 match self {
1661 Worktree::Local(worktree) => &worktree.snapshot,
1662 Worktree::Remote(worktree) => &worktree.snapshot,
1663 }
1664 }
1665}
1666
1667impl Deref for LocalWorktree {
1668 type Target = LocalSnapshot;
1669
1670 fn deref(&self) -> &Self::Target {
1671 &self.snapshot
1672 }
1673}
1674
1675impl Deref for RemoteWorktree {
1676 type Target = Snapshot;
1677
1678 fn deref(&self) -> &Self::Target {
1679 &self.snapshot
1680 }
1681}
1682
1683impl fmt::Debug for LocalWorktree {
1684 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1685 self.snapshot.fmt(f)
1686 }
1687}
1688
1689impl fmt::Debug for Snapshot {
1690 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1691 struct EntriesById<'a>(&'a SumTree<PathEntry>);
1692 struct EntriesByPath<'a>(&'a SumTree<Entry>);
1693
1694 impl<'a> fmt::Debug for EntriesByPath<'a> {
1695 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1696 f.debug_map()
1697 .entries(self.0.iter().map(|entry| (&entry.path, entry.id)))
1698 .finish()
1699 }
1700 }
1701
1702 impl<'a> fmt::Debug for EntriesById<'a> {
1703 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1704 f.debug_list().entries(self.0.iter()).finish()
1705 }
1706 }
1707
1708 f.debug_struct("Snapshot")
1709 .field("id", &self.id)
1710 .field("root_name", &self.root_name)
1711 .field("entries_by_path", &EntriesByPath(&self.entries_by_path))
1712 .field("entries_by_id", &EntriesById(&self.entries_by_id))
1713 .finish()
1714 }
1715}
1716
1717#[derive(Clone, PartialEq)]
1718pub struct File {
1719 pub worktree: ModelHandle<Worktree>,
1720 pub path: Arc<Path>,
1721 pub mtime: SystemTime,
1722 pub(crate) entry_id: Option<ProjectEntryId>,
1723 pub(crate) is_local: bool,
1724}
1725
1726impl language::File for File {
1727 fn as_local(&self) -> Option<&dyn language::LocalFile> {
1728 if self.is_local {
1729 Some(self)
1730 } else {
1731 None
1732 }
1733 }
1734
1735 fn mtime(&self) -> SystemTime {
1736 self.mtime
1737 }
1738
1739 fn path(&self) -> &Arc<Path> {
1740 &self.path
1741 }
1742
1743 fn full_path(&self, cx: &AppContext) -> PathBuf {
1744 let mut full_path = PathBuf::new();
1745 full_path.push(self.worktree.read(cx).root_name());
1746 if self.path.components().next().is_some() {
1747 full_path.push(&self.path);
1748 }
1749 full_path
1750 }
1751
1752 /// Returns the last component of this handle's absolute path. If this handle refers to the root
1753 /// of its worktree, then this method will return the name of the worktree itself.
1754 fn file_name(&self, cx: &AppContext) -> OsString {
1755 self.path
1756 .file_name()
1757 .map(|name| name.into())
1758 .unwrap_or_else(|| OsString::from(&self.worktree.read(cx).root_name))
1759 }
1760
1761 fn is_deleted(&self) -> bool {
1762 self.entry_id.is_none()
1763 }
1764
1765 fn save(
1766 &self,
1767 buffer_id: u64,
1768 text: Rope,
1769 version: clock::Global,
1770 cx: &mut MutableAppContext,
1771 ) -> Task<Result<(clock::Global, String, SystemTime)>> {
1772 self.worktree.update(cx, |worktree, cx| match worktree {
1773 Worktree::Local(worktree) => {
1774 let rpc = worktree.client.clone();
1775 let project_id = worktree.share.as_ref().map(|share| share.project_id);
1776 let fingerprint = text.fingerprint();
1777 let save = worktree.write_file(self.path.clone(), text, cx);
1778 cx.background().spawn(async move {
1779 let entry = save.await?;
1780 if let Some(project_id) = project_id {
1781 rpc.send(proto::BufferSaved {
1782 project_id,
1783 buffer_id,
1784 version: serialize_version(&version),
1785 mtime: Some(entry.mtime.into()),
1786 fingerprint: fingerprint.clone(),
1787 })?;
1788 }
1789 Ok((version, fingerprint, entry.mtime))
1790 })
1791 }
1792 Worktree::Remote(worktree) => {
1793 let rpc = worktree.client.clone();
1794 let project_id = worktree.project_id;
1795 cx.foreground().spawn(async move {
1796 let response = rpc
1797 .request(proto::SaveBuffer {
1798 project_id,
1799 buffer_id,
1800 version: serialize_version(&version),
1801 })
1802 .await?;
1803 let version = deserialize_version(response.version);
1804 let mtime = response
1805 .mtime
1806 .ok_or_else(|| anyhow!("missing mtime"))?
1807 .into();
1808 Ok((version, response.fingerprint, mtime))
1809 })
1810 }
1811 })
1812 }
1813
1814 fn as_any(&self) -> &dyn Any {
1815 self
1816 }
1817
1818 fn to_proto(&self) -> rpc::proto::File {
1819 rpc::proto::File {
1820 worktree_id: self.worktree.id() as u64,
1821 entry_id: self.entry_id.map(|entry_id| entry_id.to_proto()),
1822 path: self.path.to_string_lossy().into(),
1823 mtime: Some(self.mtime.into()),
1824 }
1825 }
1826}
1827
1828impl language::LocalFile for File {
1829 fn abs_path(&self, cx: &AppContext) -> PathBuf {
1830 self.worktree
1831 .read(cx)
1832 .as_local()
1833 .unwrap()
1834 .abs_path
1835 .join(&self.path)
1836 }
1837
1838 fn load(&self, cx: &AppContext) -> Task<Result<String>> {
1839 let worktree = self.worktree.read(cx).as_local().unwrap();
1840 let abs_path = worktree.absolutize(&self.path);
1841 let fs = worktree.fs.clone();
1842 cx.background()
1843 .spawn(async move { fs.load(&abs_path).await })
1844 }
1845
1846 fn buffer_reloaded(
1847 &self,
1848 buffer_id: u64,
1849 version: &clock::Global,
1850 fingerprint: String,
1851 mtime: SystemTime,
1852 cx: &mut MutableAppContext,
1853 ) {
1854 let worktree = self.worktree.read(cx).as_local().unwrap();
1855 if let Some(project_id) = worktree.share.as_ref().map(|share| share.project_id) {
1856 worktree
1857 .client
1858 .send(proto::BufferReloaded {
1859 project_id,
1860 buffer_id,
1861 version: serialize_version(&version),
1862 mtime: Some(mtime.into()),
1863 fingerprint,
1864 })
1865 .log_err();
1866 }
1867 }
1868}
1869
1870impl File {
1871 pub fn from_proto(
1872 proto: rpc::proto::File,
1873 worktree: ModelHandle<Worktree>,
1874 cx: &AppContext,
1875 ) -> Result<Self> {
1876 let worktree_id = worktree
1877 .read(cx)
1878 .as_remote()
1879 .ok_or_else(|| anyhow!("not remote"))?
1880 .id();
1881
1882 if worktree_id.to_proto() != proto.worktree_id {
1883 return Err(anyhow!("worktree id does not match file"));
1884 }
1885
1886 Ok(Self {
1887 worktree,
1888 path: Path::new(&proto.path).into(),
1889 mtime: proto.mtime.ok_or_else(|| anyhow!("no timestamp"))?.into(),
1890 entry_id: proto.entry_id.map(ProjectEntryId::from_proto),
1891 is_local: false,
1892 })
1893 }
1894
1895 pub fn from_dyn(file: Option<&dyn language::File>) -> Option<&Self> {
1896 file.and_then(|f| f.as_any().downcast_ref())
1897 }
1898
1899 pub fn worktree_id(&self, cx: &AppContext) -> WorktreeId {
1900 self.worktree.read(cx).id()
1901 }
1902
1903 pub fn project_entry_id(&self, _: &AppContext) -> Option<ProjectEntryId> {
1904 self.entry_id
1905 }
1906}
1907
1908#[derive(Clone, Debug, PartialEq, Eq)]
1909pub struct Entry {
1910 pub id: ProjectEntryId,
1911 pub kind: EntryKind,
1912 pub path: Arc<Path>,
1913 pub inode: u64,
1914 pub mtime: SystemTime,
1915 pub is_symlink: bool,
1916 pub is_ignored: bool,
1917}
1918
1919#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1920pub enum EntryKind {
1921 PendingDir,
1922 Dir,
1923 File(CharBag),
1924}
1925
1926impl Entry {
1927 fn new(
1928 path: Arc<Path>,
1929 metadata: &fs::Metadata,
1930 next_entry_id: &AtomicUsize,
1931 root_char_bag: CharBag,
1932 ) -> Self {
1933 Self {
1934 id: ProjectEntryId::new(next_entry_id),
1935 kind: if metadata.is_dir {
1936 EntryKind::PendingDir
1937 } else {
1938 EntryKind::File(char_bag_for_path(root_char_bag, &path))
1939 },
1940 path,
1941 inode: metadata.inode,
1942 mtime: metadata.mtime,
1943 is_symlink: metadata.is_symlink,
1944 is_ignored: false,
1945 }
1946 }
1947
1948 pub fn is_dir(&self) -> bool {
1949 matches!(self.kind, EntryKind::Dir | EntryKind::PendingDir)
1950 }
1951
1952 pub fn is_file(&self) -> bool {
1953 matches!(self.kind, EntryKind::File(_))
1954 }
1955}
1956
1957impl sum_tree::Item for Entry {
1958 type Summary = EntrySummary;
1959
1960 fn summary(&self) -> Self::Summary {
1961 let visible_count = if self.is_ignored { 0 } else { 1 };
1962 let file_count;
1963 let visible_file_count;
1964 if self.is_file() {
1965 file_count = 1;
1966 visible_file_count = visible_count;
1967 } else {
1968 file_count = 0;
1969 visible_file_count = 0;
1970 }
1971
1972 EntrySummary {
1973 max_path: self.path.clone(),
1974 count: 1,
1975 visible_count,
1976 file_count,
1977 visible_file_count,
1978 }
1979 }
1980}
1981
1982impl sum_tree::KeyedItem for Entry {
1983 type Key = PathKey;
1984
1985 fn key(&self) -> Self::Key {
1986 PathKey(self.path.clone())
1987 }
1988}
1989
1990#[derive(Clone, Debug)]
1991pub struct EntrySummary {
1992 max_path: Arc<Path>,
1993 count: usize,
1994 visible_count: usize,
1995 file_count: usize,
1996 visible_file_count: usize,
1997}
1998
1999impl Default for EntrySummary {
2000 fn default() -> Self {
2001 Self {
2002 max_path: Arc::from(Path::new("")),
2003 count: 0,
2004 visible_count: 0,
2005 file_count: 0,
2006 visible_file_count: 0,
2007 }
2008 }
2009}
2010
2011impl sum_tree::Summary for EntrySummary {
2012 type Context = ();
2013
2014 fn add_summary(&mut self, rhs: &Self, _: &()) {
2015 self.max_path = rhs.max_path.clone();
2016 self.count += rhs.count;
2017 self.visible_count += rhs.visible_count;
2018 self.file_count += rhs.file_count;
2019 self.visible_file_count += rhs.visible_file_count;
2020 }
2021}
2022
2023#[derive(Clone, Debug)]
2024struct PathEntry {
2025 id: ProjectEntryId,
2026 path: Arc<Path>,
2027 is_ignored: bool,
2028 scan_id: usize,
2029}
2030
2031impl sum_tree::Item for PathEntry {
2032 type Summary = PathEntrySummary;
2033
2034 fn summary(&self) -> Self::Summary {
2035 PathEntrySummary { max_id: self.id }
2036 }
2037}
2038
2039impl sum_tree::KeyedItem for PathEntry {
2040 type Key = ProjectEntryId;
2041
2042 fn key(&self) -> Self::Key {
2043 self.id
2044 }
2045}
2046
2047#[derive(Clone, Debug, Default)]
2048struct PathEntrySummary {
2049 max_id: ProjectEntryId,
2050}
2051
2052impl sum_tree::Summary for PathEntrySummary {
2053 type Context = ();
2054
2055 fn add_summary(&mut self, summary: &Self, _: &Self::Context) {
2056 self.max_id = summary.max_id;
2057 }
2058}
2059
2060impl<'a> sum_tree::Dimension<'a, PathEntrySummary> for ProjectEntryId {
2061 fn add_summary(&mut self, summary: &'a PathEntrySummary, _: &()) {
2062 *self = summary.max_id;
2063 }
2064}
2065
2066#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
2067pub struct PathKey(Arc<Path>);
2068
2069impl Default for PathKey {
2070 fn default() -> Self {
2071 Self(Path::new("").into())
2072 }
2073}
2074
2075impl<'a> sum_tree::Dimension<'a, EntrySummary> for PathKey {
2076 fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
2077 self.0 = summary.max_path.clone();
2078 }
2079}
2080
2081struct BackgroundScanner {
2082 fs: Arc<dyn Fs>,
2083 snapshot: Arc<Mutex<LocalSnapshot>>,
2084 notify: UnboundedSender<ScanState>,
2085 executor: Arc<executor::Background>,
2086}
2087
2088impl BackgroundScanner {
2089 fn new(
2090 snapshot: Arc<Mutex<LocalSnapshot>>,
2091 notify: UnboundedSender<ScanState>,
2092 fs: Arc<dyn Fs>,
2093 executor: Arc<executor::Background>,
2094 ) -> Self {
2095 Self {
2096 fs,
2097 snapshot,
2098 notify,
2099 executor,
2100 }
2101 }
2102
2103 fn abs_path(&self) -> Arc<Path> {
2104 self.snapshot.lock().abs_path.clone()
2105 }
2106
2107 fn snapshot(&self) -> LocalSnapshot {
2108 self.snapshot.lock().clone()
2109 }
2110
2111 async fn run(mut self, events_rx: impl Stream<Item = Vec<fsevent::Event>>) {
2112 if self.notify.unbounded_send(ScanState::Scanning).is_err() {
2113 return;
2114 }
2115
2116 if let Err(err) = self.scan_dirs().await {
2117 if self
2118 .notify
2119 .unbounded_send(ScanState::Err(Arc::new(err)))
2120 .is_err()
2121 {
2122 return;
2123 }
2124 }
2125
2126 if self.notify.unbounded_send(ScanState::Idle).is_err() {
2127 return;
2128 }
2129
2130 futures::pin_mut!(events_rx);
2131 while let Some(events) = events_rx.next().await {
2132 if self.notify.unbounded_send(ScanState::Scanning).is_err() {
2133 break;
2134 }
2135
2136 if !self.process_events(events).await {
2137 break;
2138 }
2139
2140 if self.notify.unbounded_send(ScanState::Idle).is_err() {
2141 break;
2142 }
2143 }
2144 }
2145
2146 async fn scan_dirs(&mut self) -> Result<()> {
2147 let root_char_bag;
2148 let next_entry_id;
2149 let is_dir;
2150 {
2151 let snapshot = self.snapshot.lock();
2152 root_char_bag = snapshot.root_char_bag;
2153 next_entry_id = snapshot.next_entry_id.clone();
2154 is_dir = snapshot.root_entry().map_or(false, |e| e.is_dir())
2155 };
2156
2157 if is_dir {
2158 let path: Arc<Path> = Arc::from(Path::new(""));
2159 let abs_path = self.abs_path();
2160 let (tx, rx) = channel::unbounded();
2161 self.executor
2162 .block(tx.send(ScanJob {
2163 abs_path: abs_path.to_path_buf(),
2164 path,
2165 ignore_stack: IgnoreStack::none(),
2166 scan_queue: tx.clone(),
2167 }))
2168 .unwrap();
2169 drop(tx);
2170
2171 self.executor
2172 .scoped(|scope| {
2173 for _ in 0..self.executor.num_cpus() {
2174 scope.spawn(async {
2175 while let Ok(job) = rx.recv().await {
2176 if let Err(err) = self
2177 .scan_dir(root_char_bag, next_entry_id.clone(), &job)
2178 .await
2179 {
2180 log::error!("error scanning {:?}: {}", job.abs_path, err);
2181 }
2182 }
2183 });
2184 }
2185 })
2186 .await;
2187 }
2188
2189 Ok(())
2190 }
2191
2192 async fn scan_dir(
2193 &self,
2194 root_char_bag: CharBag,
2195 next_entry_id: Arc<AtomicUsize>,
2196 job: &ScanJob,
2197 ) -> Result<()> {
2198 let mut new_entries: Vec<Entry> = Vec::new();
2199 let mut new_jobs: Vec<ScanJob> = Vec::new();
2200 let mut ignore_stack = job.ignore_stack.clone();
2201 let mut new_ignore = None;
2202
2203 let mut child_paths = self.fs.read_dir(&job.abs_path).await?;
2204 while let Some(child_abs_path) = child_paths.next().await {
2205 let child_abs_path = match child_abs_path {
2206 Ok(child_abs_path) => child_abs_path,
2207 Err(error) => {
2208 log::error!("error processing entry {:?}", error);
2209 continue;
2210 }
2211 };
2212 let child_name = child_abs_path.file_name().unwrap();
2213 let child_path: Arc<Path> = job.path.join(child_name).into();
2214 let child_metadata = match self.fs.metadata(&child_abs_path).await {
2215 Ok(Some(metadata)) => metadata,
2216 Ok(None) => continue,
2217 Err(err) => {
2218 log::error!("error processing {:?}: {:?}", child_abs_path, err);
2219 continue;
2220 }
2221 };
2222
2223 // If we find a .gitignore, add it to the stack of ignores used to determine which paths are ignored
2224 if child_name == *GITIGNORE {
2225 match build_gitignore(&child_abs_path, self.fs.as_ref()) {
2226 Ok(ignore) => {
2227 let ignore = Arc::new(ignore);
2228 ignore_stack = ignore_stack.append(job.path.clone(), ignore.clone());
2229 new_ignore = Some(ignore);
2230 }
2231 Err(error) => {
2232 log::error!(
2233 "error loading .gitignore file {:?} - {:?}",
2234 child_name,
2235 error
2236 );
2237 }
2238 }
2239
2240 // Update ignore status of any child entries we've already processed to reflect the
2241 // ignore file in the current directory. Because `.gitignore` starts with a `.`,
2242 // there should rarely be too numerous. Update the ignore stack associated with any
2243 // new jobs as well.
2244 let mut new_jobs = new_jobs.iter_mut();
2245 for entry in &mut new_entries {
2246 entry.is_ignored = ignore_stack.is_path_ignored(&entry.path, entry.is_dir());
2247 if entry.is_dir() {
2248 new_jobs.next().unwrap().ignore_stack = if entry.is_ignored {
2249 IgnoreStack::all()
2250 } else {
2251 ignore_stack.clone()
2252 };
2253 }
2254 }
2255 }
2256
2257 let mut child_entry = Entry::new(
2258 child_path.clone(),
2259 &child_metadata,
2260 &next_entry_id,
2261 root_char_bag,
2262 );
2263
2264 if child_metadata.is_dir {
2265 let is_ignored = ignore_stack.is_path_ignored(&child_path, true);
2266 child_entry.is_ignored = is_ignored;
2267 new_entries.push(child_entry);
2268 new_jobs.push(ScanJob {
2269 abs_path: child_abs_path,
2270 path: child_path,
2271 ignore_stack: if is_ignored {
2272 IgnoreStack::all()
2273 } else {
2274 ignore_stack.clone()
2275 },
2276 scan_queue: job.scan_queue.clone(),
2277 });
2278 } else {
2279 child_entry.is_ignored = ignore_stack.is_path_ignored(&child_path, false);
2280 new_entries.push(child_entry);
2281 };
2282 }
2283
2284 self.snapshot
2285 .lock()
2286 .populate_dir(job.path.clone(), new_entries, new_ignore);
2287 for new_job in new_jobs {
2288 job.scan_queue.send(new_job).await.unwrap();
2289 }
2290
2291 Ok(())
2292 }
2293
2294 async fn process_events(&mut self, mut events: Vec<fsevent::Event>) -> bool {
2295 events.sort_unstable_by(|a, b| a.path.cmp(&b.path));
2296 events.dedup_by(|a, b| a.path.starts_with(&b.path));
2297
2298 let root_char_bag;
2299 let root_abs_path;
2300 let next_entry_id;
2301 {
2302 let snapshot = self.snapshot.lock();
2303 root_char_bag = snapshot.root_char_bag;
2304 root_abs_path = snapshot.abs_path.clone();
2305 next_entry_id = snapshot.next_entry_id.clone();
2306 }
2307
2308 let root_abs_path = if let Ok(abs_path) = self.fs.canonicalize(&root_abs_path).await {
2309 abs_path
2310 } else {
2311 return false;
2312 };
2313 let metadata = futures::future::join_all(
2314 events
2315 .iter()
2316 .map(|event| self.fs.metadata(&event.path))
2317 .collect::<Vec<_>>(),
2318 )
2319 .await;
2320
2321 // Hold the snapshot lock while clearing and re-inserting the root entries
2322 // for each event. This way, the snapshot is not observable to the foreground
2323 // thread while this operation is in-progress.
2324 let (scan_queue_tx, scan_queue_rx) = channel::unbounded();
2325 {
2326 let mut snapshot = self.snapshot.lock();
2327 snapshot.scan_id += 1;
2328 for event in &events {
2329 if let Ok(path) = event.path.strip_prefix(&root_abs_path) {
2330 snapshot.remove_path(&path);
2331 }
2332 }
2333
2334 for (event, metadata) in events.into_iter().zip(metadata.into_iter()) {
2335 let path: Arc<Path> = match event.path.strip_prefix(&root_abs_path) {
2336 Ok(path) => Arc::from(path.to_path_buf()),
2337 Err(_) => {
2338 log::error!(
2339 "unexpected event {:?} for root path {:?}",
2340 event.path,
2341 root_abs_path
2342 );
2343 continue;
2344 }
2345 };
2346
2347 match metadata {
2348 Ok(Some(metadata)) => {
2349 let ignore_stack = snapshot.ignore_stack_for_path(&path, metadata.is_dir);
2350 let mut fs_entry = Entry::new(
2351 path.clone(),
2352 &metadata,
2353 snapshot.next_entry_id.as_ref(),
2354 snapshot.root_char_bag,
2355 );
2356 fs_entry.is_ignored = ignore_stack.is_all();
2357 snapshot.insert_entry(fs_entry, self.fs.as_ref());
2358 if metadata.is_dir {
2359 self.executor
2360 .block(scan_queue_tx.send(ScanJob {
2361 abs_path: event.path,
2362 path,
2363 ignore_stack,
2364 scan_queue: scan_queue_tx.clone(),
2365 }))
2366 .unwrap();
2367 }
2368 }
2369 Ok(None) => {}
2370 Err(err) => {
2371 // TODO - create a special 'error' entry in the entries tree to mark this
2372 log::error!("error reading file on event {:?}", err);
2373 }
2374 }
2375 }
2376 drop(scan_queue_tx);
2377 }
2378
2379 // Scan any directories that were created as part of this event batch.
2380 self.executor
2381 .scoped(|scope| {
2382 for _ in 0..self.executor.num_cpus() {
2383 scope.spawn(async {
2384 while let Ok(job) = scan_queue_rx.recv().await {
2385 if let Err(err) = self
2386 .scan_dir(root_char_bag, next_entry_id.clone(), &job)
2387 .await
2388 {
2389 log::error!("error scanning {:?}: {}", job.abs_path, err);
2390 }
2391 }
2392 });
2393 }
2394 })
2395 .await;
2396
2397 // Attempt to detect renames only over a single batch of file-system events.
2398 self.snapshot.lock().removed_entry_ids.clear();
2399
2400 self.update_ignore_statuses().await;
2401 true
2402 }
2403
2404 async fn update_ignore_statuses(&self) {
2405 let mut snapshot = self.snapshot();
2406
2407 let mut ignores_to_update = Vec::new();
2408 let mut ignores_to_delete = Vec::new();
2409 for (parent_path, (_, scan_id)) in &snapshot.ignores {
2410 if *scan_id == snapshot.scan_id && snapshot.entry_for_path(parent_path).is_some() {
2411 ignores_to_update.push(parent_path.clone());
2412 }
2413
2414 let ignore_path = parent_path.join(&*GITIGNORE);
2415 if snapshot.entry_for_path(ignore_path).is_none() {
2416 ignores_to_delete.push(parent_path.clone());
2417 }
2418 }
2419
2420 for parent_path in ignores_to_delete {
2421 snapshot.ignores.remove(&parent_path);
2422 self.snapshot.lock().ignores.remove(&parent_path);
2423 }
2424
2425 let (ignore_queue_tx, ignore_queue_rx) = channel::unbounded();
2426 ignores_to_update.sort_unstable();
2427 let mut ignores_to_update = ignores_to_update.into_iter().peekable();
2428 while let Some(parent_path) = ignores_to_update.next() {
2429 while ignores_to_update
2430 .peek()
2431 .map_or(false, |p| p.starts_with(&parent_path))
2432 {
2433 ignores_to_update.next().unwrap();
2434 }
2435
2436 let ignore_stack = snapshot.ignore_stack_for_path(&parent_path, true);
2437 ignore_queue_tx
2438 .send(UpdateIgnoreStatusJob {
2439 path: parent_path,
2440 ignore_stack,
2441 ignore_queue: ignore_queue_tx.clone(),
2442 })
2443 .await
2444 .unwrap();
2445 }
2446 drop(ignore_queue_tx);
2447
2448 self.executor
2449 .scoped(|scope| {
2450 for _ in 0..self.executor.num_cpus() {
2451 scope.spawn(async {
2452 while let Ok(job) = ignore_queue_rx.recv().await {
2453 self.update_ignore_status(job, &snapshot).await;
2454 }
2455 });
2456 }
2457 })
2458 .await;
2459 }
2460
2461 async fn update_ignore_status(&self, job: UpdateIgnoreStatusJob, snapshot: &LocalSnapshot) {
2462 let mut ignore_stack = job.ignore_stack;
2463 if let Some((ignore, _)) = snapshot.ignores.get(&job.path) {
2464 ignore_stack = ignore_stack.append(job.path.clone(), ignore.clone());
2465 }
2466
2467 let mut entries_by_id_edits = Vec::new();
2468 let mut entries_by_path_edits = Vec::new();
2469 for mut entry in snapshot.child_entries(&job.path).cloned() {
2470 let was_ignored = entry.is_ignored;
2471 entry.is_ignored = ignore_stack.is_path_ignored(&entry.path, entry.is_dir());
2472 if entry.is_dir() {
2473 let child_ignore_stack = if entry.is_ignored {
2474 IgnoreStack::all()
2475 } else {
2476 ignore_stack.clone()
2477 };
2478 job.ignore_queue
2479 .send(UpdateIgnoreStatusJob {
2480 path: entry.path.clone(),
2481 ignore_stack: child_ignore_stack,
2482 ignore_queue: job.ignore_queue.clone(),
2483 })
2484 .await
2485 .unwrap();
2486 }
2487
2488 if entry.is_ignored != was_ignored {
2489 let mut path_entry = snapshot.entries_by_id.get(&entry.id, &()).unwrap().clone();
2490 path_entry.scan_id = snapshot.scan_id;
2491 path_entry.is_ignored = entry.is_ignored;
2492 entries_by_id_edits.push(Edit::Insert(path_entry));
2493 entries_by_path_edits.push(Edit::Insert(entry));
2494 }
2495 }
2496
2497 let mut snapshot = self.snapshot.lock();
2498 snapshot.entries_by_path.edit(entries_by_path_edits, &());
2499 snapshot.entries_by_id.edit(entries_by_id_edits, &());
2500 }
2501}
2502
2503fn char_bag_for_path(root_char_bag: CharBag, path: &Path) -> CharBag {
2504 let mut result = root_char_bag;
2505 result.extend(
2506 path.to_string_lossy()
2507 .chars()
2508 .map(|c| c.to_ascii_lowercase()),
2509 );
2510 result
2511}
2512
2513struct ScanJob {
2514 abs_path: PathBuf,
2515 path: Arc<Path>,
2516 ignore_stack: Arc<IgnoreStack>,
2517 scan_queue: Sender<ScanJob>,
2518}
2519
2520struct UpdateIgnoreStatusJob {
2521 path: Arc<Path>,
2522 ignore_stack: Arc<IgnoreStack>,
2523 ignore_queue: Sender<UpdateIgnoreStatusJob>,
2524}
2525
2526pub trait WorktreeHandle {
2527 #[cfg(any(test, feature = "test-support"))]
2528 fn flush_fs_events<'a>(
2529 &self,
2530 cx: &'a gpui::TestAppContext,
2531 ) -> futures::future::LocalBoxFuture<'a, ()>;
2532}
2533
2534impl WorktreeHandle for ModelHandle<Worktree> {
2535 // When the worktree's FS event stream sometimes delivers "redundant" events for FS changes that
2536 // occurred before the worktree was constructed. These events can cause the worktree to perfrom
2537 // extra directory scans, and emit extra scan-state notifications.
2538 //
2539 // This function mutates the worktree's directory and waits for those mutations to be picked up,
2540 // to ensure that all redundant FS events have already been processed.
2541 #[cfg(any(test, feature = "test-support"))]
2542 fn flush_fs_events<'a>(
2543 &self,
2544 cx: &'a gpui::TestAppContext,
2545 ) -> futures::future::LocalBoxFuture<'a, ()> {
2546 use smol::future::FutureExt;
2547
2548 let filename = "fs-event-sentinel";
2549 let tree = self.clone();
2550 let (fs, root_path) = self.read_with(cx, |tree, _| {
2551 let tree = tree.as_local().unwrap();
2552 (tree.fs.clone(), tree.abs_path().clone())
2553 });
2554
2555 async move {
2556 fs.create_file(&root_path.join(filename), Default::default())
2557 .await
2558 .unwrap();
2559 tree.condition(&cx, |tree, _| tree.entry_for_path(filename).is_some())
2560 .await;
2561
2562 fs.remove_file(&root_path.join(filename), Default::default())
2563 .await
2564 .unwrap();
2565 tree.condition(&cx, |tree, _| tree.entry_for_path(filename).is_none())
2566 .await;
2567
2568 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2569 .await;
2570 }
2571 .boxed_local()
2572 }
2573}
2574
2575#[derive(Clone, Debug)]
2576struct TraversalProgress<'a> {
2577 max_path: &'a Path,
2578 count: usize,
2579 visible_count: usize,
2580 file_count: usize,
2581 visible_file_count: usize,
2582}
2583
2584impl<'a> TraversalProgress<'a> {
2585 fn count(&self, include_dirs: bool, include_ignored: bool) -> usize {
2586 match (include_ignored, include_dirs) {
2587 (true, true) => self.count,
2588 (true, false) => self.file_count,
2589 (false, true) => self.visible_count,
2590 (false, false) => self.visible_file_count,
2591 }
2592 }
2593}
2594
2595impl<'a> sum_tree::Dimension<'a, EntrySummary> for TraversalProgress<'a> {
2596 fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
2597 self.max_path = summary.max_path.as_ref();
2598 self.count += summary.count;
2599 self.visible_count += summary.visible_count;
2600 self.file_count += summary.file_count;
2601 self.visible_file_count += summary.visible_file_count;
2602 }
2603}
2604
2605impl<'a> Default for TraversalProgress<'a> {
2606 fn default() -> Self {
2607 Self {
2608 max_path: Path::new(""),
2609 count: 0,
2610 visible_count: 0,
2611 file_count: 0,
2612 visible_file_count: 0,
2613 }
2614 }
2615}
2616
2617pub struct Traversal<'a> {
2618 cursor: sum_tree::Cursor<'a, Entry, TraversalProgress<'a>>,
2619 include_ignored: bool,
2620 include_dirs: bool,
2621}
2622
2623impl<'a> Traversal<'a> {
2624 pub fn advance(&mut self) -> bool {
2625 self.advance_to_offset(self.offset() + 1)
2626 }
2627
2628 pub fn advance_to_offset(&mut self, offset: usize) -> bool {
2629 self.cursor.seek_forward(
2630 &TraversalTarget::Count {
2631 count: offset,
2632 include_dirs: self.include_dirs,
2633 include_ignored: self.include_ignored,
2634 },
2635 Bias::Right,
2636 &(),
2637 )
2638 }
2639
2640 pub fn advance_to_sibling(&mut self) -> bool {
2641 while let Some(entry) = self.cursor.item() {
2642 self.cursor.seek_forward(
2643 &TraversalTarget::PathSuccessor(&entry.path),
2644 Bias::Left,
2645 &(),
2646 );
2647 if let Some(entry) = self.cursor.item() {
2648 if (self.include_dirs || !entry.is_dir())
2649 && (self.include_ignored || !entry.is_ignored)
2650 {
2651 return true;
2652 }
2653 }
2654 }
2655 false
2656 }
2657
2658 pub fn entry(&self) -> Option<&'a Entry> {
2659 self.cursor.item()
2660 }
2661
2662 pub fn offset(&self) -> usize {
2663 self.cursor
2664 .start()
2665 .count(self.include_dirs, self.include_ignored)
2666 }
2667}
2668
2669impl<'a> Iterator for Traversal<'a> {
2670 type Item = &'a Entry;
2671
2672 fn next(&mut self) -> Option<Self::Item> {
2673 if let Some(item) = self.entry() {
2674 self.advance();
2675 Some(item)
2676 } else {
2677 None
2678 }
2679 }
2680}
2681
2682#[derive(Debug)]
2683enum TraversalTarget<'a> {
2684 Path(&'a Path),
2685 PathSuccessor(&'a Path),
2686 Count {
2687 count: usize,
2688 include_ignored: bool,
2689 include_dirs: bool,
2690 },
2691}
2692
2693impl<'a, 'b> SeekTarget<'a, EntrySummary, TraversalProgress<'a>> for TraversalTarget<'b> {
2694 fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: &()) -> Ordering {
2695 match self {
2696 TraversalTarget::Path(path) => path.cmp(&cursor_location.max_path),
2697 TraversalTarget::PathSuccessor(path) => {
2698 if !cursor_location.max_path.starts_with(path) {
2699 Ordering::Equal
2700 } else {
2701 Ordering::Greater
2702 }
2703 }
2704 TraversalTarget::Count {
2705 count,
2706 include_dirs,
2707 include_ignored,
2708 } => Ord::cmp(
2709 count,
2710 &cursor_location.count(*include_dirs, *include_ignored),
2711 ),
2712 }
2713 }
2714}
2715
2716struct ChildEntriesIter<'a> {
2717 parent_path: &'a Path,
2718 traversal: Traversal<'a>,
2719}
2720
2721impl<'a> Iterator for ChildEntriesIter<'a> {
2722 type Item = &'a Entry;
2723
2724 fn next(&mut self) -> Option<Self::Item> {
2725 if let Some(item) = self.traversal.entry() {
2726 if item.path.starts_with(&self.parent_path) {
2727 self.traversal.advance_to_sibling();
2728 return Some(item);
2729 }
2730 }
2731 None
2732 }
2733}
2734
2735impl<'a> From<&'a Entry> for proto::Entry {
2736 fn from(entry: &'a Entry) -> Self {
2737 Self {
2738 id: entry.id.to_proto(),
2739 is_dir: entry.is_dir(),
2740 path: entry.path.as_os_str().as_bytes().to_vec(),
2741 inode: entry.inode,
2742 mtime: Some(entry.mtime.into()),
2743 is_symlink: entry.is_symlink,
2744 is_ignored: entry.is_ignored,
2745 }
2746 }
2747}
2748
2749impl<'a> TryFrom<(&'a CharBag, proto::Entry)> for Entry {
2750 type Error = anyhow::Error;
2751
2752 fn try_from((root_char_bag, entry): (&'a CharBag, proto::Entry)) -> Result<Self> {
2753 if let Some(mtime) = entry.mtime {
2754 let kind = if entry.is_dir {
2755 EntryKind::Dir
2756 } else {
2757 let mut char_bag = root_char_bag.clone();
2758 char_bag.extend(
2759 String::from_utf8_lossy(&entry.path)
2760 .chars()
2761 .map(|c| c.to_ascii_lowercase()),
2762 );
2763 EntryKind::File(char_bag)
2764 };
2765 let path: Arc<Path> = PathBuf::from(OsString::from_vec(entry.path)).into();
2766 Ok(Entry {
2767 id: ProjectEntryId::from_proto(entry.id),
2768 kind,
2769 path: path.clone(),
2770 inode: entry.inode,
2771 mtime: mtime.into(),
2772 is_symlink: entry.is_symlink,
2773 is_ignored: entry.is_ignored,
2774 })
2775 } else {
2776 Err(anyhow!(
2777 "missing mtime in remote worktree entry {:?}",
2778 entry.path
2779 ))
2780 }
2781 }
2782}
2783
2784#[cfg(test)]
2785mod tests {
2786 use super::*;
2787 use crate::fs::FakeFs;
2788 use anyhow::Result;
2789 use client::test::FakeHttpClient;
2790 use fs::RealFs;
2791 use gpui::TestAppContext;
2792 use rand::prelude::*;
2793 use serde_json::json;
2794 use std::{
2795 env,
2796 fmt::Write,
2797 time::{SystemTime, UNIX_EPOCH},
2798 };
2799 use util::test::temp_tree;
2800
2801 #[gpui::test]
2802 async fn test_traversal(cx: &mut TestAppContext) {
2803 let fs = FakeFs::new(cx.background());
2804 fs.insert_tree(
2805 "/root",
2806 json!({
2807 ".gitignore": "a/b\n",
2808 "a": {
2809 "b": "",
2810 "c": "",
2811 }
2812 }),
2813 )
2814 .await;
2815
2816 let http_client = FakeHttpClient::with_404_response();
2817 let client = Client::new(http_client);
2818
2819 let tree = Worktree::local(
2820 client,
2821 Arc::from(Path::new("/root")),
2822 true,
2823 fs,
2824 Default::default(),
2825 &mut cx.to_async(),
2826 )
2827 .await
2828 .unwrap();
2829 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2830 .await;
2831
2832 tree.read_with(cx, |tree, _| {
2833 assert_eq!(
2834 tree.entries(false)
2835 .map(|entry| entry.path.as_ref())
2836 .collect::<Vec<_>>(),
2837 vec![
2838 Path::new(""),
2839 Path::new(".gitignore"),
2840 Path::new("a"),
2841 Path::new("a/c"),
2842 ]
2843 );
2844 assert_eq!(
2845 tree.entries(true)
2846 .map(|entry| entry.path.as_ref())
2847 .collect::<Vec<_>>(),
2848 vec![
2849 Path::new(""),
2850 Path::new(".gitignore"),
2851 Path::new("a"),
2852 Path::new("a/b"),
2853 Path::new("a/c"),
2854 ]
2855 );
2856 })
2857 }
2858
2859 #[gpui::test]
2860 async fn test_rescan_with_gitignore(cx: &mut TestAppContext) {
2861 let dir = temp_tree(json!({
2862 ".git": {},
2863 ".gitignore": "ignored-dir\n",
2864 "tracked-dir": {
2865 "tracked-file1": "tracked contents",
2866 },
2867 "ignored-dir": {
2868 "ignored-file1": "ignored contents",
2869 }
2870 }));
2871
2872 let http_client = FakeHttpClient::with_404_response();
2873 let client = Client::new(http_client.clone());
2874
2875 let tree = Worktree::local(
2876 client,
2877 dir.path(),
2878 true,
2879 Arc::new(RealFs),
2880 Default::default(),
2881 &mut cx.to_async(),
2882 )
2883 .await
2884 .unwrap();
2885 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2886 .await;
2887 tree.flush_fs_events(&cx).await;
2888 cx.read(|cx| {
2889 let tree = tree.read(cx);
2890 let tracked = tree.entry_for_path("tracked-dir/tracked-file1").unwrap();
2891 let ignored = tree.entry_for_path("ignored-dir/ignored-file1").unwrap();
2892 assert_eq!(tracked.is_ignored, false);
2893 assert_eq!(ignored.is_ignored, true);
2894 });
2895
2896 std::fs::write(dir.path().join("tracked-dir/tracked-file2"), "").unwrap();
2897 std::fs::write(dir.path().join("ignored-dir/ignored-file2"), "").unwrap();
2898 tree.flush_fs_events(&cx).await;
2899 cx.read(|cx| {
2900 let tree = tree.read(cx);
2901 let dot_git = tree.entry_for_path(".git").unwrap();
2902 let tracked = tree.entry_for_path("tracked-dir/tracked-file2").unwrap();
2903 let ignored = tree.entry_for_path("ignored-dir/ignored-file2").unwrap();
2904 assert_eq!(tracked.is_ignored, false);
2905 assert_eq!(ignored.is_ignored, true);
2906 assert_eq!(dot_git.is_ignored, true);
2907 });
2908 }
2909
2910 #[gpui::test]
2911 async fn test_write_file(cx: &mut TestAppContext) {
2912 let dir = temp_tree(json!({
2913 ".git": {},
2914 ".gitignore": "ignored-dir\n",
2915 "tracked-dir": {},
2916 "ignored-dir": {}
2917 }));
2918
2919 let http_client = FakeHttpClient::with_404_response();
2920 let client = Client::new(http_client.clone());
2921
2922 let tree = Worktree::local(
2923 client,
2924 dir.path(),
2925 true,
2926 Arc::new(RealFs),
2927 Default::default(),
2928 &mut cx.to_async(),
2929 )
2930 .await
2931 .unwrap();
2932 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2933 .await;
2934 tree.flush_fs_events(&cx).await;
2935
2936 tree.update(cx, |tree, cx| {
2937 tree.as_local().unwrap().write_file(
2938 Path::new("tracked-dir/file.txt"),
2939 "hello".into(),
2940 cx,
2941 )
2942 })
2943 .await
2944 .unwrap();
2945 tree.update(cx, |tree, cx| {
2946 tree.as_local().unwrap().write_file(
2947 Path::new("ignored-dir/file.txt"),
2948 "world".into(),
2949 cx,
2950 )
2951 })
2952 .await
2953 .unwrap();
2954
2955 tree.read_with(cx, |tree, _| {
2956 let tracked = tree.entry_for_path("tracked-dir/file.txt").unwrap();
2957 let ignored = tree.entry_for_path("ignored-dir/file.txt").unwrap();
2958 assert_eq!(tracked.is_ignored, false);
2959 assert_eq!(ignored.is_ignored, true);
2960 });
2961 }
2962
2963 #[gpui::test(iterations = 100)]
2964 fn test_random(mut rng: StdRng) {
2965 let operations = env::var("OPERATIONS")
2966 .map(|o| o.parse().unwrap())
2967 .unwrap_or(40);
2968 let initial_entries = env::var("INITIAL_ENTRIES")
2969 .map(|o| o.parse().unwrap())
2970 .unwrap_or(20);
2971
2972 let root_dir = tempdir::TempDir::new("worktree-test").unwrap();
2973 for _ in 0..initial_entries {
2974 randomly_mutate_tree(root_dir.path(), 1.0, &mut rng).unwrap();
2975 }
2976 log::info!("Generated initial tree");
2977
2978 let (notify_tx, _notify_rx) = mpsc::unbounded();
2979 let fs = Arc::new(RealFs);
2980 let next_entry_id = Arc::new(AtomicUsize::new(0));
2981 let mut initial_snapshot = LocalSnapshot {
2982 abs_path: root_dir.path().into(),
2983 removed_entry_ids: Default::default(),
2984 ignores: Default::default(),
2985 next_entry_id: next_entry_id.clone(),
2986 snapshot: Snapshot {
2987 id: WorktreeId::from_usize(0),
2988 entries_by_path: Default::default(),
2989 entries_by_id: Default::default(),
2990 root_name: Default::default(),
2991 root_char_bag: Default::default(),
2992 scan_id: 0,
2993 },
2994 extension_counts: Default::default(),
2995 };
2996 initial_snapshot.insert_entry(
2997 Entry::new(
2998 Path::new("").into(),
2999 &smol::block_on(fs.metadata(root_dir.path()))
3000 .unwrap()
3001 .unwrap(),
3002 &next_entry_id,
3003 Default::default(),
3004 ),
3005 fs.as_ref(),
3006 );
3007 let mut scanner = BackgroundScanner::new(
3008 Arc::new(Mutex::new(initial_snapshot.clone())),
3009 notify_tx,
3010 fs.clone(),
3011 Arc::new(gpui::executor::Background::new()),
3012 );
3013 smol::block_on(scanner.scan_dirs()).unwrap();
3014 scanner.snapshot().check_invariants();
3015
3016 let mut events = Vec::new();
3017 let mut snapshots = Vec::new();
3018 let mut mutations_len = operations;
3019 while mutations_len > 1 {
3020 if !events.is_empty() && rng.gen_bool(0.4) {
3021 let len = rng.gen_range(0..=events.len());
3022 let to_deliver = events.drain(0..len).collect::<Vec<_>>();
3023 log::info!("Delivering events: {:#?}", to_deliver);
3024 smol::block_on(scanner.process_events(to_deliver));
3025 scanner.snapshot().check_invariants();
3026 } else {
3027 events.extend(randomly_mutate_tree(root_dir.path(), 0.6, &mut rng).unwrap());
3028 mutations_len -= 1;
3029 }
3030
3031 if rng.gen_bool(0.2) {
3032 snapshots.push(scanner.snapshot());
3033 }
3034 }
3035 log::info!("Quiescing: {:#?}", events);
3036 smol::block_on(scanner.process_events(events));
3037 scanner.snapshot().check_invariants();
3038
3039 let (notify_tx, _notify_rx) = mpsc::unbounded();
3040 let mut new_scanner = BackgroundScanner::new(
3041 Arc::new(Mutex::new(initial_snapshot)),
3042 notify_tx,
3043 scanner.fs.clone(),
3044 scanner.executor.clone(),
3045 );
3046 smol::block_on(new_scanner.scan_dirs()).unwrap();
3047 assert_eq!(
3048 scanner.snapshot().to_vec(true),
3049 new_scanner.snapshot().to_vec(true)
3050 );
3051
3052 for mut prev_snapshot in snapshots {
3053 let include_ignored = rng.gen::<bool>();
3054 if !include_ignored {
3055 let mut entries_by_path_edits = Vec::new();
3056 let mut entries_by_id_edits = Vec::new();
3057 for entry in prev_snapshot
3058 .entries_by_id
3059 .cursor::<()>()
3060 .filter(|e| e.is_ignored)
3061 {
3062 entries_by_path_edits.push(Edit::Remove(PathKey(entry.path.clone())));
3063 entries_by_id_edits.push(Edit::Remove(entry.id));
3064 }
3065
3066 prev_snapshot
3067 .entries_by_path
3068 .edit(entries_by_path_edits, &());
3069 prev_snapshot.entries_by_id.edit(entries_by_id_edits, &());
3070 }
3071
3072 let update = scanner
3073 .snapshot()
3074 .build_update(&prev_snapshot, 0, 0, include_ignored);
3075 prev_snapshot.apply_remote_update(update).unwrap();
3076 assert_eq!(
3077 prev_snapshot.to_vec(true),
3078 scanner.snapshot().to_vec(include_ignored)
3079 );
3080 }
3081 }
3082
3083 fn randomly_mutate_tree(
3084 root_path: &Path,
3085 insertion_probability: f64,
3086 rng: &mut impl Rng,
3087 ) -> Result<Vec<fsevent::Event>> {
3088 let root_path = root_path.canonicalize().unwrap();
3089 let (dirs, files) = read_dir_recursive(root_path.clone());
3090
3091 let mut events = Vec::new();
3092 let mut record_event = |path: PathBuf| {
3093 events.push(fsevent::Event {
3094 event_id: SystemTime::now()
3095 .duration_since(UNIX_EPOCH)
3096 .unwrap()
3097 .as_secs(),
3098 flags: fsevent::StreamFlags::empty(),
3099 path,
3100 });
3101 };
3102
3103 if (files.is_empty() && dirs.len() == 1) || rng.gen_bool(insertion_probability) {
3104 let path = dirs.choose(rng).unwrap();
3105 let new_path = path.join(gen_name(rng));
3106
3107 if rng.gen() {
3108 log::info!("Creating dir {:?}", new_path.strip_prefix(root_path)?);
3109 std::fs::create_dir(&new_path)?;
3110 } else {
3111 log::info!("Creating file {:?}", new_path.strip_prefix(root_path)?);
3112 std::fs::write(&new_path, "")?;
3113 }
3114 record_event(new_path);
3115 } else if rng.gen_bool(0.05) {
3116 let ignore_dir_path = dirs.choose(rng).unwrap();
3117 let ignore_path = ignore_dir_path.join(&*GITIGNORE);
3118
3119 let (subdirs, subfiles) = read_dir_recursive(ignore_dir_path.clone());
3120 let files_to_ignore = {
3121 let len = rng.gen_range(0..=subfiles.len());
3122 subfiles.choose_multiple(rng, len)
3123 };
3124 let dirs_to_ignore = {
3125 let len = rng.gen_range(0..subdirs.len());
3126 subdirs.choose_multiple(rng, len)
3127 };
3128
3129 let mut ignore_contents = String::new();
3130 for path_to_ignore in files_to_ignore.chain(dirs_to_ignore) {
3131 write!(
3132 ignore_contents,
3133 "{}\n",
3134 path_to_ignore
3135 .strip_prefix(&ignore_dir_path)?
3136 .to_str()
3137 .unwrap()
3138 )
3139 .unwrap();
3140 }
3141 log::info!(
3142 "Creating {:?} with contents:\n{}",
3143 ignore_path.strip_prefix(&root_path)?,
3144 ignore_contents
3145 );
3146 std::fs::write(&ignore_path, ignore_contents).unwrap();
3147 record_event(ignore_path);
3148 } else {
3149 let old_path = {
3150 let file_path = files.choose(rng);
3151 let dir_path = dirs[1..].choose(rng);
3152 file_path.into_iter().chain(dir_path).choose(rng).unwrap()
3153 };
3154
3155 let is_rename = rng.gen();
3156 if is_rename {
3157 let new_path_parent = dirs
3158 .iter()
3159 .filter(|d| !d.starts_with(old_path))
3160 .choose(rng)
3161 .unwrap();
3162
3163 let overwrite_existing_dir =
3164 !old_path.starts_with(&new_path_parent) && rng.gen_bool(0.3);
3165 let new_path = if overwrite_existing_dir {
3166 std::fs::remove_dir_all(&new_path_parent).ok();
3167 new_path_parent.to_path_buf()
3168 } else {
3169 new_path_parent.join(gen_name(rng))
3170 };
3171
3172 log::info!(
3173 "Renaming {:?} to {}{:?}",
3174 old_path.strip_prefix(&root_path)?,
3175 if overwrite_existing_dir {
3176 "overwrite "
3177 } else {
3178 ""
3179 },
3180 new_path.strip_prefix(&root_path)?
3181 );
3182 std::fs::rename(&old_path, &new_path)?;
3183 record_event(old_path.clone());
3184 record_event(new_path);
3185 } else if old_path.is_dir() {
3186 let (dirs, files) = read_dir_recursive(old_path.clone());
3187
3188 log::info!("Deleting dir {:?}", old_path.strip_prefix(&root_path)?);
3189 std::fs::remove_dir_all(&old_path).unwrap();
3190 for file in files {
3191 record_event(file);
3192 }
3193 for dir in dirs {
3194 record_event(dir);
3195 }
3196 } else {
3197 log::info!("Deleting file {:?}", old_path.strip_prefix(&root_path)?);
3198 std::fs::remove_file(old_path).unwrap();
3199 record_event(old_path.clone());
3200 }
3201 }
3202
3203 Ok(events)
3204 }
3205
3206 fn read_dir_recursive(path: PathBuf) -> (Vec<PathBuf>, Vec<PathBuf>) {
3207 let child_entries = std::fs::read_dir(&path).unwrap();
3208 let mut dirs = vec![path];
3209 let mut files = Vec::new();
3210 for child_entry in child_entries {
3211 let child_path = child_entry.unwrap().path();
3212 if child_path.is_dir() {
3213 let (child_dirs, child_files) = read_dir_recursive(child_path);
3214 dirs.extend(child_dirs);
3215 files.extend(child_files);
3216 } else {
3217 files.push(child_path);
3218 }
3219 }
3220 (dirs, files)
3221 }
3222
3223 fn gen_name(rng: &mut impl Rng) -> String {
3224 (0..6)
3225 .map(|_| rng.sample(rand::distributions::Alphanumeric))
3226 .map(char::from)
3227 .collect()
3228 }
3229
3230 impl LocalSnapshot {
3231 fn check_invariants(&self) {
3232 let mut files = self.files(true, 0);
3233 let mut visible_files = self.files(false, 0);
3234 for entry in self.entries_by_path.cursor::<()>() {
3235 if entry.is_file() {
3236 assert_eq!(files.next().unwrap().inode, entry.inode);
3237 if !entry.is_ignored {
3238 assert_eq!(visible_files.next().unwrap().inode, entry.inode);
3239 }
3240 }
3241 }
3242 assert!(files.next().is_none());
3243 assert!(visible_files.next().is_none());
3244
3245 let mut bfs_paths = Vec::new();
3246 let mut stack = vec![Path::new("")];
3247 while let Some(path) = stack.pop() {
3248 bfs_paths.push(path);
3249 let ix = stack.len();
3250 for child_entry in self.child_entries(path) {
3251 stack.insert(ix, &child_entry.path);
3252 }
3253 }
3254
3255 let dfs_paths_via_iter = self
3256 .entries_by_path
3257 .cursor::<()>()
3258 .map(|e| e.path.as_ref())
3259 .collect::<Vec<_>>();
3260 assert_eq!(bfs_paths, dfs_paths_via_iter);
3261
3262 let dfs_paths_via_traversal = self
3263 .entries(true)
3264 .map(|e| e.path.as_ref())
3265 .collect::<Vec<_>>();
3266 assert_eq!(dfs_paths_via_traversal, dfs_paths_via_iter);
3267
3268 for (ignore_parent_path, _) in &self.ignores {
3269 assert!(self.entry_for_path(ignore_parent_path).is_some());
3270 assert!(self
3271 .entry_for_path(ignore_parent_path.join(&*GITIGNORE))
3272 .is_some());
3273 }
3274
3275 // Ensure extension counts are correct.
3276 let mut expected_extension_counts = HashMap::default();
3277 for extension in self.entries(false).filter_map(|e| e.path.extension()) {
3278 *expected_extension_counts
3279 .entry(extension.into())
3280 .or_insert(0) += 1;
3281 }
3282 assert_eq!(self.extension_counts, expected_extension_counts);
3283 }
3284
3285 fn to_vec(&self, include_ignored: bool) -> Vec<(&Path, u64, bool)> {
3286 let mut paths = Vec::new();
3287 for entry in self.entries_by_path.cursor::<()>() {
3288 if include_ignored || !entry.is_ignored {
3289 paths.push((entry.path.as_ref(), entry.inode, entry.is_ignored));
3290 }
3291 }
3292 paths.sort_by(|a, b| a.0.cmp(&b.0));
3293 paths
3294 }
3295 }
3296}