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