1use super::{
2 fs::{self, Fs},
3 ignore::IgnoreStack,
4 DiagnosticSummary,
5};
6use ::ignore::gitignore::{Gitignore, GitignoreBuilder};
7use anyhow::{anyhow, Context, Result};
8use client::{proto, Client, PeerId, TypedEnvelope, UserStore};
9use clock::ReplicaId;
10use collections::{hash_map, HashMap, HashSet};
11use futures::{Stream, StreamExt};
12use fuzzy::CharBag;
13use gpui::{
14 executor, AppContext, AsyncAppContext, Entity, ModelContext, ModelHandle, MutableAppContext,
15 Task, UpgradeModelHandle, WeakModelHandle,
16};
17use language::{
18 Buffer, Diagnostic, DiagnosticEntry, DiagnosticSeverity, File as _, Language, LanguageRegistry,
19 Operation, PointUtf16, Rope,
20};
21use lazy_static::lazy_static;
22use lsp::LanguageServer;
23use parking_lot::Mutex;
24use postage::{
25 prelude::{Sink as _, Stream as _},
26 watch,
27};
28use serde::Deserialize;
29use smol::channel::{self, Sender};
30use std::{
31 any::Any,
32 cmp::{self, Ordering},
33 convert::{TryFrom, TryInto},
34 ffi::{OsStr, OsString},
35 fmt,
36 future::Future,
37 mem,
38 ops::{Deref, Range},
39 path::{Path, PathBuf},
40 sync::{
41 atomic::{AtomicUsize, Ordering::SeqCst},
42 Arc,
43 },
44 time::{Duration, SystemTime},
45};
46use sum_tree::{Bias, TreeMap};
47use sum_tree::{Edit, SeekTarget, SumTree};
48use util::{post_inc, ResultExt, TryFutureExt};
49
50lazy_static! {
51 static ref GITIGNORE: &'static OsStr = OsStr::new(".gitignore");
52}
53
54#[derive(Clone, Debug)]
55enum ScanState {
56 Idle,
57 Scanning,
58 Err(Arc<anyhow::Error>),
59}
60
61#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
62pub struct WorktreeId(usize);
63
64pub enum Worktree {
65 Local(LocalWorktree),
66 Remote(RemoteWorktree),
67}
68
69#[derive(Clone, Debug, Eq, PartialEq)]
70pub enum Event {
71 DiskBasedDiagnosticsUpdated,
72 DiagnosticsUpdated(Arc<Path>),
73}
74
75impl Entity for Worktree {
76 type Event = Event;
77
78 fn app_will_quit(
79 &mut self,
80 _: &mut MutableAppContext,
81 ) -> Option<std::pin::Pin<Box<dyn 'static + Future<Output = ()>>>> {
82 use futures::FutureExt;
83
84 if let Self::Local(worktree) = self {
85 let shutdown_futures = worktree
86 .language_servers
87 .drain()
88 .filter_map(|(_, server)| server.shutdown())
89 .collect::<Vec<_>>();
90 Some(
91 async move {
92 futures::future::join_all(shutdown_futures).await;
93 }
94 .boxed(),
95 )
96 } else {
97 None
98 }
99 }
100}
101
102impl Worktree {
103 pub async fn open_local(
104 client: Arc<Client>,
105 user_store: ModelHandle<UserStore>,
106 path: impl Into<Arc<Path>>,
107 fs: Arc<dyn Fs>,
108 languages: Arc<LanguageRegistry>,
109 cx: &mut AsyncAppContext,
110 ) -> Result<ModelHandle<Self>> {
111 let (tree, scan_states_tx) =
112 LocalWorktree::new(client, user_store, path, fs.clone(), languages, cx).await?;
113 tree.update(cx, |tree, cx| {
114 let tree = tree.as_local_mut().unwrap();
115 let abs_path = tree.snapshot.abs_path.clone();
116 let background_snapshot = tree.background_snapshot.clone();
117 let background = cx.background().clone();
118 tree._background_scanner_task = Some(cx.background().spawn(async move {
119 let events = fs.watch(&abs_path, Duration::from_millis(100)).await;
120 let scanner =
121 BackgroundScanner::new(background_snapshot, scan_states_tx, fs, background);
122 scanner.run(events).await;
123 }));
124 });
125 Ok(tree)
126 }
127
128 pub async fn remote(
129 project_remote_id: u64,
130 replica_id: ReplicaId,
131 worktree: proto::Worktree,
132 client: Arc<Client>,
133 user_store: ModelHandle<UserStore>,
134 languages: Arc<LanguageRegistry>,
135 cx: &mut AsyncAppContext,
136 ) -> Result<ModelHandle<Self>> {
137 let remote_id = worktree.id;
138 let root_char_bag: CharBag = worktree
139 .root_name
140 .chars()
141 .map(|c| c.to_ascii_lowercase())
142 .collect();
143 let root_name = worktree.root_name.clone();
144 let (entries_by_path, entries_by_id, diagnostic_summaries) = cx
145 .background()
146 .spawn(async move {
147 let mut entries_by_path_edits = Vec::new();
148 let mut entries_by_id_edits = Vec::new();
149 for entry in worktree.entries {
150 match Entry::try_from((&root_char_bag, entry)) {
151 Ok(entry) => {
152 entries_by_id_edits.push(Edit::Insert(PathEntry {
153 id: entry.id,
154 path: entry.path.clone(),
155 is_ignored: entry.is_ignored,
156 scan_id: 0,
157 }));
158 entries_by_path_edits.push(Edit::Insert(entry));
159 }
160 Err(err) => log::warn!("error for remote worktree entry {:?}", err),
161 }
162 }
163
164 let mut entries_by_path = SumTree::new();
165 let mut entries_by_id = SumTree::new();
166 entries_by_path.edit(entries_by_path_edits, &());
167 entries_by_id.edit(entries_by_id_edits, &());
168
169 let diagnostic_summaries = TreeMap::from_ordered_entries(
170 worktree.diagnostic_summaries.into_iter().map(|summary| {
171 (
172 PathKey(PathBuf::from(summary.path).into()),
173 DiagnosticSummary {
174 error_count: summary.error_count as usize,
175 warning_count: summary.warning_count as usize,
176 info_count: summary.info_count as usize,
177 hint_count: summary.hint_count as usize,
178 },
179 )
180 }),
181 );
182
183 (entries_by_path, entries_by_id, diagnostic_summaries)
184 })
185 .await;
186
187 let worktree = cx.update(|cx| {
188 cx.add_model(|cx: &mut ModelContext<Worktree>| {
189 let snapshot = Snapshot {
190 id: WorktreeId(remote_id as usize),
191 scan_id: 0,
192 abs_path: Path::new("").into(),
193 root_name,
194 root_char_bag,
195 ignores: Default::default(),
196 entries_by_path,
197 entries_by_id,
198 removed_entry_ids: Default::default(),
199 next_entry_id: Default::default(),
200 diagnostic_summaries,
201 };
202
203 let (updates_tx, mut updates_rx) = postage::mpsc::channel(64);
204 let (mut snapshot_tx, snapshot_rx) = watch::channel_with(snapshot.clone());
205
206 cx.background()
207 .spawn(async move {
208 while let Some(update) = updates_rx.recv().await {
209 let mut snapshot = snapshot_tx.borrow().clone();
210 if let Err(error) = snapshot.apply_update(update) {
211 log::error!("error applying worktree update: {}", error);
212 }
213 *snapshot_tx.borrow_mut() = snapshot;
214 }
215 })
216 .detach();
217
218 {
219 let mut snapshot_rx = snapshot_rx.clone();
220 cx.spawn_weak(|this, mut cx| async move {
221 while let Some(_) = snapshot_rx.recv().await {
222 if let Some(this) = cx.read(|cx| this.upgrade(cx)) {
223 this.update(&mut cx, |this, cx| this.poll_snapshot(cx));
224 } else {
225 break;
226 }
227 }
228 })
229 .detach();
230 }
231
232 Worktree::Remote(RemoteWorktree {
233 project_id: project_remote_id,
234 replica_id,
235 snapshot,
236 snapshot_rx,
237 updates_tx,
238 client: client.clone(),
239 loading_buffers: Default::default(),
240 open_buffers: Default::default(),
241 queued_operations: Default::default(),
242 languages,
243 user_store,
244 })
245 })
246 });
247
248 Ok(worktree)
249 }
250
251 pub fn as_local(&self) -> Option<&LocalWorktree> {
252 if let Worktree::Local(worktree) = self {
253 Some(worktree)
254 } else {
255 None
256 }
257 }
258
259 pub fn as_remote(&self) -> Option<&RemoteWorktree> {
260 if let Worktree::Remote(worktree) = self {
261 Some(worktree)
262 } else {
263 None
264 }
265 }
266
267 pub fn as_local_mut(&mut self) -> Option<&mut LocalWorktree> {
268 if let Worktree::Local(worktree) = self {
269 Some(worktree)
270 } else {
271 None
272 }
273 }
274
275 pub fn as_remote_mut(&mut self) -> Option<&mut RemoteWorktree> {
276 if let Worktree::Remote(worktree) = self {
277 Some(worktree)
278 } else {
279 None
280 }
281 }
282
283 pub fn snapshot(&self) -> Snapshot {
284 match self {
285 Worktree::Local(worktree) => worktree.snapshot(),
286 Worktree::Remote(worktree) => worktree.snapshot(),
287 }
288 }
289
290 pub fn replica_id(&self) -> ReplicaId {
291 match self {
292 Worktree::Local(_) => 0,
293 Worktree::Remote(worktree) => worktree.replica_id,
294 }
295 }
296
297 pub fn remove_collaborator(
298 &mut self,
299 peer_id: PeerId,
300 replica_id: ReplicaId,
301 cx: &mut ModelContext<Self>,
302 ) {
303 match self {
304 Worktree::Local(worktree) => worktree.remove_collaborator(peer_id, replica_id, cx),
305 Worktree::Remote(worktree) => worktree.remove_collaborator(replica_id, cx),
306 }
307 }
308
309 pub fn languages(&self) -> &Arc<LanguageRegistry> {
310 match self {
311 Worktree::Local(worktree) => &worktree.language_registry,
312 Worktree::Remote(worktree) => &worktree.languages,
313 }
314 }
315
316 pub fn user_store(&self) -> &ModelHandle<UserStore> {
317 match self {
318 Worktree::Local(worktree) => &worktree.user_store,
319 Worktree::Remote(worktree) => &worktree.user_store,
320 }
321 }
322
323 pub fn handle_open_buffer(
324 &mut self,
325 envelope: TypedEnvelope<proto::OpenBuffer>,
326 rpc: Arc<Client>,
327 cx: &mut ModelContext<Self>,
328 ) -> anyhow::Result<()> {
329 let receipt = envelope.receipt();
330
331 let response = self
332 .as_local_mut()
333 .unwrap()
334 .open_remote_buffer(envelope, cx);
335
336 cx.background()
337 .spawn(
338 async move {
339 rpc.respond(receipt, response.await?).await?;
340 Ok(())
341 }
342 .log_err(),
343 )
344 .detach();
345
346 Ok(())
347 }
348
349 pub fn handle_close_buffer(
350 &mut self,
351 envelope: TypedEnvelope<proto::CloseBuffer>,
352 _: Arc<Client>,
353 cx: &mut ModelContext<Self>,
354 ) -> anyhow::Result<()> {
355 self.as_local_mut()
356 .unwrap()
357 .close_remote_buffer(envelope, cx)
358 }
359
360 pub fn diagnostic_summaries<'a>(
361 &'a self,
362 ) -> impl Iterator<Item = (Arc<Path>, DiagnosticSummary)> + 'a {
363 match self {
364 Worktree::Local(worktree) => &worktree.diagnostic_summaries,
365 Worktree::Remote(worktree) => &worktree.diagnostic_summaries,
366 }
367 .iter()
368 .map(|(path, summary)| (path.0.clone(), summary.clone()))
369 }
370
371 pub fn loading_buffers<'a>(&'a mut self) -> &'a mut LoadingBuffers {
372 match self {
373 Worktree::Local(worktree) => &mut worktree.loading_buffers,
374 Worktree::Remote(worktree) => &mut worktree.loading_buffers,
375 }
376 }
377
378 pub fn open_buffer(
379 &mut self,
380 path: impl AsRef<Path>,
381 cx: &mut ModelContext<Self>,
382 ) -> Task<Result<ModelHandle<Buffer>>> {
383 let path = path.as_ref();
384
385 // If there is already a buffer for the given path, then return it.
386 let existing_buffer = match self {
387 Worktree::Local(worktree) => worktree.get_open_buffer(path, cx),
388 Worktree::Remote(worktree) => worktree.get_open_buffer(path, cx),
389 };
390 if let Some(existing_buffer) = existing_buffer {
391 return cx.spawn(move |_, _| async move { Ok(existing_buffer) });
392 }
393
394 let path: Arc<Path> = Arc::from(path);
395 let mut loading_watch = match self.loading_buffers().entry(path.clone()) {
396 // If the given path is already being loaded, then wait for that existing
397 // task to complete and return the same buffer.
398 hash_map::Entry::Occupied(e) => e.get().clone(),
399
400 // Otherwise, record the fact that this path is now being loaded.
401 hash_map::Entry::Vacant(entry) => {
402 let (mut tx, rx) = postage::watch::channel();
403 entry.insert(rx.clone());
404
405 let load_buffer = match self {
406 Worktree::Local(worktree) => worktree.open_buffer(&path, cx),
407 Worktree::Remote(worktree) => worktree.open_buffer(&path, cx),
408 };
409 cx.spawn(move |this, mut cx| async move {
410 let result = load_buffer.await;
411
412 // After the buffer loads, record the fact that it is no longer
413 // loading.
414 this.update(&mut cx, |this, _| this.loading_buffers().remove(&path));
415 *tx.borrow_mut() = Some(result.map_err(|e| Arc::new(e)));
416 })
417 .detach();
418 rx
419 }
420 };
421
422 cx.spawn(|_, _| async move {
423 loop {
424 if let Some(result) = loading_watch.borrow().as_ref() {
425 return result.clone().map_err(|e| anyhow!("{}", e));
426 }
427 loading_watch.recv().await;
428 }
429 })
430 }
431
432 #[cfg(feature = "test-support")]
433 pub fn has_open_buffer(&self, path: impl AsRef<Path>, cx: &AppContext) -> bool {
434 let mut open_buffers: Box<dyn Iterator<Item = _>> = match self {
435 Worktree::Local(worktree) => Box::new(worktree.open_buffers.values()),
436 Worktree::Remote(worktree) => {
437 Box::new(worktree.open_buffers.values().filter_map(|buf| {
438 if let RemoteBuffer::Loaded(buf) = buf {
439 Some(buf)
440 } else {
441 None
442 }
443 }))
444 }
445 };
446
447 let path = path.as_ref();
448 open_buffers
449 .find(|buffer| {
450 if let Some(file) = buffer.upgrade(cx).and_then(|buffer| buffer.read(cx).file()) {
451 file.path().as_ref() == path
452 } else {
453 false
454 }
455 })
456 .is_some()
457 }
458
459 pub fn handle_update_buffer(
460 &mut self,
461 envelope: TypedEnvelope<proto::UpdateBuffer>,
462 cx: &mut ModelContext<Self>,
463 ) -> Result<()> {
464 let payload = envelope.payload.clone();
465 let buffer_id = payload.buffer_id as usize;
466 let ops = payload
467 .operations
468 .into_iter()
469 .map(|op| language::proto::deserialize_operation(op))
470 .collect::<Result<Vec<_>, _>>()?;
471
472 match self {
473 Worktree::Local(worktree) => {
474 let buffer = worktree
475 .open_buffers
476 .get(&buffer_id)
477 .and_then(|buf| buf.upgrade(cx))
478 .ok_or_else(|| {
479 anyhow!("invalid buffer {} in update buffer message", buffer_id)
480 })?;
481 buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx))?;
482 }
483 Worktree::Remote(worktree) => match worktree.open_buffers.get_mut(&buffer_id) {
484 Some(RemoteBuffer::Operations(pending_ops)) => pending_ops.extend(ops),
485 Some(RemoteBuffer::Loaded(buffer)) => {
486 if let Some(buffer) = buffer.upgrade(cx) {
487 buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx))?;
488 } else {
489 worktree
490 .open_buffers
491 .insert(buffer_id, RemoteBuffer::Operations(ops));
492 }
493 }
494 None => {
495 worktree
496 .open_buffers
497 .insert(buffer_id, RemoteBuffer::Operations(ops));
498 }
499 },
500 }
501
502 Ok(())
503 }
504
505 pub fn handle_save_buffer(
506 &mut self,
507 envelope: TypedEnvelope<proto::SaveBuffer>,
508 rpc: Arc<Client>,
509 cx: &mut ModelContext<Self>,
510 ) -> Result<()> {
511 let sender_id = envelope.original_sender_id()?;
512 let this = self.as_local().unwrap();
513 let project_id = this
514 .share
515 .as_ref()
516 .ok_or_else(|| anyhow!("can't save buffer while disconnected"))?
517 .project_id;
518
519 let buffer = this
520 .shared_buffers
521 .get(&sender_id)
522 .and_then(|shared_buffers| shared_buffers.get(&envelope.payload.buffer_id).cloned())
523 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
524
525 let receipt = envelope.receipt();
526 let worktree_id = envelope.payload.worktree_id;
527 let buffer_id = envelope.payload.buffer_id;
528 let save = cx.spawn(|_, mut cx| async move {
529 buffer.update(&mut cx, |buffer, cx| buffer.save(cx))?.await
530 });
531
532 cx.background()
533 .spawn(
534 async move {
535 let (version, mtime) = save.await?;
536
537 rpc.respond(
538 receipt,
539 proto::BufferSaved {
540 project_id,
541 worktree_id,
542 buffer_id,
543 version: (&version).into(),
544 mtime: Some(mtime.into()),
545 },
546 )
547 .await?;
548
549 Ok(())
550 }
551 .log_err(),
552 )
553 .detach();
554
555 Ok(())
556 }
557
558 pub fn handle_buffer_saved(
559 &mut self,
560 envelope: TypedEnvelope<proto::BufferSaved>,
561 cx: &mut ModelContext<Self>,
562 ) -> Result<()> {
563 let payload = envelope.payload.clone();
564 let worktree = self.as_remote_mut().unwrap();
565 if let Some(buffer) = worktree
566 .open_buffers
567 .get(&(payload.buffer_id as usize))
568 .and_then(|buf| buf.upgrade(cx))
569 {
570 buffer.update(cx, |buffer, cx| {
571 let version = payload.version.try_into()?;
572 let mtime = payload
573 .mtime
574 .ok_or_else(|| anyhow!("missing mtime"))?
575 .into();
576 buffer.did_save(version, mtime, None, cx);
577 Result::<_, anyhow::Error>::Ok(())
578 })?;
579 }
580 Ok(())
581 }
582
583 fn poll_snapshot(&mut self, cx: &mut ModelContext<Self>) {
584 match self {
585 Self::Local(worktree) => {
586 let is_fake_fs = worktree.fs.is_fake();
587 worktree.snapshot = worktree.background_snapshot.lock().clone();
588 if worktree.is_scanning() {
589 if worktree.poll_task.is_none() {
590 worktree.poll_task = Some(cx.spawn(|this, mut cx| async move {
591 if is_fake_fs {
592 smol::future::yield_now().await;
593 } else {
594 smol::Timer::after(Duration::from_millis(100)).await;
595 }
596 this.update(&mut cx, |this, cx| {
597 this.as_local_mut().unwrap().poll_task = None;
598 this.poll_snapshot(cx);
599 })
600 }));
601 }
602 } else {
603 worktree.poll_task.take();
604 self.update_open_buffers(cx);
605 }
606 }
607 Self::Remote(worktree) => {
608 worktree.snapshot = worktree.snapshot_rx.borrow().clone();
609 self.update_open_buffers(cx);
610 }
611 };
612
613 cx.notify();
614 }
615
616 fn update_open_buffers(&mut self, cx: &mut ModelContext<Self>) {
617 let open_buffers: Box<dyn Iterator<Item = _>> = match &self {
618 Self::Local(worktree) => Box::new(worktree.open_buffers.iter()),
619 Self::Remote(worktree) => {
620 Box::new(worktree.open_buffers.iter().filter_map(|(id, buf)| {
621 if let RemoteBuffer::Loaded(buf) = buf {
622 Some((id, buf))
623 } else {
624 None
625 }
626 }))
627 }
628 };
629
630 let local = self.as_local().is_some();
631 let worktree_path = self.abs_path.clone();
632 let worktree_handle = cx.handle();
633 let mut buffers_to_delete = Vec::new();
634 for (buffer_id, buffer) in open_buffers {
635 if let Some(buffer) = buffer.upgrade(cx) {
636 buffer.update(cx, |buffer, cx| {
637 if let Some(old_file) = File::from_dyn(buffer.file()) {
638 let new_file = if let Some(entry) = old_file
639 .entry_id
640 .and_then(|entry_id| self.entry_for_id(entry_id))
641 {
642 File {
643 is_local: local,
644 worktree_path: worktree_path.clone(),
645 entry_id: Some(entry.id),
646 mtime: entry.mtime,
647 path: entry.path.clone(),
648 worktree: worktree_handle.clone(),
649 }
650 } else if let Some(entry) = self.entry_for_path(old_file.path().as_ref()) {
651 File {
652 is_local: local,
653 worktree_path: worktree_path.clone(),
654 entry_id: Some(entry.id),
655 mtime: entry.mtime,
656 path: entry.path.clone(),
657 worktree: worktree_handle.clone(),
658 }
659 } else {
660 File {
661 is_local: local,
662 worktree_path: worktree_path.clone(),
663 entry_id: None,
664 path: old_file.path().clone(),
665 mtime: old_file.mtime(),
666 worktree: worktree_handle.clone(),
667 }
668 };
669
670 if let Some(task) = buffer.file_updated(Box::new(new_file), cx) {
671 task.detach();
672 }
673 }
674 });
675 } else {
676 buffers_to_delete.push(*buffer_id);
677 }
678 }
679
680 for buffer_id in buffers_to_delete {
681 match self {
682 Self::Local(worktree) => {
683 worktree.open_buffers.remove(&buffer_id);
684 }
685 Self::Remote(worktree) => {
686 worktree.open_buffers.remove(&buffer_id);
687 }
688 }
689 }
690 }
691
692 pub fn update_diagnostics(
693 &mut self,
694 mut params: lsp::PublishDiagnosticsParams,
695 disk_based_sources: &HashSet<String>,
696 cx: &mut ModelContext<Worktree>,
697 ) -> Result<()> {
698 let this = self.as_local_mut().ok_or_else(|| anyhow!("not local"))?;
699 let abs_path = params
700 .uri
701 .to_file_path()
702 .map_err(|_| anyhow!("URI is not a file"))?;
703 let worktree_path = Arc::from(
704 abs_path
705 .strip_prefix(&this.abs_path)
706 .context("path is not within worktree")?,
707 );
708
709 let mut group_ids_by_diagnostic_range = HashMap::default();
710 let mut diagnostics_by_group_id = HashMap::default();
711 let mut next_group_id = 0;
712 for diagnostic in &mut params.diagnostics {
713 let source = diagnostic.source.as_ref();
714 let code = diagnostic.code.as_ref();
715 let group_id = diagnostic_ranges(&diagnostic, &abs_path)
716 .find_map(|range| group_ids_by_diagnostic_range.get(&(source, code, range)))
717 .copied()
718 .unwrap_or_else(|| {
719 let group_id = post_inc(&mut next_group_id);
720 for range in diagnostic_ranges(&diagnostic, &abs_path) {
721 group_ids_by_diagnostic_range.insert((source, code, range), group_id);
722 }
723 group_id
724 });
725
726 diagnostics_by_group_id
727 .entry(group_id)
728 .or_insert(Vec::new())
729 .push(DiagnosticEntry {
730 range: diagnostic.range.start.to_point_utf16()
731 ..diagnostic.range.end.to_point_utf16(),
732 diagnostic: Diagnostic {
733 code: diagnostic.code.clone().map(|code| match code {
734 lsp::NumberOrString::Number(code) => code.to_string(),
735 lsp::NumberOrString::String(code) => code,
736 }),
737 severity: diagnostic.severity.unwrap_or(DiagnosticSeverity::ERROR),
738 message: mem::take(&mut diagnostic.message),
739 group_id,
740 is_primary: false,
741 is_valid: true,
742 is_disk_based: diagnostic
743 .source
744 .as_ref()
745 .map_or(false, |source| disk_based_sources.contains(source)),
746 },
747 });
748 }
749
750 let diagnostics = diagnostics_by_group_id
751 .into_values()
752 .flat_map(|mut diagnostics| {
753 let primary = diagnostics
754 .iter_mut()
755 .min_by_key(|entry| entry.diagnostic.severity)
756 .unwrap();
757 primary.diagnostic.is_primary = true;
758 diagnostics
759 })
760 .collect::<Vec<_>>();
761
762 self.update_diagnostic_entries(worktree_path, params.version, diagnostics, cx)?;
763 Ok(())
764 }
765
766 pub fn update_diagnostic_entries(
767 &mut self,
768 worktree_path: Arc<Path>,
769 version: Option<i32>,
770 diagnostics: Vec<DiagnosticEntry<PointUtf16>>,
771 cx: &mut ModelContext<Self>,
772 ) -> Result<()> {
773 let this = self.as_local_mut().unwrap();
774 for buffer in this.open_buffers.values() {
775 if let Some(buffer) = buffer.upgrade(cx) {
776 if buffer
777 .read(cx)
778 .file()
779 .map_or(false, |file| *file.path() == worktree_path)
780 {
781 let (remote_id, operation) = buffer.update(cx, |buffer, cx| {
782 (
783 buffer.remote_id(),
784 buffer.update_diagnostics(version, diagnostics.clone(), cx),
785 )
786 });
787 self.send_buffer_update(remote_id, operation?, cx);
788 break;
789 }
790 }
791 }
792
793 let this = self.as_local_mut().unwrap();
794 let summary = DiagnosticSummary::new(&diagnostics);
795 this.snapshot
796 .diagnostic_summaries
797 .insert(PathKey(worktree_path.clone()), summary.clone());
798 this.diagnostics.insert(worktree_path.clone(), diagnostics);
799
800 cx.emit(Event::DiagnosticsUpdated(worktree_path.clone()));
801
802 if let Some(share) = this.share.as_ref() {
803 cx.foreground()
804 .spawn({
805 let client = this.client.clone();
806 let project_id = share.project_id;
807 let worktree_id = this.id().to_proto();
808 let path = worktree_path.to_string_lossy().to_string();
809 async move {
810 client
811 .send(proto::UpdateDiagnosticSummary {
812 project_id,
813 worktree_id,
814 summary: Some(proto::DiagnosticSummary {
815 path,
816 error_count: summary.error_count as u32,
817 warning_count: summary.warning_count as u32,
818 info_count: summary.info_count as u32,
819 hint_count: summary.hint_count as u32,
820 }),
821 })
822 .await
823 .log_err()
824 }
825 })
826 .detach();
827 }
828
829 Ok(())
830 }
831
832 fn send_buffer_update(
833 &mut self,
834 buffer_id: u64,
835 operation: Operation,
836 cx: &mut ModelContext<Self>,
837 ) {
838 if let Some((project_id, worktree_id, rpc)) = match self {
839 Worktree::Local(worktree) => worktree
840 .share
841 .as_ref()
842 .map(|share| (share.project_id, worktree.id(), worktree.client.clone())),
843 Worktree::Remote(worktree) => Some((
844 worktree.project_id,
845 worktree.snapshot.id(),
846 worktree.client.clone(),
847 )),
848 } {
849 cx.spawn(|worktree, mut cx| async move {
850 if let Err(error) = rpc
851 .request(proto::UpdateBuffer {
852 project_id,
853 worktree_id: worktree_id.0 as u64,
854 buffer_id,
855 operations: vec![language::proto::serialize_operation(&operation)],
856 })
857 .await
858 {
859 worktree.update(&mut cx, |worktree, _| {
860 log::error!("error sending buffer operation: {}", error);
861 match worktree {
862 Worktree::Local(t) => &mut t.queued_operations,
863 Worktree::Remote(t) => &mut t.queued_operations,
864 }
865 .push((buffer_id, operation));
866 });
867 }
868 })
869 .detach();
870 }
871 }
872}
873
874impl WorktreeId {
875 pub fn from_usize(handle_id: usize) -> Self {
876 Self(handle_id)
877 }
878
879 pub(crate) fn from_proto(id: u64) -> Self {
880 Self(id as usize)
881 }
882
883 pub fn to_proto(&self) -> u64 {
884 self.0 as u64
885 }
886
887 pub fn to_usize(&self) -> usize {
888 self.0
889 }
890}
891
892impl fmt::Display for WorktreeId {
893 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
894 self.0.fmt(f)
895 }
896}
897
898#[derive(Clone)]
899pub struct Snapshot {
900 id: WorktreeId,
901 scan_id: usize,
902 abs_path: Arc<Path>,
903 root_name: String,
904 root_char_bag: CharBag,
905 ignores: HashMap<Arc<Path>, (Arc<Gitignore>, usize)>,
906 entries_by_path: SumTree<Entry>,
907 entries_by_id: SumTree<PathEntry>,
908 removed_entry_ids: HashMap<u64, usize>,
909 next_entry_id: Arc<AtomicUsize>,
910 diagnostic_summaries: TreeMap<PathKey, DiagnosticSummary>,
911}
912
913pub struct LocalWorktree {
914 snapshot: Snapshot,
915 config: WorktreeConfig,
916 background_snapshot: Arc<Mutex<Snapshot>>,
917 last_scan_state_rx: watch::Receiver<ScanState>,
918 _background_scanner_task: Option<Task<()>>,
919 poll_task: Option<Task<()>>,
920 share: Option<ShareState>,
921 loading_buffers: LoadingBuffers,
922 open_buffers: HashMap<usize, WeakModelHandle<Buffer>>,
923 shared_buffers: HashMap<PeerId, HashMap<u64, ModelHandle<Buffer>>>,
924 diagnostics: HashMap<Arc<Path>, Vec<DiagnosticEntry<PointUtf16>>>,
925 queued_operations: Vec<(u64, Operation)>,
926 language_registry: Arc<LanguageRegistry>,
927 client: Arc<Client>,
928 user_store: ModelHandle<UserStore>,
929 fs: Arc<dyn Fs>,
930 languages: Vec<Arc<Language>>,
931 language_servers: HashMap<String, Arc<LanguageServer>>,
932}
933
934struct ShareState {
935 project_id: u64,
936 snapshots_tx: Sender<Snapshot>,
937}
938
939pub struct RemoteWorktree {
940 project_id: u64,
941 snapshot: Snapshot,
942 snapshot_rx: watch::Receiver<Snapshot>,
943 client: Arc<Client>,
944 updates_tx: postage::mpsc::Sender<proto::UpdateWorktree>,
945 replica_id: ReplicaId,
946 loading_buffers: LoadingBuffers,
947 open_buffers: HashMap<usize, RemoteBuffer>,
948 languages: Arc<LanguageRegistry>,
949 user_store: ModelHandle<UserStore>,
950 queued_operations: Vec<(u64, Operation)>,
951}
952
953type LoadingBuffers = HashMap<
954 Arc<Path>,
955 postage::watch::Receiver<Option<Result<ModelHandle<Buffer>, Arc<anyhow::Error>>>>,
956>;
957
958#[derive(Default, Deserialize)]
959struct WorktreeConfig {
960 collaborators: Vec<String>,
961}
962
963impl LocalWorktree {
964 async fn new(
965 client: Arc<Client>,
966 user_store: ModelHandle<UserStore>,
967 path: impl Into<Arc<Path>>,
968 fs: Arc<dyn Fs>,
969 languages: Arc<LanguageRegistry>,
970 cx: &mut AsyncAppContext,
971 ) -> Result<(ModelHandle<Worktree>, Sender<ScanState>)> {
972 let abs_path = path.into();
973 let path: Arc<Path> = Arc::from(Path::new(""));
974 let next_entry_id = AtomicUsize::new(0);
975
976 // After determining whether the root entry is a file or a directory, populate the
977 // snapshot's "root name", which will be used for the purpose of fuzzy matching.
978 let root_name = abs_path
979 .file_name()
980 .map_or(String::new(), |f| f.to_string_lossy().to_string());
981 let root_char_bag = root_name.chars().map(|c| c.to_ascii_lowercase()).collect();
982 let metadata = fs.metadata(&abs_path).await?;
983
984 let mut config = WorktreeConfig::default();
985 if let Ok(zed_toml) = fs.load(&abs_path.join(".zed.toml")).await {
986 if let Ok(parsed) = toml::from_str(&zed_toml) {
987 config = parsed;
988 }
989 }
990
991 let (scan_states_tx, scan_states_rx) = smol::channel::unbounded();
992 let (mut last_scan_state_tx, last_scan_state_rx) = watch::channel_with(ScanState::Scanning);
993 let tree = cx.add_model(move |cx: &mut ModelContext<Worktree>| {
994 let mut snapshot = Snapshot {
995 id: WorktreeId::from_usize(cx.model_id()),
996 scan_id: 0,
997 abs_path,
998 root_name: root_name.clone(),
999 root_char_bag,
1000 ignores: Default::default(),
1001 entries_by_path: Default::default(),
1002 entries_by_id: Default::default(),
1003 removed_entry_ids: Default::default(),
1004 next_entry_id: Arc::new(next_entry_id),
1005 diagnostic_summaries: Default::default(),
1006 };
1007 if let Some(metadata) = metadata {
1008 snapshot.insert_entry(
1009 Entry::new(
1010 path.into(),
1011 &metadata,
1012 &snapshot.next_entry_id,
1013 snapshot.root_char_bag,
1014 ),
1015 fs.as_ref(),
1016 );
1017 }
1018
1019 let tree = Self {
1020 snapshot: snapshot.clone(),
1021 config,
1022 background_snapshot: Arc::new(Mutex::new(snapshot)),
1023 last_scan_state_rx,
1024 _background_scanner_task: None,
1025 share: None,
1026 poll_task: None,
1027 loading_buffers: Default::default(),
1028 open_buffers: Default::default(),
1029 shared_buffers: Default::default(),
1030 diagnostics: Default::default(),
1031 queued_operations: Default::default(),
1032 language_registry: languages,
1033 client,
1034 user_store,
1035 fs,
1036 languages: Default::default(),
1037 language_servers: Default::default(),
1038 };
1039
1040 cx.spawn_weak(|this, mut cx| async move {
1041 while let Ok(scan_state) = scan_states_rx.recv().await {
1042 if let Some(handle) = cx.read(|cx| this.upgrade(cx)) {
1043 let to_send = handle.update(&mut cx, |this, cx| {
1044 last_scan_state_tx.blocking_send(scan_state).ok();
1045 this.poll_snapshot(cx);
1046 let tree = this.as_local_mut().unwrap();
1047 if !tree.is_scanning() {
1048 if let Some(share) = tree.share.as_ref() {
1049 return Some((tree.snapshot(), share.snapshots_tx.clone()));
1050 }
1051 }
1052 None
1053 });
1054
1055 if let Some((snapshot, snapshots_to_send_tx)) = to_send {
1056 if let Err(err) = snapshots_to_send_tx.send(snapshot).await {
1057 log::error!("error submitting snapshot to send {}", err);
1058 }
1059 }
1060 } else {
1061 break;
1062 }
1063 }
1064 })
1065 .detach();
1066
1067 Worktree::Local(tree)
1068 });
1069
1070 Ok((tree, scan_states_tx))
1071 }
1072
1073 pub fn authorized_logins(&self) -> Vec<String> {
1074 self.config.collaborators.clone()
1075 }
1076
1077 pub fn language_registry(&self) -> &LanguageRegistry {
1078 &self.language_registry
1079 }
1080
1081 pub fn languages(&self) -> &[Arc<Language>] {
1082 &self.languages
1083 }
1084
1085 pub fn register_language(
1086 &mut self,
1087 language: &Arc<Language>,
1088 cx: &mut ModelContext<Worktree>,
1089 ) -> Option<Arc<LanguageServer>> {
1090 if !self.languages.iter().any(|l| Arc::ptr_eq(l, language)) {
1091 self.languages.push(language.clone());
1092 }
1093
1094 if let Some(server) = self.language_servers.get(language.name()) {
1095 return Some(server.clone());
1096 }
1097
1098 if let Some(language_server) = language
1099 .start_server(self.abs_path(), cx)
1100 .log_err()
1101 .flatten()
1102 {
1103 let disk_based_sources = language
1104 .disk_based_diagnostic_sources()
1105 .cloned()
1106 .unwrap_or_default();
1107 let disk_based_diagnostics_progress_token =
1108 language.disk_based_diagnostics_progress_token().cloned();
1109 let (diagnostics_tx, diagnostics_rx) = smol::channel::unbounded();
1110 let (disk_based_diagnostics_done_tx, disk_based_diagnostics_done_rx) =
1111 smol::channel::unbounded();
1112 language_server
1113 .on_notification::<lsp::notification::PublishDiagnostics, _>(move |params| {
1114 smol::block_on(diagnostics_tx.send(params)).ok();
1115 })
1116 .detach();
1117 cx.spawn_weak(|this, mut cx| {
1118 let has_disk_based_diagnostic_progress_token =
1119 disk_based_diagnostics_progress_token.is_some();
1120 let disk_based_diagnostics_done_tx = disk_based_diagnostics_done_tx.clone();
1121 async move {
1122 while let Ok(diagnostics) = diagnostics_rx.recv().await {
1123 if let Some(handle) = cx.read(|cx| this.upgrade(cx)) {
1124 handle.update(&mut cx, |this, cx| {
1125 this.update_diagnostics(diagnostics, &disk_based_sources, cx)
1126 .log_err();
1127 if !has_disk_based_diagnostic_progress_token {
1128 smol::block_on(disk_based_diagnostics_done_tx.send(())).ok();
1129 }
1130 })
1131 } else {
1132 break;
1133 }
1134 }
1135 }
1136 })
1137 .detach();
1138
1139 let mut pending_disk_based_diagnostics: i32 = 0;
1140 language_server
1141 .on_notification::<lsp::notification::Progress, _>(move |params| {
1142 let token = match params.token {
1143 lsp::NumberOrString::Number(_) => None,
1144 lsp::NumberOrString::String(token) => Some(token),
1145 };
1146
1147 if token == disk_based_diagnostics_progress_token {
1148 match params.value {
1149 lsp::ProgressParamsValue::WorkDone(progress) => match progress {
1150 lsp::WorkDoneProgress::Begin(_) => {
1151 pending_disk_based_diagnostics += 1;
1152 }
1153 lsp::WorkDoneProgress::End(_) => {
1154 pending_disk_based_diagnostics -= 1;
1155 if pending_disk_based_diagnostics == 0 {
1156 smol::block_on(disk_based_diagnostics_done_tx.send(()))
1157 .ok();
1158 }
1159 }
1160 _ => {}
1161 },
1162 }
1163 }
1164 })
1165 .detach();
1166 let rpc = self.client.clone();
1167 cx.spawn_weak(|this, mut cx| async move {
1168 while let Ok(()) = disk_based_diagnostics_done_rx.recv().await {
1169 if let Some(handle) = cx.read(|cx| this.upgrade(cx)) {
1170 let message = handle.update(&mut cx, |this, cx| {
1171 cx.emit(Event::DiskBasedDiagnosticsUpdated);
1172 let this = this.as_local().unwrap();
1173 this.share
1174 .as_ref()
1175 .map(|share| proto::DiskBasedDiagnosticsUpdated {
1176 project_id: share.project_id,
1177 worktree_id: this.id().to_proto(),
1178 })
1179 });
1180
1181 if let Some(message) = message {
1182 rpc.send(message).await.log_err();
1183 }
1184 } else {
1185 break;
1186 }
1187 }
1188 })
1189 .detach();
1190
1191 self.language_servers
1192 .insert(language.name().to_string(), language_server.clone());
1193 Some(language_server.clone())
1194 } else {
1195 None
1196 }
1197 }
1198
1199 fn get_open_buffer(
1200 &mut self,
1201 path: &Path,
1202 cx: &mut ModelContext<Worktree>,
1203 ) -> Option<ModelHandle<Buffer>> {
1204 let handle = cx.handle();
1205 let mut result = None;
1206 self.open_buffers.retain(|_buffer_id, buffer| {
1207 if let Some(buffer) = buffer.upgrade(cx) {
1208 if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
1209 if file.worktree == handle && file.path().as_ref() == path {
1210 result = Some(buffer);
1211 }
1212 }
1213 true
1214 } else {
1215 false
1216 }
1217 });
1218 result
1219 }
1220
1221 fn open_buffer(
1222 &mut self,
1223 path: &Path,
1224 cx: &mut ModelContext<Worktree>,
1225 ) -> Task<Result<ModelHandle<Buffer>>> {
1226 let path = Arc::from(path);
1227 cx.spawn(move |this, mut cx| async move {
1228 let (file, contents) = this
1229 .update(&mut cx, |t, cx| t.as_local().unwrap().load(&path, cx))
1230 .await?;
1231
1232 let (diagnostics, language, language_server) = this.update(&mut cx, |this, cx| {
1233 let this = this.as_local_mut().unwrap();
1234 let diagnostics = this.diagnostics.remove(&path);
1235 let language = this
1236 .language_registry
1237 .select_language(file.full_path())
1238 .cloned();
1239 let server = language
1240 .as_ref()
1241 .and_then(|language| this.register_language(language, cx));
1242 (diagnostics, language, server)
1243 });
1244
1245 let mut buffer_operations = Vec::new();
1246 let buffer = cx.add_model(|cx| {
1247 let mut buffer = Buffer::from_file(0, contents, Box::new(file), cx);
1248 buffer.set_language(language, language_server, cx);
1249 if let Some(diagnostics) = diagnostics {
1250 let op = buffer.update_diagnostics(None, diagnostics, cx).unwrap();
1251 buffer_operations.push(op);
1252 }
1253 buffer
1254 });
1255
1256 this.update(&mut cx, |this, cx| {
1257 for op in buffer_operations {
1258 this.send_buffer_update(buffer.read(cx).remote_id(), op, cx);
1259 }
1260 let this = this.as_local_mut().unwrap();
1261 this.open_buffers.insert(buffer.id(), buffer.downgrade());
1262 });
1263
1264 Ok(buffer)
1265 })
1266 }
1267
1268 pub fn open_remote_buffer(
1269 &mut self,
1270 envelope: TypedEnvelope<proto::OpenBuffer>,
1271 cx: &mut ModelContext<Worktree>,
1272 ) -> Task<Result<proto::OpenBufferResponse>> {
1273 cx.spawn(|this, mut cx| async move {
1274 let peer_id = envelope.original_sender_id();
1275 let path = Path::new(&envelope.payload.path);
1276 let buffer = this
1277 .update(&mut cx, |this, cx| this.open_buffer(path, cx))
1278 .await?;
1279 this.update(&mut cx, |this, cx| {
1280 this.as_local_mut()
1281 .unwrap()
1282 .shared_buffers
1283 .entry(peer_id?)
1284 .or_default()
1285 .insert(buffer.id() as u64, buffer.clone());
1286
1287 Ok(proto::OpenBufferResponse {
1288 buffer: Some(buffer.update(cx.as_mut(), |buffer, _| buffer.to_proto())),
1289 })
1290 })
1291 })
1292 }
1293
1294 pub fn close_remote_buffer(
1295 &mut self,
1296 envelope: TypedEnvelope<proto::CloseBuffer>,
1297 cx: &mut ModelContext<Worktree>,
1298 ) -> Result<()> {
1299 if let Some(shared_buffers) = self.shared_buffers.get_mut(&envelope.original_sender_id()?) {
1300 shared_buffers.remove(&envelope.payload.buffer_id);
1301 cx.notify();
1302 }
1303
1304 Ok(())
1305 }
1306
1307 pub fn remove_collaborator(
1308 &mut self,
1309 peer_id: PeerId,
1310 replica_id: ReplicaId,
1311 cx: &mut ModelContext<Worktree>,
1312 ) {
1313 self.shared_buffers.remove(&peer_id);
1314 for (_, buffer) in &self.open_buffers {
1315 if let Some(buffer) = buffer.upgrade(cx) {
1316 buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
1317 }
1318 }
1319 cx.notify();
1320 }
1321
1322 pub fn scan_complete(&self) -> impl Future<Output = ()> {
1323 let mut scan_state_rx = self.last_scan_state_rx.clone();
1324 async move {
1325 let mut scan_state = Some(scan_state_rx.borrow().clone());
1326 while let Some(ScanState::Scanning) = scan_state {
1327 scan_state = scan_state_rx.recv().await;
1328 }
1329 }
1330 }
1331
1332 fn is_scanning(&self) -> bool {
1333 if let ScanState::Scanning = *self.last_scan_state_rx.borrow() {
1334 true
1335 } else {
1336 false
1337 }
1338 }
1339
1340 pub fn snapshot(&self) -> Snapshot {
1341 self.snapshot.clone()
1342 }
1343
1344 pub fn abs_path(&self) -> &Arc<Path> {
1345 &self.snapshot.abs_path
1346 }
1347
1348 pub fn contains_abs_path(&self, path: &Path) -> bool {
1349 path.starts_with(&self.snapshot.abs_path)
1350 }
1351
1352 fn absolutize(&self, path: &Path) -> PathBuf {
1353 if path.file_name().is_some() {
1354 self.snapshot.abs_path.join(path)
1355 } else {
1356 self.snapshot.abs_path.to_path_buf()
1357 }
1358 }
1359
1360 fn load(&self, path: &Path, cx: &mut ModelContext<Worktree>) -> Task<Result<(File, String)>> {
1361 let handle = cx.handle();
1362 let path = Arc::from(path);
1363 let worktree_path = self.abs_path.clone();
1364 let abs_path = self.absolutize(&path);
1365 let background_snapshot = self.background_snapshot.clone();
1366 let fs = self.fs.clone();
1367 cx.spawn(|this, mut cx| async move {
1368 let text = fs.load(&abs_path).await?;
1369 // Eagerly populate the snapshot with an updated entry for the loaded file
1370 let entry = refresh_entry(fs.as_ref(), &background_snapshot, path, &abs_path).await?;
1371 this.update(&mut cx, |this, cx| this.poll_snapshot(cx));
1372 Ok((
1373 File {
1374 entry_id: Some(entry.id),
1375 worktree: handle,
1376 worktree_path,
1377 path: entry.path,
1378 mtime: entry.mtime,
1379 is_local: true,
1380 },
1381 text,
1382 ))
1383 })
1384 }
1385
1386 pub fn save_buffer_as(
1387 &self,
1388 buffer: ModelHandle<Buffer>,
1389 path: impl Into<Arc<Path>>,
1390 text: Rope,
1391 cx: &mut ModelContext<Worktree>,
1392 ) -> Task<Result<File>> {
1393 let save = self.save(path, text, cx);
1394 cx.spawn(|this, mut cx| async move {
1395 let entry = save.await?;
1396 this.update(&mut cx, |this, cx| {
1397 let this = this.as_local_mut().unwrap();
1398 this.open_buffers.insert(buffer.id(), buffer.downgrade());
1399 Ok(File {
1400 entry_id: Some(entry.id),
1401 worktree: cx.handle(),
1402 worktree_path: this.abs_path.clone(),
1403 path: entry.path,
1404 mtime: entry.mtime,
1405 is_local: true,
1406 })
1407 })
1408 })
1409 }
1410
1411 fn save(
1412 &self,
1413 path: impl Into<Arc<Path>>,
1414 text: Rope,
1415 cx: &mut ModelContext<Worktree>,
1416 ) -> Task<Result<Entry>> {
1417 let path = path.into();
1418 let abs_path = self.absolutize(&path);
1419 let background_snapshot = self.background_snapshot.clone();
1420 let fs = self.fs.clone();
1421 let save = cx.background().spawn(async move {
1422 fs.save(&abs_path, &text).await?;
1423 refresh_entry(fs.as_ref(), &background_snapshot, path.clone(), &abs_path).await
1424 });
1425
1426 cx.spawn(|this, mut cx| async move {
1427 let entry = save.await?;
1428 this.update(&mut cx, |this, cx| this.poll_snapshot(cx));
1429 Ok(entry)
1430 })
1431 }
1432
1433 pub fn share(
1434 &mut self,
1435 project_id: u64,
1436 cx: &mut ModelContext<Worktree>,
1437 ) -> Task<anyhow::Result<()>> {
1438 if self.share.is_some() {
1439 return Task::ready(Ok(()));
1440 }
1441
1442 let snapshot = self.snapshot();
1443 let rpc = self.client.clone();
1444 let worktree_id = cx.model_id() as u64;
1445 let (snapshots_to_send_tx, snapshots_to_send_rx) = smol::channel::unbounded::<Snapshot>();
1446 self.share = Some(ShareState {
1447 project_id,
1448 snapshots_tx: snapshots_to_send_tx,
1449 });
1450
1451 cx.background()
1452 .spawn({
1453 let rpc = rpc.clone();
1454 let snapshot = snapshot.clone();
1455 async move {
1456 let mut prev_snapshot = snapshot;
1457 while let Ok(snapshot) = snapshots_to_send_rx.recv().await {
1458 let message =
1459 snapshot.build_update(&prev_snapshot, project_id, worktree_id, false);
1460 match rpc.send(message).await {
1461 Ok(()) => prev_snapshot = snapshot,
1462 Err(err) => log::error!("error sending snapshot diff {}", err),
1463 }
1464 }
1465 }
1466 })
1467 .detach();
1468
1469 let share_message = cx.background().spawn(async move {
1470 proto::ShareWorktree {
1471 project_id,
1472 worktree: Some(snapshot.to_proto()),
1473 }
1474 });
1475
1476 cx.foreground().spawn(async move {
1477 rpc.request(share_message.await).await?;
1478 Ok(())
1479 })
1480 }
1481}
1482
1483fn build_gitignore(abs_path: &Path, fs: &dyn Fs) -> Result<Gitignore> {
1484 let contents = smol::block_on(fs.load(&abs_path))?;
1485 let parent = abs_path.parent().unwrap_or(Path::new("/"));
1486 let mut builder = GitignoreBuilder::new(parent);
1487 for line in contents.lines() {
1488 builder.add_line(Some(abs_path.into()), line)?;
1489 }
1490 Ok(builder.build()?)
1491}
1492
1493impl Deref for Worktree {
1494 type Target = Snapshot;
1495
1496 fn deref(&self) -> &Self::Target {
1497 match self {
1498 Worktree::Local(worktree) => &worktree.snapshot,
1499 Worktree::Remote(worktree) => &worktree.snapshot,
1500 }
1501 }
1502}
1503
1504impl Deref for LocalWorktree {
1505 type Target = Snapshot;
1506
1507 fn deref(&self) -> &Self::Target {
1508 &self.snapshot
1509 }
1510}
1511
1512impl Deref for RemoteWorktree {
1513 type Target = Snapshot;
1514
1515 fn deref(&self) -> &Self::Target {
1516 &self.snapshot
1517 }
1518}
1519
1520impl fmt::Debug for LocalWorktree {
1521 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1522 self.snapshot.fmt(f)
1523 }
1524}
1525
1526impl RemoteWorktree {
1527 fn get_open_buffer(
1528 &mut self,
1529 path: &Path,
1530 cx: &mut ModelContext<Worktree>,
1531 ) -> Option<ModelHandle<Buffer>> {
1532 let handle = cx.handle();
1533 let mut existing_buffer = None;
1534 self.open_buffers.retain(|_buffer_id, buffer| {
1535 if let Some(buffer) = buffer.upgrade(cx.as_ref()) {
1536 if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
1537 if file.worktree == handle && file.path().as_ref() == path {
1538 existing_buffer = Some(buffer);
1539 }
1540 }
1541 true
1542 } else {
1543 false
1544 }
1545 });
1546 existing_buffer
1547 }
1548
1549 fn open_buffer(
1550 &mut self,
1551 path: &Path,
1552 cx: &mut ModelContext<Worktree>,
1553 ) -> Task<Result<ModelHandle<Buffer>>> {
1554 let rpc = self.client.clone();
1555 let replica_id = self.replica_id;
1556 let project_id = self.project_id;
1557 let remote_worktree_id = self.id();
1558 let root_path = self.snapshot.abs_path.clone();
1559 let path: Arc<Path> = Arc::from(path);
1560 let path_string = path.to_string_lossy().to_string();
1561 cx.spawn_weak(move |this, mut cx| async move {
1562 let entry = this
1563 .upgrade(&cx)
1564 .ok_or_else(|| anyhow!("worktree was closed"))?
1565 .read_with(&cx, |tree, _| tree.entry_for_path(&path).cloned())
1566 .ok_or_else(|| anyhow!("file does not exist"))?;
1567 let response = rpc
1568 .request(proto::OpenBuffer {
1569 project_id,
1570 worktree_id: remote_worktree_id.to_proto(),
1571 path: path_string,
1572 })
1573 .await?;
1574
1575 let this = this
1576 .upgrade(&cx)
1577 .ok_or_else(|| anyhow!("worktree was closed"))?;
1578 let file = File {
1579 entry_id: Some(entry.id),
1580 worktree: this.clone(),
1581 worktree_path: root_path,
1582 path: entry.path,
1583 mtime: entry.mtime,
1584 is_local: false,
1585 };
1586 let language = this.read_with(&cx, |this, _| {
1587 use language::File;
1588 this.languages().select_language(file.full_path()).cloned()
1589 });
1590 let remote_buffer = response.buffer.ok_or_else(|| anyhow!("empty buffer"))?;
1591 let buffer_id = remote_buffer.id as usize;
1592 let buffer = cx.add_model(|cx| {
1593 Buffer::from_proto(replica_id, remote_buffer, Some(Box::new(file)), cx)
1594 .unwrap()
1595 .with_language(language, None, cx)
1596 });
1597 this.update(&mut cx, move |this, cx| {
1598 let this = this.as_remote_mut().unwrap();
1599 if let Some(RemoteBuffer::Operations(pending_ops)) = this
1600 .open_buffers
1601 .insert(buffer_id, RemoteBuffer::Loaded(buffer.downgrade()))
1602 {
1603 buffer.update(cx, |buf, cx| buf.apply_ops(pending_ops, cx))?;
1604 }
1605 Result::<_, anyhow::Error>::Ok(buffer)
1606 })
1607 })
1608 }
1609
1610 pub fn close_all_buffers(&mut self, cx: &mut MutableAppContext) {
1611 for (_, buffer) in self.open_buffers.drain() {
1612 if let RemoteBuffer::Loaded(buffer) = buffer {
1613 if let Some(buffer) = buffer.upgrade(cx) {
1614 buffer.update(cx, |buffer, cx| buffer.close(cx))
1615 }
1616 }
1617 }
1618 }
1619
1620 fn snapshot(&self) -> Snapshot {
1621 self.snapshot.clone()
1622 }
1623
1624 pub fn update_from_remote(
1625 &mut self,
1626 envelope: TypedEnvelope<proto::UpdateWorktree>,
1627 cx: &mut ModelContext<Worktree>,
1628 ) -> Result<()> {
1629 let mut tx = self.updates_tx.clone();
1630 let payload = envelope.payload.clone();
1631 cx.background()
1632 .spawn(async move {
1633 tx.send(payload).await.expect("receiver runs to completion");
1634 })
1635 .detach();
1636
1637 Ok(())
1638 }
1639
1640 pub fn update_diagnostic_summary(
1641 &mut self,
1642 envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
1643 cx: &mut ModelContext<Worktree>,
1644 ) {
1645 if let Some(summary) = envelope.payload.summary {
1646 let path: Arc<Path> = Path::new(&summary.path).into();
1647 self.snapshot.diagnostic_summaries.insert(
1648 PathKey(path.clone()),
1649 DiagnosticSummary {
1650 error_count: summary.error_count as usize,
1651 warning_count: summary.warning_count as usize,
1652 info_count: summary.info_count as usize,
1653 hint_count: summary.hint_count as usize,
1654 },
1655 );
1656 cx.emit(Event::DiagnosticsUpdated(path));
1657 }
1658 }
1659
1660 pub fn disk_based_diagnostics_updated(&self, cx: &mut ModelContext<Worktree>) {
1661 cx.emit(Event::DiskBasedDiagnosticsUpdated);
1662 }
1663
1664 pub fn remove_collaborator(&mut self, replica_id: ReplicaId, cx: &mut ModelContext<Worktree>) {
1665 for (_, buffer) in &self.open_buffers {
1666 if let Some(buffer) = buffer.upgrade(cx) {
1667 buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
1668 }
1669 }
1670 cx.notify();
1671 }
1672}
1673
1674enum RemoteBuffer {
1675 Operations(Vec<Operation>),
1676 Loaded(WeakModelHandle<Buffer>),
1677}
1678
1679impl RemoteBuffer {
1680 fn upgrade(&self, cx: &impl UpgradeModelHandle) -> Option<ModelHandle<Buffer>> {
1681 match self {
1682 Self::Operations(_) => None,
1683 Self::Loaded(buffer) => buffer.upgrade(cx),
1684 }
1685 }
1686}
1687
1688impl Snapshot {
1689 pub fn id(&self) -> WorktreeId {
1690 self.id
1691 }
1692
1693 pub fn to_proto(&self) -> proto::Worktree {
1694 let root_name = self.root_name.clone();
1695 proto::Worktree {
1696 id: self.id.0 as u64,
1697 root_name,
1698 entries: self
1699 .entries_by_path
1700 .iter()
1701 .filter(|e| !e.is_ignored)
1702 .map(Into::into)
1703 .collect(),
1704 diagnostic_summaries: self
1705 .diagnostic_summaries
1706 .iter()
1707 .map(|(path, summary)| summary.to_proto(path.0.clone()))
1708 .collect(),
1709 }
1710 }
1711
1712 pub fn build_update(
1713 &self,
1714 other: &Self,
1715 project_id: u64,
1716 worktree_id: u64,
1717 include_ignored: bool,
1718 ) -> proto::UpdateWorktree {
1719 let mut updated_entries = Vec::new();
1720 let mut removed_entries = Vec::new();
1721 let mut self_entries = self
1722 .entries_by_id
1723 .cursor::<()>()
1724 .filter(|e| include_ignored || !e.is_ignored)
1725 .peekable();
1726 let mut other_entries = other
1727 .entries_by_id
1728 .cursor::<()>()
1729 .filter(|e| include_ignored || !e.is_ignored)
1730 .peekable();
1731 loop {
1732 match (self_entries.peek(), other_entries.peek()) {
1733 (Some(self_entry), Some(other_entry)) => {
1734 match Ord::cmp(&self_entry.id, &other_entry.id) {
1735 Ordering::Less => {
1736 let entry = self.entry_for_id(self_entry.id).unwrap().into();
1737 updated_entries.push(entry);
1738 self_entries.next();
1739 }
1740 Ordering::Equal => {
1741 if self_entry.scan_id != other_entry.scan_id {
1742 let entry = self.entry_for_id(self_entry.id).unwrap().into();
1743 updated_entries.push(entry);
1744 }
1745
1746 self_entries.next();
1747 other_entries.next();
1748 }
1749 Ordering::Greater => {
1750 removed_entries.push(other_entry.id as u64);
1751 other_entries.next();
1752 }
1753 }
1754 }
1755 (Some(self_entry), None) => {
1756 let entry = self.entry_for_id(self_entry.id).unwrap().into();
1757 updated_entries.push(entry);
1758 self_entries.next();
1759 }
1760 (None, Some(other_entry)) => {
1761 removed_entries.push(other_entry.id as u64);
1762 other_entries.next();
1763 }
1764 (None, None) => break,
1765 }
1766 }
1767
1768 proto::UpdateWorktree {
1769 project_id,
1770 worktree_id,
1771 root_name: self.root_name().to_string(),
1772 updated_entries,
1773 removed_entries,
1774 }
1775 }
1776
1777 fn apply_update(&mut self, update: proto::UpdateWorktree) -> Result<()> {
1778 self.scan_id += 1;
1779 let scan_id = self.scan_id;
1780
1781 let mut entries_by_path_edits = Vec::new();
1782 let mut entries_by_id_edits = Vec::new();
1783 for entry_id in update.removed_entries {
1784 let entry_id = entry_id as usize;
1785 let entry = self
1786 .entry_for_id(entry_id)
1787 .ok_or_else(|| anyhow!("unknown entry"))?;
1788 entries_by_path_edits.push(Edit::Remove(PathKey(entry.path.clone())));
1789 entries_by_id_edits.push(Edit::Remove(entry.id));
1790 }
1791
1792 for entry in update.updated_entries {
1793 let entry = Entry::try_from((&self.root_char_bag, entry))?;
1794 if let Some(PathEntry { path, .. }) = self.entries_by_id.get(&entry.id, &()) {
1795 entries_by_path_edits.push(Edit::Remove(PathKey(path.clone())));
1796 }
1797 entries_by_id_edits.push(Edit::Insert(PathEntry {
1798 id: entry.id,
1799 path: entry.path.clone(),
1800 is_ignored: entry.is_ignored,
1801 scan_id,
1802 }));
1803 entries_by_path_edits.push(Edit::Insert(entry));
1804 }
1805
1806 self.entries_by_path.edit(entries_by_path_edits, &());
1807 self.entries_by_id.edit(entries_by_id_edits, &());
1808
1809 Ok(())
1810 }
1811
1812 pub fn file_count(&self) -> usize {
1813 self.entries_by_path.summary().file_count
1814 }
1815
1816 pub fn visible_file_count(&self) -> usize {
1817 self.entries_by_path.summary().visible_file_count
1818 }
1819
1820 fn traverse_from_offset(
1821 &self,
1822 include_dirs: bool,
1823 include_ignored: bool,
1824 start_offset: usize,
1825 ) -> Traversal {
1826 let mut cursor = self.entries_by_path.cursor();
1827 cursor.seek(
1828 &TraversalTarget::Count {
1829 count: start_offset,
1830 include_dirs,
1831 include_ignored,
1832 },
1833 Bias::Right,
1834 &(),
1835 );
1836 Traversal {
1837 cursor,
1838 include_dirs,
1839 include_ignored,
1840 }
1841 }
1842
1843 fn traverse_from_path(
1844 &self,
1845 include_dirs: bool,
1846 include_ignored: bool,
1847 path: &Path,
1848 ) -> Traversal {
1849 let mut cursor = self.entries_by_path.cursor();
1850 cursor.seek(&TraversalTarget::Path(path), Bias::Left, &());
1851 Traversal {
1852 cursor,
1853 include_dirs,
1854 include_ignored,
1855 }
1856 }
1857
1858 pub fn files(&self, include_ignored: bool, start: usize) -> Traversal {
1859 self.traverse_from_offset(false, include_ignored, start)
1860 }
1861
1862 pub fn entries(&self, include_ignored: bool) -> Traversal {
1863 self.traverse_from_offset(true, include_ignored, 0)
1864 }
1865
1866 pub fn paths(&self) -> impl Iterator<Item = &Arc<Path>> {
1867 let empty_path = Path::new("");
1868 self.entries_by_path
1869 .cursor::<()>()
1870 .filter(move |entry| entry.path.as_ref() != empty_path)
1871 .map(|entry| &entry.path)
1872 }
1873
1874 fn child_entries<'a>(&'a self, parent_path: &'a Path) -> ChildEntriesIter<'a> {
1875 let mut cursor = self.entries_by_path.cursor();
1876 cursor.seek(&TraversalTarget::Path(parent_path), Bias::Right, &());
1877 let traversal = Traversal {
1878 cursor,
1879 include_dirs: true,
1880 include_ignored: true,
1881 };
1882 ChildEntriesIter {
1883 traversal,
1884 parent_path,
1885 }
1886 }
1887
1888 pub fn root_entry(&self) -> Option<&Entry> {
1889 self.entry_for_path("")
1890 }
1891
1892 pub fn root_name(&self) -> &str {
1893 &self.root_name
1894 }
1895
1896 pub fn entry_for_path(&self, path: impl AsRef<Path>) -> Option<&Entry> {
1897 let path = path.as_ref();
1898 self.traverse_from_path(true, true, path)
1899 .entry()
1900 .and_then(|entry| {
1901 if entry.path.as_ref() == path {
1902 Some(entry)
1903 } else {
1904 None
1905 }
1906 })
1907 }
1908
1909 pub fn entry_for_id(&self, id: usize) -> Option<&Entry> {
1910 let entry = self.entries_by_id.get(&id, &())?;
1911 self.entry_for_path(&entry.path)
1912 }
1913
1914 pub fn inode_for_path(&self, path: impl AsRef<Path>) -> Option<u64> {
1915 self.entry_for_path(path.as_ref()).map(|e| e.inode)
1916 }
1917
1918 fn insert_entry(&mut self, mut entry: Entry, fs: &dyn Fs) -> Entry {
1919 if !entry.is_dir() && entry.path.file_name() == Some(&GITIGNORE) {
1920 let abs_path = self.abs_path.join(&entry.path);
1921 match build_gitignore(&abs_path, fs) {
1922 Ok(ignore) => {
1923 let ignore_dir_path = entry.path.parent().unwrap();
1924 self.ignores
1925 .insert(ignore_dir_path.into(), (Arc::new(ignore), self.scan_id));
1926 }
1927 Err(error) => {
1928 log::error!(
1929 "error loading .gitignore file {:?} - {:?}",
1930 &entry.path,
1931 error
1932 );
1933 }
1934 }
1935 }
1936
1937 self.reuse_entry_id(&mut entry);
1938 self.entries_by_path.insert_or_replace(entry.clone(), &());
1939 self.entries_by_id.insert_or_replace(
1940 PathEntry {
1941 id: entry.id,
1942 path: entry.path.clone(),
1943 is_ignored: entry.is_ignored,
1944 scan_id: self.scan_id,
1945 },
1946 &(),
1947 );
1948 entry
1949 }
1950
1951 fn populate_dir(
1952 &mut self,
1953 parent_path: Arc<Path>,
1954 entries: impl IntoIterator<Item = Entry>,
1955 ignore: Option<Arc<Gitignore>>,
1956 ) {
1957 let mut parent_entry = self
1958 .entries_by_path
1959 .get(&PathKey(parent_path.clone()), &())
1960 .unwrap()
1961 .clone();
1962 if let Some(ignore) = ignore {
1963 self.ignores.insert(parent_path, (ignore, self.scan_id));
1964 }
1965 if matches!(parent_entry.kind, EntryKind::PendingDir) {
1966 parent_entry.kind = EntryKind::Dir;
1967 } else {
1968 unreachable!();
1969 }
1970
1971 let mut entries_by_path_edits = vec![Edit::Insert(parent_entry)];
1972 let mut entries_by_id_edits = Vec::new();
1973
1974 for mut entry in entries {
1975 self.reuse_entry_id(&mut entry);
1976 entries_by_id_edits.push(Edit::Insert(PathEntry {
1977 id: entry.id,
1978 path: entry.path.clone(),
1979 is_ignored: entry.is_ignored,
1980 scan_id: self.scan_id,
1981 }));
1982 entries_by_path_edits.push(Edit::Insert(entry));
1983 }
1984
1985 self.entries_by_path.edit(entries_by_path_edits, &());
1986 self.entries_by_id.edit(entries_by_id_edits, &());
1987 }
1988
1989 fn reuse_entry_id(&mut self, entry: &mut Entry) {
1990 if let Some(removed_entry_id) = self.removed_entry_ids.remove(&entry.inode) {
1991 entry.id = removed_entry_id;
1992 } else if let Some(existing_entry) = self.entry_for_path(&entry.path) {
1993 entry.id = existing_entry.id;
1994 }
1995 }
1996
1997 fn remove_path(&mut self, path: &Path) {
1998 let mut new_entries;
1999 let removed_entries;
2000 {
2001 let mut cursor = self.entries_by_path.cursor::<TraversalProgress>();
2002 new_entries = cursor.slice(&TraversalTarget::Path(path), Bias::Left, &());
2003 removed_entries = cursor.slice(&TraversalTarget::PathSuccessor(path), Bias::Left, &());
2004 new_entries.push_tree(cursor.suffix(&()), &());
2005 }
2006 self.entries_by_path = new_entries;
2007
2008 let mut entries_by_id_edits = Vec::new();
2009 for entry in removed_entries.cursor::<()>() {
2010 let removed_entry_id = self
2011 .removed_entry_ids
2012 .entry(entry.inode)
2013 .or_insert(entry.id);
2014 *removed_entry_id = cmp::max(*removed_entry_id, entry.id);
2015 entries_by_id_edits.push(Edit::Remove(entry.id));
2016 }
2017 self.entries_by_id.edit(entries_by_id_edits, &());
2018
2019 if path.file_name() == Some(&GITIGNORE) {
2020 if let Some((_, scan_id)) = self.ignores.get_mut(path.parent().unwrap()) {
2021 *scan_id = self.scan_id;
2022 }
2023 }
2024 }
2025
2026 fn ignore_stack_for_path(&self, path: &Path, is_dir: bool) -> Arc<IgnoreStack> {
2027 let mut new_ignores = Vec::new();
2028 for ancestor in path.ancestors().skip(1) {
2029 if let Some((ignore, _)) = self.ignores.get(ancestor) {
2030 new_ignores.push((ancestor, Some(ignore.clone())));
2031 } else {
2032 new_ignores.push((ancestor, None));
2033 }
2034 }
2035
2036 let mut ignore_stack = IgnoreStack::none();
2037 for (parent_path, ignore) in new_ignores.into_iter().rev() {
2038 if ignore_stack.is_path_ignored(&parent_path, true) {
2039 ignore_stack = IgnoreStack::all();
2040 break;
2041 } else if let Some(ignore) = ignore {
2042 ignore_stack = ignore_stack.append(Arc::from(parent_path), ignore);
2043 }
2044 }
2045
2046 if ignore_stack.is_path_ignored(path, is_dir) {
2047 ignore_stack = IgnoreStack::all();
2048 }
2049
2050 ignore_stack
2051 }
2052}
2053
2054impl fmt::Debug for Snapshot {
2055 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2056 for entry in self.entries_by_path.cursor::<()>() {
2057 for _ in entry.path.ancestors().skip(1) {
2058 write!(f, " ")?;
2059 }
2060 writeln!(f, "{:?} (inode: {})", entry.path, entry.inode)?;
2061 }
2062 Ok(())
2063 }
2064}
2065
2066#[derive(Clone, PartialEq)]
2067pub struct File {
2068 entry_id: Option<usize>,
2069 worktree: ModelHandle<Worktree>,
2070 worktree_path: Arc<Path>,
2071 pub path: Arc<Path>,
2072 pub mtime: SystemTime,
2073 is_local: bool,
2074}
2075
2076impl language::File for File {
2077 fn mtime(&self) -> SystemTime {
2078 self.mtime
2079 }
2080
2081 fn path(&self) -> &Arc<Path> {
2082 &self.path
2083 }
2084
2085 fn abs_path(&self) -> Option<PathBuf> {
2086 if self.is_local {
2087 Some(self.worktree_path.join(&self.path))
2088 } else {
2089 None
2090 }
2091 }
2092
2093 fn full_path(&self) -> PathBuf {
2094 let mut full_path = PathBuf::new();
2095 if let Some(worktree_name) = self.worktree_path.file_name() {
2096 full_path.push(worktree_name);
2097 }
2098 full_path.push(&self.path);
2099 full_path
2100 }
2101
2102 /// Returns the last component of this handle's absolute path. If this handle refers to the root
2103 /// of its worktree, then this method will return the name of the worktree itself.
2104 fn file_name<'a>(&'a self) -> Option<OsString> {
2105 self.path
2106 .file_name()
2107 .or_else(|| self.worktree_path.file_name())
2108 .map(Into::into)
2109 }
2110
2111 fn is_deleted(&self) -> bool {
2112 self.entry_id.is_none()
2113 }
2114
2115 fn save(
2116 &self,
2117 buffer_id: u64,
2118 text: Rope,
2119 version: clock::Global,
2120 cx: &mut MutableAppContext,
2121 ) -> Task<Result<(clock::Global, SystemTime)>> {
2122 let worktree_id = self.worktree.read(cx).id().to_proto();
2123 self.worktree.update(cx, |worktree, cx| match worktree {
2124 Worktree::Local(worktree) => {
2125 let rpc = worktree.client.clone();
2126 let project_id = worktree.share.as_ref().map(|share| share.project_id);
2127 let save = worktree.save(self.path.clone(), text, cx);
2128 cx.background().spawn(async move {
2129 let entry = save.await?;
2130 if let Some(project_id) = project_id {
2131 rpc.send(proto::BufferSaved {
2132 project_id,
2133 worktree_id,
2134 buffer_id,
2135 version: (&version).into(),
2136 mtime: Some(entry.mtime.into()),
2137 })
2138 .await?;
2139 }
2140 Ok((version, entry.mtime))
2141 })
2142 }
2143 Worktree::Remote(worktree) => {
2144 let rpc = worktree.client.clone();
2145 let project_id = worktree.project_id;
2146 cx.foreground().spawn(async move {
2147 let response = rpc
2148 .request(proto::SaveBuffer {
2149 project_id,
2150 worktree_id,
2151 buffer_id,
2152 })
2153 .await?;
2154 let version = response.version.try_into()?;
2155 let mtime = response
2156 .mtime
2157 .ok_or_else(|| anyhow!("missing mtime"))?
2158 .into();
2159 Ok((version, mtime))
2160 })
2161 }
2162 })
2163 }
2164
2165 fn load_local(&self, cx: &AppContext) -> Option<Task<Result<String>>> {
2166 let worktree = self.worktree.read(cx).as_local()?;
2167 let abs_path = worktree.absolutize(&self.path);
2168 let fs = worktree.fs.clone();
2169 Some(
2170 cx.background()
2171 .spawn(async move { fs.load(&abs_path).await }),
2172 )
2173 }
2174
2175 fn buffer_updated(&self, buffer_id: u64, operation: Operation, cx: &mut MutableAppContext) {
2176 self.worktree.update(cx, |worktree, cx| {
2177 worktree.send_buffer_update(buffer_id, operation, cx);
2178 });
2179 }
2180
2181 fn buffer_removed(&self, buffer_id: u64, cx: &mut MutableAppContext) {
2182 self.worktree.update(cx, |worktree, cx| {
2183 if let Worktree::Remote(worktree) = worktree {
2184 let project_id = worktree.project_id;
2185 let worktree_id = worktree.id().to_proto();
2186 let rpc = worktree.client.clone();
2187 cx.background()
2188 .spawn(async move {
2189 if let Err(error) = rpc
2190 .send(proto::CloseBuffer {
2191 project_id,
2192 worktree_id,
2193 buffer_id,
2194 })
2195 .await
2196 {
2197 log::error!("error closing remote buffer: {}", error);
2198 }
2199 })
2200 .detach();
2201 }
2202 });
2203 }
2204
2205 fn as_any(&self) -> &dyn Any {
2206 self
2207 }
2208}
2209
2210impl File {
2211 pub fn from_dyn(file: Option<&dyn language::File>) -> Option<&Self> {
2212 file.and_then(|f| f.as_any().downcast_ref())
2213 }
2214
2215 pub fn worktree_id(&self, cx: &AppContext) -> WorktreeId {
2216 self.worktree.read(cx).id()
2217 }
2218}
2219
2220#[derive(Clone, Debug)]
2221pub struct Entry {
2222 pub id: usize,
2223 pub kind: EntryKind,
2224 pub path: Arc<Path>,
2225 pub inode: u64,
2226 pub mtime: SystemTime,
2227 pub is_symlink: bool,
2228 pub is_ignored: bool,
2229}
2230
2231#[derive(Clone, Debug)]
2232pub enum EntryKind {
2233 PendingDir,
2234 Dir,
2235 File(CharBag),
2236}
2237
2238impl Entry {
2239 fn new(
2240 path: Arc<Path>,
2241 metadata: &fs::Metadata,
2242 next_entry_id: &AtomicUsize,
2243 root_char_bag: CharBag,
2244 ) -> Self {
2245 Self {
2246 id: next_entry_id.fetch_add(1, SeqCst),
2247 kind: if metadata.is_dir {
2248 EntryKind::PendingDir
2249 } else {
2250 EntryKind::File(char_bag_for_path(root_char_bag, &path))
2251 },
2252 path,
2253 inode: metadata.inode,
2254 mtime: metadata.mtime,
2255 is_symlink: metadata.is_symlink,
2256 is_ignored: false,
2257 }
2258 }
2259
2260 pub fn is_dir(&self) -> bool {
2261 matches!(self.kind, EntryKind::Dir | EntryKind::PendingDir)
2262 }
2263
2264 pub fn is_file(&self) -> bool {
2265 matches!(self.kind, EntryKind::File(_))
2266 }
2267}
2268
2269impl sum_tree::Item for Entry {
2270 type Summary = EntrySummary;
2271
2272 fn summary(&self) -> Self::Summary {
2273 let visible_count = if self.is_ignored { 0 } else { 1 };
2274 let file_count;
2275 let visible_file_count;
2276 if self.is_file() {
2277 file_count = 1;
2278 visible_file_count = visible_count;
2279 } else {
2280 file_count = 0;
2281 visible_file_count = 0;
2282 }
2283
2284 EntrySummary {
2285 max_path: self.path.clone(),
2286 count: 1,
2287 visible_count,
2288 file_count,
2289 visible_file_count,
2290 }
2291 }
2292}
2293
2294impl sum_tree::KeyedItem for Entry {
2295 type Key = PathKey;
2296
2297 fn key(&self) -> Self::Key {
2298 PathKey(self.path.clone())
2299 }
2300}
2301
2302#[derive(Clone, Debug)]
2303pub struct EntrySummary {
2304 max_path: Arc<Path>,
2305 count: usize,
2306 visible_count: usize,
2307 file_count: usize,
2308 visible_file_count: usize,
2309}
2310
2311impl Default for EntrySummary {
2312 fn default() -> Self {
2313 Self {
2314 max_path: Arc::from(Path::new("")),
2315 count: 0,
2316 visible_count: 0,
2317 file_count: 0,
2318 visible_file_count: 0,
2319 }
2320 }
2321}
2322
2323impl sum_tree::Summary for EntrySummary {
2324 type Context = ();
2325
2326 fn add_summary(&mut self, rhs: &Self, _: &()) {
2327 self.max_path = rhs.max_path.clone();
2328 self.visible_count += rhs.visible_count;
2329 self.file_count += rhs.file_count;
2330 self.visible_file_count += rhs.visible_file_count;
2331 }
2332}
2333
2334#[derive(Clone, Debug)]
2335struct PathEntry {
2336 id: usize,
2337 path: Arc<Path>,
2338 is_ignored: bool,
2339 scan_id: usize,
2340}
2341
2342impl sum_tree::Item for PathEntry {
2343 type Summary = PathEntrySummary;
2344
2345 fn summary(&self) -> Self::Summary {
2346 PathEntrySummary { max_id: self.id }
2347 }
2348}
2349
2350impl sum_tree::KeyedItem for PathEntry {
2351 type Key = usize;
2352
2353 fn key(&self) -> Self::Key {
2354 self.id
2355 }
2356}
2357
2358#[derive(Clone, Debug, Default)]
2359struct PathEntrySummary {
2360 max_id: usize,
2361}
2362
2363impl sum_tree::Summary for PathEntrySummary {
2364 type Context = ();
2365
2366 fn add_summary(&mut self, summary: &Self, _: &Self::Context) {
2367 self.max_id = summary.max_id;
2368 }
2369}
2370
2371impl<'a> sum_tree::Dimension<'a, PathEntrySummary> for usize {
2372 fn add_summary(&mut self, summary: &'a PathEntrySummary, _: &()) {
2373 *self = summary.max_id;
2374 }
2375}
2376
2377#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
2378pub struct PathKey(Arc<Path>);
2379
2380impl Default for PathKey {
2381 fn default() -> Self {
2382 Self(Path::new("").into())
2383 }
2384}
2385
2386impl<'a> sum_tree::Dimension<'a, EntrySummary> for PathKey {
2387 fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
2388 self.0 = summary.max_path.clone();
2389 }
2390}
2391
2392struct BackgroundScanner {
2393 fs: Arc<dyn Fs>,
2394 snapshot: Arc<Mutex<Snapshot>>,
2395 notify: Sender<ScanState>,
2396 executor: Arc<executor::Background>,
2397}
2398
2399impl BackgroundScanner {
2400 fn new(
2401 snapshot: Arc<Mutex<Snapshot>>,
2402 notify: Sender<ScanState>,
2403 fs: Arc<dyn Fs>,
2404 executor: Arc<executor::Background>,
2405 ) -> Self {
2406 Self {
2407 fs,
2408 snapshot,
2409 notify,
2410 executor,
2411 }
2412 }
2413
2414 fn abs_path(&self) -> Arc<Path> {
2415 self.snapshot.lock().abs_path.clone()
2416 }
2417
2418 fn snapshot(&self) -> Snapshot {
2419 self.snapshot.lock().clone()
2420 }
2421
2422 async fn run(mut self, events_rx: impl Stream<Item = Vec<fsevent::Event>>) {
2423 if self.notify.send(ScanState::Scanning).await.is_err() {
2424 return;
2425 }
2426
2427 if let Err(err) = self.scan_dirs().await {
2428 if self
2429 .notify
2430 .send(ScanState::Err(Arc::new(err)))
2431 .await
2432 .is_err()
2433 {
2434 return;
2435 }
2436 }
2437
2438 if self.notify.send(ScanState::Idle).await.is_err() {
2439 return;
2440 }
2441
2442 futures::pin_mut!(events_rx);
2443 while let Some(events) = events_rx.next().await {
2444 if self.notify.send(ScanState::Scanning).await.is_err() {
2445 break;
2446 }
2447
2448 if !self.process_events(events).await {
2449 break;
2450 }
2451
2452 if self.notify.send(ScanState::Idle).await.is_err() {
2453 break;
2454 }
2455 }
2456 }
2457
2458 async fn scan_dirs(&mut self) -> Result<()> {
2459 let root_char_bag;
2460 let next_entry_id;
2461 let is_dir;
2462 {
2463 let snapshot = self.snapshot.lock();
2464 root_char_bag = snapshot.root_char_bag;
2465 next_entry_id = snapshot.next_entry_id.clone();
2466 is_dir = snapshot.root_entry().map_or(false, |e| e.is_dir())
2467 };
2468
2469 if is_dir {
2470 let path: Arc<Path> = Arc::from(Path::new(""));
2471 let abs_path = self.abs_path();
2472 let (tx, rx) = channel::unbounded();
2473 tx.send(ScanJob {
2474 abs_path: abs_path.to_path_buf(),
2475 path,
2476 ignore_stack: IgnoreStack::none(),
2477 scan_queue: tx.clone(),
2478 })
2479 .await
2480 .unwrap();
2481 drop(tx);
2482
2483 self.executor
2484 .scoped(|scope| {
2485 for _ in 0..self.executor.num_cpus() {
2486 scope.spawn(async {
2487 while let Ok(job) = rx.recv().await {
2488 if let Err(err) = self
2489 .scan_dir(root_char_bag, next_entry_id.clone(), &job)
2490 .await
2491 {
2492 log::error!("error scanning {:?}: {}", job.abs_path, err);
2493 }
2494 }
2495 });
2496 }
2497 })
2498 .await;
2499 }
2500
2501 Ok(())
2502 }
2503
2504 async fn scan_dir(
2505 &self,
2506 root_char_bag: CharBag,
2507 next_entry_id: Arc<AtomicUsize>,
2508 job: &ScanJob,
2509 ) -> Result<()> {
2510 let mut new_entries: Vec<Entry> = Vec::new();
2511 let mut new_jobs: Vec<ScanJob> = Vec::new();
2512 let mut ignore_stack = job.ignore_stack.clone();
2513 let mut new_ignore = None;
2514
2515 let mut child_paths = self.fs.read_dir(&job.abs_path).await?;
2516 while let Some(child_abs_path) = child_paths.next().await {
2517 let child_abs_path = match child_abs_path {
2518 Ok(child_abs_path) => child_abs_path,
2519 Err(error) => {
2520 log::error!("error processing entry {:?}", error);
2521 continue;
2522 }
2523 };
2524 let child_name = child_abs_path.file_name().unwrap();
2525 let child_path: Arc<Path> = job.path.join(child_name).into();
2526 let child_metadata = match self.fs.metadata(&child_abs_path).await? {
2527 Some(metadata) => metadata,
2528 None => continue,
2529 };
2530
2531 // If we find a .gitignore, add it to the stack of ignores used to determine which paths are ignored
2532 if child_name == *GITIGNORE {
2533 match build_gitignore(&child_abs_path, self.fs.as_ref()) {
2534 Ok(ignore) => {
2535 let ignore = Arc::new(ignore);
2536 ignore_stack = ignore_stack.append(job.path.clone(), ignore.clone());
2537 new_ignore = Some(ignore);
2538 }
2539 Err(error) => {
2540 log::error!(
2541 "error loading .gitignore file {:?} - {:?}",
2542 child_name,
2543 error
2544 );
2545 }
2546 }
2547
2548 // Update ignore status of any child entries we've already processed to reflect the
2549 // ignore file in the current directory. Because `.gitignore` starts with a `.`,
2550 // there should rarely be too numerous. Update the ignore stack associated with any
2551 // new jobs as well.
2552 let mut new_jobs = new_jobs.iter_mut();
2553 for entry in &mut new_entries {
2554 entry.is_ignored = ignore_stack.is_path_ignored(&entry.path, entry.is_dir());
2555 if entry.is_dir() {
2556 new_jobs.next().unwrap().ignore_stack = if entry.is_ignored {
2557 IgnoreStack::all()
2558 } else {
2559 ignore_stack.clone()
2560 };
2561 }
2562 }
2563 }
2564
2565 let mut child_entry = Entry::new(
2566 child_path.clone(),
2567 &child_metadata,
2568 &next_entry_id,
2569 root_char_bag,
2570 );
2571
2572 if child_metadata.is_dir {
2573 let is_ignored = ignore_stack.is_path_ignored(&child_path, true);
2574 child_entry.is_ignored = is_ignored;
2575 new_entries.push(child_entry);
2576 new_jobs.push(ScanJob {
2577 abs_path: child_abs_path,
2578 path: child_path,
2579 ignore_stack: if is_ignored {
2580 IgnoreStack::all()
2581 } else {
2582 ignore_stack.clone()
2583 },
2584 scan_queue: job.scan_queue.clone(),
2585 });
2586 } else {
2587 child_entry.is_ignored = ignore_stack.is_path_ignored(&child_path, false);
2588 new_entries.push(child_entry);
2589 };
2590 }
2591
2592 self.snapshot
2593 .lock()
2594 .populate_dir(job.path.clone(), new_entries, new_ignore);
2595 for new_job in new_jobs {
2596 job.scan_queue.send(new_job).await.unwrap();
2597 }
2598
2599 Ok(())
2600 }
2601
2602 async fn process_events(&mut self, mut events: Vec<fsevent::Event>) -> bool {
2603 let mut snapshot = self.snapshot();
2604 snapshot.scan_id += 1;
2605
2606 let root_abs_path = if let Ok(abs_path) = self.fs.canonicalize(&snapshot.abs_path).await {
2607 abs_path
2608 } else {
2609 return false;
2610 };
2611 let root_char_bag = snapshot.root_char_bag;
2612 let next_entry_id = snapshot.next_entry_id.clone();
2613
2614 events.sort_unstable_by(|a, b| a.path.cmp(&b.path));
2615 events.dedup_by(|a, b| a.path.starts_with(&b.path));
2616
2617 for event in &events {
2618 match event.path.strip_prefix(&root_abs_path) {
2619 Ok(path) => snapshot.remove_path(&path),
2620 Err(_) => {
2621 log::error!(
2622 "unexpected event {:?} for root path {:?}",
2623 event.path,
2624 root_abs_path
2625 );
2626 continue;
2627 }
2628 }
2629 }
2630
2631 let (scan_queue_tx, scan_queue_rx) = channel::unbounded();
2632 for event in events {
2633 let path: Arc<Path> = match event.path.strip_prefix(&root_abs_path) {
2634 Ok(path) => Arc::from(path.to_path_buf()),
2635 Err(_) => {
2636 log::error!(
2637 "unexpected event {:?} for root path {:?}",
2638 event.path,
2639 root_abs_path
2640 );
2641 continue;
2642 }
2643 };
2644
2645 match self.fs.metadata(&event.path).await {
2646 Ok(Some(metadata)) => {
2647 let ignore_stack = snapshot.ignore_stack_for_path(&path, metadata.is_dir);
2648 let mut fs_entry = Entry::new(
2649 path.clone(),
2650 &metadata,
2651 snapshot.next_entry_id.as_ref(),
2652 snapshot.root_char_bag,
2653 );
2654 fs_entry.is_ignored = ignore_stack.is_all();
2655 snapshot.insert_entry(fs_entry, self.fs.as_ref());
2656 if metadata.is_dir {
2657 scan_queue_tx
2658 .send(ScanJob {
2659 abs_path: event.path,
2660 path,
2661 ignore_stack,
2662 scan_queue: scan_queue_tx.clone(),
2663 })
2664 .await
2665 .unwrap();
2666 }
2667 }
2668 Ok(None) => {}
2669 Err(err) => {
2670 // TODO - create a special 'error' entry in the entries tree to mark this
2671 log::error!("error reading file on event {:?}", err);
2672 }
2673 }
2674 }
2675
2676 *self.snapshot.lock() = snapshot;
2677
2678 // Scan any directories that were created as part of this event batch.
2679 drop(scan_queue_tx);
2680 self.executor
2681 .scoped(|scope| {
2682 for _ in 0..self.executor.num_cpus() {
2683 scope.spawn(async {
2684 while let Ok(job) = scan_queue_rx.recv().await {
2685 if let Err(err) = self
2686 .scan_dir(root_char_bag, next_entry_id.clone(), &job)
2687 .await
2688 {
2689 log::error!("error scanning {:?}: {}", job.abs_path, err);
2690 }
2691 }
2692 });
2693 }
2694 })
2695 .await;
2696
2697 // Attempt to detect renames only over a single batch of file-system events.
2698 self.snapshot.lock().removed_entry_ids.clear();
2699
2700 self.update_ignore_statuses().await;
2701 true
2702 }
2703
2704 async fn update_ignore_statuses(&self) {
2705 let mut snapshot = self.snapshot();
2706
2707 let mut ignores_to_update = Vec::new();
2708 let mut ignores_to_delete = Vec::new();
2709 for (parent_path, (_, scan_id)) in &snapshot.ignores {
2710 if *scan_id == snapshot.scan_id && snapshot.entry_for_path(parent_path).is_some() {
2711 ignores_to_update.push(parent_path.clone());
2712 }
2713
2714 let ignore_path = parent_path.join(&*GITIGNORE);
2715 if snapshot.entry_for_path(ignore_path).is_none() {
2716 ignores_to_delete.push(parent_path.clone());
2717 }
2718 }
2719
2720 for parent_path in ignores_to_delete {
2721 snapshot.ignores.remove(&parent_path);
2722 self.snapshot.lock().ignores.remove(&parent_path);
2723 }
2724
2725 let (ignore_queue_tx, ignore_queue_rx) = channel::unbounded();
2726 ignores_to_update.sort_unstable();
2727 let mut ignores_to_update = ignores_to_update.into_iter().peekable();
2728 while let Some(parent_path) = ignores_to_update.next() {
2729 while ignores_to_update
2730 .peek()
2731 .map_or(false, |p| p.starts_with(&parent_path))
2732 {
2733 ignores_to_update.next().unwrap();
2734 }
2735
2736 let ignore_stack = snapshot.ignore_stack_for_path(&parent_path, true);
2737 ignore_queue_tx
2738 .send(UpdateIgnoreStatusJob {
2739 path: parent_path,
2740 ignore_stack,
2741 ignore_queue: ignore_queue_tx.clone(),
2742 })
2743 .await
2744 .unwrap();
2745 }
2746 drop(ignore_queue_tx);
2747
2748 self.executor
2749 .scoped(|scope| {
2750 for _ in 0..self.executor.num_cpus() {
2751 scope.spawn(async {
2752 while let Ok(job) = ignore_queue_rx.recv().await {
2753 self.update_ignore_status(job, &snapshot).await;
2754 }
2755 });
2756 }
2757 })
2758 .await;
2759 }
2760
2761 async fn update_ignore_status(&self, job: UpdateIgnoreStatusJob, snapshot: &Snapshot) {
2762 let mut ignore_stack = job.ignore_stack;
2763 if let Some((ignore, _)) = snapshot.ignores.get(&job.path) {
2764 ignore_stack = ignore_stack.append(job.path.clone(), ignore.clone());
2765 }
2766
2767 let mut entries_by_id_edits = Vec::new();
2768 let mut entries_by_path_edits = Vec::new();
2769 for mut entry in snapshot.child_entries(&job.path).cloned() {
2770 let was_ignored = entry.is_ignored;
2771 entry.is_ignored = ignore_stack.is_path_ignored(&entry.path, entry.is_dir());
2772 if entry.is_dir() {
2773 let child_ignore_stack = if entry.is_ignored {
2774 IgnoreStack::all()
2775 } else {
2776 ignore_stack.clone()
2777 };
2778 job.ignore_queue
2779 .send(UpdateIgnoreStatusJob {
2780 path: entry.path.clone(),
2781 ignore_stack: child_ignore_stack,
2782 ignore_queue: job.ignore_queue.clone(),
2783 })
2784 .await
2785 .unwrap();
2786 }
2787
2788 if entry.is_ignored != was_ignored {
2789 let mut path_entry = snapshot.entries_by_id.get(&entry.id, &()).unwrap().clone();
2790 path_entry.scan_id = snapshot.scan_id;
2791 path_entry.is_ignored = entry.is_ignored;
2792 entries_by_id_edits.push(Edit::Insert(path_entry));
2793 entries_by_path_edits.push(Edit::Insert(entry));
2794 }
2795 }
2796
2797 let mut snapshot = self.snapshot.lock();
2798 snapshot.entries_by_path.edit(entries_by_path_edits, &());
2799 snapshot.entries_by_id.edit(entries_by_id_edits, &());
2800 }
2801}
2802
2803async fn refresh_entry(
2804 fs: &dyn Fs,
2805 snapshot: &Mutex<Snapshot>,
2806 path: Arc<Path>,
2807 abs_path: &Path,
2808) -> Result<Entry> {
2809 let root_char_bag;
2810 let next_entry_id;
2811 {
2812 let snapshot = snapshot.lock();
2813 root_char_bag = snapshot.root_char_bag;
2814 next_entry_id = snapshot.next_entry_id.clone();
2815 }
2816 let entry = Entry::new(
2817 path,
2818 &fs.metadata(abs_path)
2819 .await?
2820 .ok_or_else(|| anyhow!("could not read saved file metadata"))?,
2821 &next_entry_id,
2822 root_char_bag,
2823 );
2824 Ok(snapshot.lock().insert_entry(entry, fs))
2825}
2826
2827fn char_bag_for_path(root_char_bag: CharBag, path: &Path) -> CharBag {
2828 let mut result = root_char_bag;
2829 result.extend(
2830 path.to_string_lossy()
2831 .chars()
2832 .map(|c| c.to_ascii_lowercase()),
2833 );
2834 result
2835}
2836
2837struct ScanJob {
2838 abs_path: PathBuf,
2839 path: Arc<Path>,
2840 ignore_stack: Arc<IgnoreStack>,
2841 scan_queue: Sender<ScanJob>,
2842}
2843
2844struct UpdateIgnoreStatusJob {
2845 path: Arc<Path>,
2846 ignore_stack: Arc<IgnoreStack>,
2847 ignore_queue: Sender<UpdateIgnoreStatusJob>,
2848}
2849
2850pub trait WorktreeHandle {
2851 #[cfg(test)]
2852 fn flush_fs_events<'a>(
2853 &self,
2854 cx: &'a gpui::TestAppContext,
2855 ) -> futures::future::LocalBoxFuture<'a, ()>;
2856}
2857
2858impl WorktreeHandle for ModelHandle<Worktree> {
2859 // When the worktree's FS event stream sometimes delivers "redundant" events for FS changes that
2860 // occurred before the worktree was constructed. These events can cause the worktree to perfrom
2861 // extra directory scans, and emit extra scan-state notifications.
2862 //
2863 // This function mutates the worktree's directory and waits for those mutations to be picked up,
2864 // to ensure that all redundant FS events have already been processed.
2865 #[cfg(test)]
2866 fn flush_fs_events<'a>(
2867 &self,
2868 cx: &'a gpui::TestAppContext,
2869 ) -> futures::future::LocalBoxFuture<'a, ()> {
2870 use smol::future::FutureExt;
2871
2872 let filename = "fs-event-sentinel";
2873 let root_path = cx.read(|cx| self.read(cx).abs_path.clone());
2874 let tree = self.clone();
2875 async move {
2876 std::fs::write(root_path.join(filename), "").unwrap();
2877 tree.condition(&cx, |tree, _| tree.entry_for_path(filename).is_some())
2878 .await;
2879
2880 std::fs::remove_file(root_path.join(filename)).unwrap();
2881 tree.condition(&cx, |tree, _| tree.entry_for_path(filename).is_none())
2882 .await;
2883
2884 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2885 .await;
2886 }
2887 .boxed_local()
2888 }
2889}
2890
2891#[derive(Clone, Debug)]
2892struct TraversalProgress<'a> {
2893 max_path: &'a Path,
2894 count: usize,
2895 visible_count: usize,
2896 file_count: usize,
2897 visible_file_count: usize,
2898}
2899
2900impl<'a> TraversalProgress<'a> {
2901 fn count(&self, include_dirs: bool, include_ignored: bool) -> usize {
2902 match (include_ignored, include_dirs) {
2903 (true, true) => self.count,
2904 (true, false) => self.file_count,
2905 (false, true) => self.visible_count,
2906 (false, false) => self.visible_file_count,
2907 }
2908 }
2909}
2910
2911impl<'a> sum_tree::Dimension<'a, EntrySummary> for TraversalProgress<'a> {
2912 fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
2913 self.max_path = summary.max_path.as_ref();
2914 self.count += summary.count;
2915 self.visible_count += summary.visible_count;
2916 self.file_count += summary.file_count;
2917 self.visible_file_count += summary.visible_file_count;
2918 }
2919}
2920
2921impl<'a> Default for TraversalProgress<'a> {
2922 fn default() -> Self {
2923 Self {
2924 max_path: Path::new(""),
2925 count: 0,
2926 visible_count: 0,
2927 file_count: 0,
2928 visible_file_count: 0,
2929 }
2930 }
2931}
2932
2933pub struct Traversal<'a> {
2934 cursor: sum_tree::Cursor<'a, Entry, TraversalProgress<'a>>,
2935 include_ignored: bool,
2936 include_dirs: bool,
2937}
2938
2939impl<'a> Traversal<'a> {
2940 pub fn advance(&mut self) -> bool {
2941 self.advance_to_offset(self.offset() + 1)
2942 }
2943
2944 pub fn advance_to_offset(&mut self, offset: usize) -> bool {
2945 self.cursor.seek_forward(
2946 &TraversalTarget::Count {
2947 count: offset,
2948 include_dirs: self.include_dirs,
2949 include_ignored: self.include_ignored,
2950 },
2951 Bias::Right,
2952 &(),
2953 )
2954 }
2955
2956 pub fn advance_to_sibling(&mut self) -> bool {
2957 while let Some(entry) = self.cursor.item() {
2958 self.cursor.seek_forward(
2959 &TraversalTarget::PathSuccessor(&entry.path),
2960 Bias::Left,
2961 &(),
2962 );
2963 if let Some(entry) = self.cursor.item() {
2964 if (self.include_dirs || !entry.is_dir())
2965 && (self.include_ignored || !entry.is_ignored)
2966 {
2967 return true;
2968 }
2969 }
2970 }
2971 false
2972 }
2973
2974 pub fn entry(&self) -> Option<&'a Entry> {
2975 self.cursor.item()
2976 }
2977
2978 pub fn offset(&self) -> usize {
2979 self.cursor
2980 .start()
2981 .count(self.include_dirs, self.include_ignored)
2982 }
2983}
2984
2985impl<'a> Iterator for Traversal<'a> {
2986 type Item = &'a Entry;
2987
2988 fn next(&mut self) -> Option<Self::Item> {
2989 if let Some(item) = self.entry() {
2990 self.advance();
2991 Some(item)
2992 } else {
2993 None
2994 }
2995 }
2996}
2997
2998#[derive(Debug)]
2999enum TraversalTarget<'a> {
3000 Path(&'a Path),
3001 PathSuccessor(&'a Path),
3002 Count {
3003 count: usize,
3004 include_ignored: bool,
3005 include_dirs: bool,
3006 },
3007}
3008
3009impl<'a, 'b> SeekTarget<'a, EntrySummary, TraversalProgress<'a>> for TraversalTarget<'b> {
3010 fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: &()) -> Ordering {
3011 match self {
3012 TraversalTarget::Path(path) => path.cmp(&cursor_location.max_path),
3013 TraversalTarget::PathSuccessor(path) => {
3014 if !cursor_location.max_path.starts_with(path) {
3015 Ordering::Equal
3016 } else {
3017 Ordering::Greater
3018 }
3019 }
3020 TraversalTarget::Count {
3021 count,
3022 include_dirs,
3023 include_ignored,
3024 } => Ord::cmp(
3025 count,
3026 &cursor_location.count(*include_dirs, *include_ignored),
3027 ),
3028 }
3029 }
3030}
3031
3032struct ChildEntriesIter<'a> {
3033 parent_path: &'a Path,
3034 traversal: Traversal<'a>,
3035}
3036
3037impl<'a> Iterator for ChildEntriesIter<'a> {
3038 type Item = &'a Entry;
3039
3040 fn next(&mut self) -> Option<Self::Item> {
3041 if let Some(item) = self.traversal.entry() {
3042 if item.path.starts_with(&self.parent_path) {
3043 self.traversal.advance_to_sibling();
3044 return Some(item);
3045 }
3046 }
3047 None
3048 }
3049}
3050
3051impl<'a> From<&'a Entry> for proto::Entry {
3052 fn from(entry: &'a Entry) -> Self {
3053 Self {
3054 id: entry.id as u64,
3055 is_dir: entry.is_dir(),
3056 path: entry.path.to_string_lossy().to_string(),
3057 inode: entry.inode,
3058 mtime: Some(entry.mtime.into()),
3059 is_symlink: entry.is_symlink,
3060 is_ignored: entry.is_ignored,
3061 }
3062 }
3063}
3064
3065impl<'a> TryFrom<(&'a CharBag, proto::Entry)> for Entry {
3066 type Error = anyhow::Error;
3067
3068 fn try_from((root_char_bag, entry): (&'a CharBag, proto::Entry)) -> Result<Self> {
3069 if let Some(mtime) = entry.mtime {
3070 let kind = if entry.is_dir {
3071 EntryKind::Dir
3072 } else {
3073 let mut char_bag = root_char_bag.clone();
3074 char_bag.extend(entry.path.chars().map(|c| c.to_ascii_lowercase()));
3075 EntryKind::File(char_bag)
3076 };
3077 let path: Arc<Path> = Arc::from(Path::new(&entry.path));
3078 Ok(Entry {
3079 id: entry.id as usize,
3080 kind,
3081 path: path.clone(),
3082 inode: entry.inode,
3083 mtime: mtime.into(),
3084 is_symlink: entry.is_symlink,
3085 is_ignored: entry.is_ignored,
3086 })
3087 } else {
3088 Err(anyhow!(
3089 "missing mtime in remote worktree entry {:?}",
3090 entry.path
3091 ))
3092 }
3093 }
3094}
3095
3096trait ToPointUtf16 {
3097 fn to_point_utf16(self) -> PointUtf16;
3098}
3099
3100impl ToPointUtf16 for lsp::Position {
3101 fn to_point_utf16(self) -> PointUtf16 {
3102 PointUtf16::new(self.line, self.character)
3103 }
3104}
3105
3106fn diagnostic_ranges<'a>(
3107 diagnostic: &'a lsp::Diagnostic,
3108 abs_path: &'a Path,
3109) -> impl 'a + Iterator<Item = Range<PointUtf16>> {
3110 diagnostic
3111 .related_information
3112 .iter()
3113 .flatten()
3114 .filter_map(move |info| {
3115 if info.location.uri.to_file_path().ok()? == abs_path {
3116 let info_start = PointUtf16::new(
3117 info.location.range.start.line,
3118 info.location.range.start.character,
3119 );
3120 let info_end = PointUtf16::new(
3121 info.location.range.end.line,
3122 info.location.range.end.character,
3123 );
3124 Some(info_start..info_end)
3125 } else {
3126 None
3127 }
3128 })
3129 .chain(Some(
3130 diagnostic.range.start.to_point_utf16()..diagnostic.range.end.to_point_utf16(),
3131 ))
3132}
3133
3134#[cfg(test)]
3135mod tests {
3136 use super::*;
3137 use crate::fs::FakeFs;
3138 use anyhow::Result;
3139 use client::test::{FakeHttpClient, FakeServer};
3140 use fs::RealFs;
3141 use gpui::test::subscribe;
3142 use language::{tree_sitter_rust, DiagnosticEntry, LanguageServerConfig};
3143 use language::{Diagnostic, LanguageConfig};
3144 use lsp::Url;
3145 use rand::prelude::*;
3146 use serde_json::json;
3147 use std::{cell::RefCell, rc::Rc};
3148 use std::{
3149 env,
3150 fmt::Write,
3151 time::{SystemTime, UNIX_EPOCH},
3152 };
3153 use text::Point;
3154 use unindent::Unindent as _;
3155 use util::test::temp_tree;
3156
3157 #[gpui::test]
3158 async fn test_traversal(mut cx: gpui::TestAppContext) {
3159 let fs = FakeFs::new();
3160 fs.insert_tree(
3161 "/root",
3162 json!({
3163 ".gitignore": "a/b\n",
3164 "a": {
3165 "b": "",
3166 "c": "",
3167 }
3168 }),
3169 )
3170 .await;
3171
3172 let http_client = FakeHttpClient::with_404_response();
3173 let client = Client::new(http_client.clone());
3174 let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http_client, cx));
3175
3176 let tree = Worktree::open_local(
3177 client,
3178 user_store,
3179 Arc::from(Path::new("/root")),
3180 Arc::new(fs),
3181 Default::default(),
3182 &mut cx.to_async(),
3183 )
3184 .await
3185 .unwrap();
3186 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3187 .await;
3188
3189 tree.read_with(&cx, |tree, _| {
3190 assert_eq!(
3191 tree.entries(false)
3192 .map(|entry| entry.path.as_ref())
3193 .collect::<Vec<_>>(),
3194 vec![
3195 Path::new(""),
3196 Path::new(".gitignore"),
3197 Path::new("a"),
3198 Path::new("a/c"),
3199 ]
3200 );
3201 })
3202 }
3203
3204 #[gpui::test]
3205 async fn test_save_file(mut cx: gpui::TestAppContext) {
3206 let dir = temp_tree(json!({
3207 "file1": "the old contents",
3208 }));
3209
3210 let http_client = FakeHttpClient::with_404_response();
3211 let client = Client::new(http_client.clone());
3212 let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http_client, cx));
3213
3214 let tree = Worktree::open_local(
3215 client,
3216 user_store,
3217 dir.path(),
3218 Arc::new(RealFs),
3219 Default::default(),
3220 &mut cx.to_async(),
3221 )
3222 .await
3223 .unwrap();
3224 let buffer = tree
3225 .update(&mut cx, |tree, cx| tree.open_buffer("file1", cx))
3226 .await
3227 .unwrap();
3228 let save = buffer.update(&mut cx, |buffer, cx| {
3229 buffer.edit(Some(0..0), "a line of text.\n".repeat(10 * 1024), cx);
3230 buffer.save(cx).unwrap()
3231 });
3232 save.await.unwrap();
3233
3234 let new_text = std::fs::read_to_string(dir.path().join("file1")).unwrap();
3235 assert_eq!(new_text, buffer.read_with(&cx, |buffer, _| buffer.text()));
3236 }
3237
3238 #[gpui::test]
3239 async fn test_save_in_single_file_worktree(mut cx: gpui::TestAppContext) {
3240 let dir = temp_tree(json!({
3241 "file1": "the old contents",
3242 }));
3243 let file_path = dir.path().join("file1");
3244
3245 let http_client = FakeHttpClient::with_404_response();
3246 let client = Client::new(http_client.clone());
3247 let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http_client, cx));
3248
3249 let tree = Worktree::open_local(
3250 client,
3251 user_store,
3252 file_path.clone(),
3253 Arc::new(RealFs),
3254 Default::default(),
3255 &mut cx.to_async(),
3256 )
3257 .await
3258 .unwrap();
3259 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3260 .await;
3261 cx.read(|cx| assert_eq!(tree.read(cx).file_count(), 1));
3262
3263 let buffer = tree
3264 .update(&mut cx, |tree, cx| tree.open_buffer("", cx))
3265 .await
3266 .unwrap();
3267 let save = buffer.update(&mut cx, |buffer, cx| {
3268 buffer.edit(Some(0..0), "a line of text.\n".repeat(10 * 1024), cx);
3269 buffer.save(cx).unwrap()
3270 });
3271 save.await.unwrap();
3272
3273 let new_text = std::fs::read_to_string(file_path).unwrap();
3274 assert_eq!(new_text, buffer.read_with(&cx, |buffer, _| buffer.text()));
3275 }
3276
3277 #[gpui::test]
3278 async fn test_rescan_and_remote_updates(mut cx: gpui::TestAppContext) {
3279 let dir = temp_tree(json!({
3280 "a": {
3281 "file1": "",
3282 "file2": "",
3283 "file3": "",
3284 },
3285 "b": {
3286 "c": {
3287 "file4": "",
3288 "file5": "",
3289 }
3290 }
3291 }));
3292
3293 let user_id = 5;
3294 let http_client = FakeHttpClient::with_404_response();
3295 let mut client = Client::new(http_client.clone());
3296 let server = FakeServer::for_client(user_id, &mut client, &cx).await;
3297 let user_store = server.build_user_store(client.clone(), &mut cx).await;
3298 let tree = Worktree::open_local(
3299 client,
3300 user_store.clone(),
3301 dir.path(),
3302 Arc::new(RealFs),
3303 Default::default(),
3304 &mut cx.to_async(),
3305 )
3306 .await
3307 .unwrap();
3308
3309 let buffer_for_path = |path: &'static str, cx: &mut gpui::TestAppContext| {
3310 let buffer = tree.update(cx, |tree, cx| tree.open_buffer(path, cx));
3311 async move { buffer.await.unwrap() }
3312 };
3313 let id_for_path = |path: &'static str, cx: &gpui::TestAppContext| {
3314 tree.read_with(cx, |tree, _| {
3315 tree.entry_for_path(path)
3316 .expect(&format!("no entry for path {}", path))
3317 .id
3318 })
3319 };
3320
3321 let buffer2 = buffer_for_path("a/file2", &mut cx).await;
3322 let buffer3 = buffer_for_path("a/file3", &mut cx).await;
3323 let buffer4 = buffer_for_path("b/c/file4", &mut cx).await;
3324 let buffer5 = buffer_for_path("b/c/file5", &mut cx).await;
3325
3326 let file2_id = id_for_path("a/file2", &cx);
3327 let file3_id = id_for_path("a/file3", &cx);
3328 let file4_id = id_for_path("b/c/file4", &cx);
3329
3330 // Wait for the initial scan.
3331 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3332 .await;
3333
3334 // Create a remote copy of this worktree.
3335 let initial_snapshot = tree.read_with(&cx, |tree, _| tree.snapshot());
3336 let remote = Worktree::remote(
3337 1,
3338 1,
3339 initial_snapshot.to_proto(),
3340 Client::new(http_client.clone()),
3341 user_store,
3342 Default::default(),
3343 &mut cx.to_async(),
3344 )
3345 .await
3346 .unwrap();
3347
3348 cx.read(|cx| {
3349 assert!(!buffer2.read(cx).is_dirty());
3350 assert!(!buffer3.read(cx).is_dirty());
3351 assert!(!buffer4.read(cx).is_dirty());
3352 assert!(!buffer5.read(cx).is_dirty());
3353 });
3354
3355 // Rename and delete files and directories.
3356 tree.flush_fs_events(&cx).await;
3357 std::fs::rename(dir.path().join("a/file3"), dir.path().join("b/c/file3")).unwrap();
3358 std::fs::remove_file(dir.path().join("b/c/file5")).unwrap();
3359 std::fs::rename(dir.path().join("b/c"), dir.path().join("d")).unwrap();
3360 std::fs::rename(dir.path().join("a/file2"), dir.path().join("a/file2.new")).unwrap();
3361 tree.flush_fs_events(&cx).await;
3362
3363 let expected_paths = vec![
3364 "a",
3365 "a/file1",
3366 "a/file2.new",
3367 "b",
3368 "d",
3369 "d/file3",
3370 "d/file4",
3371 ];
3372
3373 cx.read(|app| {
3374 assert_eq!(
3375 tree.read(app)
3376 .paths()
3377 .map(|p| p.to_str().unwrap())
3378 .collect::<Vec<_>>(),
3379 expected_paths
3380 );
3381
3382 assert_eq!(id_for_path("a/file2.new", &cx), file2_id);
3383 assert_eq!(id_for_path("d/file3", &cx), file3_id);
3384 assert_eq!(id_for_path("d/file4", &cx), file4_id);
3385
3386 assert_eq!(
3387 buffer2.read(app).file().unwrap().path().as_ref(),
3388 Path::new("a/file2.new")
3389 );
3390 assert_eq!(
3391 buffer3.read(app).file().unwrap().path().as_ref(),
3392 Path::new("d/file3")
3393 );
3394 assert_eq!(
3395 buffer4.read(app).file().unwrap().path().as_ref(),
3396 Path::new("d/file4")
3397 );
3398 assert_eq!(
3399 buffer5.read(app).file().unwrap().path().as_ref(),
3400 Path::new("b/c/file5")
3401 );
3402
3403 assert!(!buffer2.read(app).file().unwrap().is_deleted());
3404 assert!(!buffer3.read(app).file().unwrap().is_deleted());
3405 assert!(!buffer4.read(app).file().unwrap().is_deleted());
3406 assert!(buffer5.read(app).file().unwrap().is_deleted());
3407 });
3408
3409 // Update the remote worktree. Check that it becomes consistent with the
3410 // local worktree.
3411 remote.update(&mut cx, |remote, cx| {
3412 let update_message =
3413 tree.read(cx)
3414 .snapshot()
3415 .build_update(&initial_snapshot, 1, 1, true);
3416 remote
3417 .as_remote_mut()
3418 .unwrap()
3419 .snapshot
3420 .apply_update(update_message)
3421 .unwrap();
3422
3423 assert_eq!(
3424 remote
3425 .paths()
3426 .map(|p| p.to_str().unwrap())
3427 .collect::<Vec<_>>(),
3428 expected_paths
3429 );
3430 });
3431 }
3432
3433 #[gpui::test]
3434 async fn test_rescan_with_gitignore(mut cx: gpui::TestAppContext) {
3435 let dir = temp_tree(json!({
3436 ".git": {},
3437 ".gitignore": "ignored-dir\n",
3438 "tracked-dir": {
3439 "tracked-file1": "tracked contents",
3440 },
3441 "ignored-dir": {
3442 "ignored-file1": "ignored contents",
3443 }
3444 }));
3445
3446 let http_client = FakeHttpClient::with_404_response();
3447 let client = Client::new(http_client.clone());
3448 let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http_client, cx));
3449
3450 let tree = Worktree::open_local(
3451 client,
3452 user_store,
3453 dir.path(),
3454 Arc::new(RealFs),
3455 Default::default(),
3456 &mut cx.to_async(),
3457 )
3458 .await
3459 .unwrap();
3460 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3461 .await;
3462 tree.flush_fs_events(&cx).await;
3463 cx.read(|cx| {
3464 let tree = tree.read(cx);
3465 let tracked = tree.entry_for_path("tracked-dir/tracked-file1").unwrap();
3466 let ignored = tree.entry_for_path("ignored-dir/ignored-file1").unwrap();
3467 assert_eq!(tracked.is_ignored, false);
3468 assert_eq!(ignored.is_ignored, true);
3469 });
3470
3471 std::fs::write(dir.path().join("tracked-dir/tracked-file2"), "").unwrap();
3472 std::fs::write(dir.path().join("ignored-dir/ignored-file2"), "").unwrap();
3473 tree.flush_fs_events(&cx).await;
3474 cx.read(|cx| {
3475 let tree = tree.read(cx);
3476 let dot_git = tree.entry_for_path(".git").unwrap();
3477 let tracked = tree.entry_for_path("tracked-dir/tracked-file2").unwrap();
3478 let ignored = tree.entry_for_path("ignored-dir/ignored-file2").unwrap();
3479 assert_eq!(tracked.is_ignored, false);
3480 assert_eq!(ignored.is_ignored, true);
3481 assert_eq!(dot_git.is_ignored, true);
3482 });
3483 }
3484
3485 #[gpui::test]
3486 async fn test_buffer_deduping(mut cx: gpui::TestAppContext) {
3487 let user_id = 100;
3488 let http_client = FakeHttpClient::with_404_response();
3489 let mut client = Client::new(http_client);
3490 let server = FakeServer::for_client(user_id, &mut client, &cx).await;
3491 let user_store = server.build_user_store(client.clone(), &mut cx).await;
3492
3493 let fs = Arc::new(FakeFs::new());
3494 fs.insert_tree(
3495 "/the-dir",
3496 json!({
3497 "a.txt": "a-contents",
3498 "b.txt": "b-contents",
3499 }),
3500 )
3501 .await;
3502
3503 let worktree = Worktree::open_local(
3504 client.clone(),
3505 user_store,
3506 "/the-dir".as_ref(),
3507 fs,
3508 Default::default(),
3509 &mut cx.to_async(),
3510 )
3511 .await
3512 .unwrap();
3513
3514 // Spawn multiple tasks to open paths, repeating some paths.
3515 let (buffer_a_1, buffer_b, buffer_a_2) = worktree.update(&mut cx, |worktree, cx| {
3516 (
3517 worktree.open_buffer("a.txt", cx),
3518 worktree.open_buffer("b.txt", cx),
3519 worktree.open_buffer("a.txt", cx),
3520 )
3521 });
3522
3523 let buffer_a_1 = buffer_a_1.await.unwrap();
3524 let buffer_a_2 = buffer_a_2.await.unwrap();
3525 let buffer_b = buffer_b.await.unwrap();
3526 assert_eq!(buffer_a_1.read_with(&cx, |b, _| b.text()), "a-contents");
3527 assert_eq!(buffer_b.read_with(&cx, |b, _| b.text()), "b-contents");
3528
3529 // There is only one buffer per path.
3530 let buffer_a_id = buffer_a_1.id();
3531 assert_eq!(buffer_a_2.id(), buffer_a_id);
3532
3533 // Open the same path again while it is still open.
3534 drop(buffer_a_1);
3535 let buffer_a_3 = worktree
3536 .update(&mut cx, |worktree, cx| worktree.open_buffer("a.txt", cx))
3537 .await
3538 .unwrap();
3539
3540 // There's still only one buffer per path.
3541 assert_eq!(buffer_a_3.id(), buffer_a_id);
3542 }
3543
3544 #[gpui::test]
3545 async fn test_buffer_is_dirty(mut cx: gpui::TestAppContext) {
3546 use std::fs;
3547
3548 let dir = temp_tree(json!({
3549 "file1": "abc",
3550 "file2": "def",
3551 "file3": "ghi",
3552 }));
3553 let http_client = FakeHttpClient::with_404_response();
3554 let client = Client::new(http_client.clone());
3555 let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http_client, cx));
3556
3557 let tree = Worktree::open_local(
3558 client,
3559 user_store,
3560 dir.path(),
3561 Arc::new(RealFs),
3562 Default::default(),
3563 &mut cx.to_async(),
3564 )
3565 .await
3566 .unwrap();
3567 tree.flush_fs_events(&cx).await;
3568 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3569 .await;
3570
3571 let buffer1 = tree
3572 .update(&mut cx, |tree, cx| tree.open_buffer("file1", cx))
3573 .await
3574 .unwrap();
3575 let events = Rc::new(RefCell::new(Vec::new()));
3576
3577 // initially, the buffer isn't dirty.
3578 buffer1.update(&mut cx, |buffer, cx| {
3579 cx.subscribe(&buffer1, {
3580 let events = events.clone();
3581 move |_, _, event, _| events.borrow_mut().push(event.clone())
3582 })
3583 .detach();
3584
3585 assert!(!buffer.is_dirty());
3586 assert!(events.borrow().is_empty());
3587
3588 buffer.edit(vec![1..2], "", cx);
3589 });
3590
3591 // after the first edit, the buffer is dirty, and emits a dirtied event.
3592 buffer1.update(&mut cx, |buffer, cx| {
3593 assert!(buffer.text() == "ac");
3594 assert!(buffer.is_dirty());
3595 assert_eq!(
3596 *events.borrow(),
3597 &[language::Event::Edited, language::Event::Dirtied]
3598 );
3599 events.borrow_mut().clear();
3600 buffer.did_save(buffer.version(), buffer.file().unwrap().mtime(), None, cx);
3601 });
3602
3603 // after saving, the buffer is not dirty, and emits a saved event.
3604 buffer1.update(&mut cx, |buffer, cx| {
3605 assert!(!buffer.is_dirty());
3606 assert_eq!(*events.borrow(), &[language::Event::Saved]);
3607 events.borrow_mut().clear();
3608
3609 buffer.edit(vec![1..1], "B", cx);
3610 buffer.edit(vec![2..2], "D", cx);
3611 });
3612
3613 // after editing again, the buffer is dirty, and emits another dirty event.
3614 buffer1.update(&mut cx, |buffer, cx| {
3615 assert!(buffer.text() == "aBDc");
3616 assert!(buffer.is_dirty());
3617 assert_eq!(
3618 *events.borrow(),
3619 &[
3620 language::Event::Edited,
3621 language::Event::Dirtied,
3622 language::Event::Edited,
3623 ],
3624 );
3625 events.borrow_mut().clear();
3626
3627 // TODO - currently, after restoring the buffer to its
3628 // previously-saved state, the is still considered dirty.
3629 buffer.edit([1..3], "", cx);
3630 assert!(buffer.text() == "ac");
3631 assert!(buffer.is_dirty());
3632 });
3633
3634 assert_eq!(*events.borrow(), &[language::Event::Edited]);
3635
3636 // When a file is deleted, the buffer is considered dirty.
3637 let events = Rc::new(RefCell::new(Vec::new()));
3638 let buffer2 = tree
3639 .update(&mut cx, |tree, cx| tree.open_buffer("file2", cx))
3640 .await
3641 .unwrap();
3642 buffer2.update(&mut cx, |_, cx| {
3643 cx.subscribe(&buffer2, {
3644 let events = events.clone();
3645 move |_, _, event, _| events.borrow_mut().push(event.clone())
3646 })
3647 .detach();
3648 });
3649
3650 fs::remove_file(dir.path().join("file2")).unwrap();
3651 buffer2.condition(&cx, |b, _| b.is_dirty()).await;
3652 assert_eq!(
3653 *events.borrow(),
3654 &[language::Event::Dirtied, language::Event::FileHandleChanged]
3655 );
3656
3657 // When a file is already dirty when deleted, we don't emit a Dirtied event.
3658 let events = Rc::new(RefCell::new(Vec::new()));
3659 let buffer3 = tree
3660 .update(&mut cx, |tree, cx| tree.open_buffer("file3", cx))
3661 .await
3662 .unwrap();
3663 buffer3.update(&mut cx, |_, cx| {
3664 cx.subscribe(&buffer3, {
3665 let events = events.clone();
3666 move |_, _, event, _| events.borrow_mut().push(event.clone())
3667 })
3668 .detach();
3669 });
3670
3671 tree.flush_fs_events(&cx).await;
3672 buffer3.update(&mut cx, |buffer, cx| {
3673 buffer.edit(Some(0..0), "x", cx);
3674 });
3675 events.borrow_mut().clear();
3676 fs::remove_file(dir.path().join("file3")).unwrap();
3677 buffer3
3678 .condition(&cx, |_, _| !events.borrow().is_empty())
3679 .await;
3680 assert_eq!(*events.borrow(), &[language::Event::FileHandleChanged]);
3681 cx.read(|cx| assert!(buffer3.read(cx).is_dirty()));
3682 }
3683
3684 #[gpui::test]
3685 async fn test_buffer_file_changes_on_disk(mut cx: gpui::TestAppContext) {
3686 use std::fs;
3687
3688 let initial_contents = "aaa\nbbbbb\nc\n";
3689 let dir = temp_tree(json!({ "the-file": initial_contents }));
3690 let http_client = FakeHttpClient::with_404_response();
3691 let client = Client::new(http_client.clone());
3692 let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http_client, cx));
3693
3694 let tree = Worktree::open_local(
3695 client,
3696 user_store,
3697 dir.path(),
3698 Arc::new(RealFs),
3699 Default::default(),
3700 &mut cx.to_async(),
3701 )
3702 .await
3703 .unwrap();
3704 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3705 .await;
3706
3707 let abs_path = dir.path().join("the-file");
3708 let buffer = tree
3709 .update(&mut cx, |tree, cx| {
3710 tree.open_buffer(Path::new("the-file"), cx)
3711 })
3712 .await
3713 .unwrap();
3714
3715 // TODO
3716 // Add a cursor on each row.
3717 // let selection_set_id = buffer.update(&mut cx, |buffer, cx| {
3718 // assert!(!buffer.is_dirty());
3719 // buffer.add_selection_set(
3720 // &(0..3)
3721 // .map(|row| Selection {
3722 // id: row as usize,
3723 // start: Point::new(row, 1),
3724 // end: Point::new(row, 1),
3725 // reversed: false,
3726 // goal: SelectionGoal::None,
3727 // })
3728 // .collect::<Vec<_>>(),
3729 // cx,
3730 // )
3731 // });
3732
3733 // Change the file on disk, adding two new lines of text, and removing
3734 // one line.
3735 buffer.read_with(&cx, |buffer, _| {
3736 assert!(!buffer.is_dirty());
3737 assert!(!buffer.has_conflict());
3738 });
3739 let new_contents = "AAAA\naaa\nBB\nbbbbb\n";
3740 fs::write(&abs_path, new_contents).unwrap();
3741
3742 // Because the buffer was not modified, it is reloaded from disk. Its
3743 // contents are edited according to the diff between the old and new
3744 // file contents.
3745 buffer
3746 .condition(&cx, |buffer, _| buffer.text() == new_contents)
3747 .await;
3748
3749 buffer.update(&mut cx, |buffer, _| {
3750 assert_eq!(buffer.text(), new_contents);
3751 assert!(!buffer.is_dirty());
3752 assert!(!buffer.has_conflict());
3753
3754 // TODO
3755 // let cursor_positions = buffer
3756 // .selection_set(selection_set_id)
3757 // .unwrap()
3758 // .selections::<Point>(&*buffer)
3759 // .map(|selection| {
3760 // assert_eq!(selection.start, selection.end);
3761 // selection.start
3762 // })
3763 // .collect::<Vec<_>>();
3764 // assert_eq!(
3765 // cursor_positions,
3766 // [Point::new(1, 1), Point::new(3, 1), Point::new(4, 0)]
3767 // );
3768 });
3769
3770 // Modify the buffer
3771 buffer.update(&mut cx, |buffer, cx| {
3772 buffer.edit(vec![0..0], " ", cx);
3773 assert!(buffer.is_dirty());
3774 assert!(!buffer.has_conflict());
3775 });
3776
3777 // Change the file on disk again, adding blank lines to the beginning.
3778 fs::write(&abs_path, "\n\n\nAAAA\naaa\nBB\nbbbbb\n").unwrap();
3779
3780 // Because the buffer is modified, it doesn't reload from disk, but is
3781 // marked as having a conflict.
3782 buffer
3783 .condition(&cx, |buffer, _| buffer.has_conflict())
3784 .await;
3785 }
3786
3787 #[gpui::test]
3788 async fn test_language_server_diagnostics(mut cx: gpui::TestAppContext) {
3789 let (language_server_config, mut fake_server) =
3790 LanguageServerConfig::fake(cx.background()).await;
3791 let progress_token = language_server_config
3792 .disk_based_diagnostics_progress_token
3793 .clone()
3794 .unwrap();
3795 let mut languages = LanguageRegistry::new();
3796 languages.add(Arc::new(Language::new(
3797 LanguageConfig {
3798 name: "Rust".to_string(),
3799 path_suffixes: vec!["rs".to_string()],
3800 language_server: Some(language_server_config),
3801 ..Default::default()
3802 },
3803 Some(tree_sitter_rust::language()),
3804 )));
3805
3806 let dir = temp_tree(json!({
3807 "a.rs": "fn a() { A }",
3808 "b.rs": "const y: i32 = 1",
3809 }));
3810
3811 let http_client = FakeHttpClient::with_404_response();
3812 let client = Client::new(http_client.clone());
3813 let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http_client, cx));
3814
3815 let tree = Worktree::open_local(
3816 client,
3817 user_store,
3818 dir.path(),
3819 Arc::new(RealFs),
3820 Arc::new(languages),
3821 &mut cx.to_async(),
3822 )
3823 .await
3824 .unwrap();
3825 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3826 .await;
3827
3828 // Cause worktree to start the fake language server
3829 let _buffer = tree
3830 .update(&mut cx, |tree, cx| tree.open_buffer("b.rs", cx))
3831 .await
3832 .unwrap();
3833
3834 let mut events = subscribe(&tree, &mut cx);
3835
3836 fake_server.start_progress(&progress_token).await;
3837 fake_server.start_progress(&progress_token).await;
3838 fake_server.end_progress(&progress_token).await;
3839 fake_server.start_progress(&progress_token).await;
3840
3841 fake_server
3842 .notify::<lsp::notification::PublishDiagnostics>(lsp::PublishDiagnosticsParams {
3843 uri: Url::from_file_path(dir.path().join("a.rs")).unwrap(),
3844 version: None,
3845 diagnostics: vec![lsp::Diagnostic {
3846 range: lsp::Range::new(lsp::Position::new(0, 9), lsp::Position::new(0, 10)),
3847 severity: Some(lsp::DiagnosticSeverity::ERROR),
3848 message: "undefined variable 'A'".to_string(),
3849 ..Default::default()
3850 }],
3851 })
3852 .await;
3853
3854 let event = events.next().await.unwrap();
3855 assert_eq!(
3856 event,
3857 Event::DiagnosticsUpdated(Arc::from(Path::new("a.rs")))
3858 );
3859
3860 fake_server.end_progress(&progress_token).await;
3861 fake_server.end_progress(&progress_token).await;
3862
3863 let event = events.next().await.unwrap();
3864 assert_eq!(event, Event::DiskBasedDiagnosticsUpdated);
3865
3866 let buffer = tree
3867 .update(&mut cx, |tree, cx| tree.open_buffer("a.rs", cx))
3868 .await
3869 .unwrap();
3870
3871 buffer.read_with(&cx, |buffer, _| {
3872 let snapshot = buffer.snapshot();
3873 let diagnostics = snapshot
3874 .diagnostics_in_range::<_, Point>(0..buffer.len())
3875 .collect::<Vec<_>>();
3876 assert_eq!(
3877 diagnostics,
3878 &[DiagnosticEntry {
3879 range: Point::new(0, 9)..Point::new(0, 10),
3880 diagnostic: Diagnostic {
3881 severity: lsp::DiagnosticSeverity::ERROR,
3882 message: "undefined variable 'A'".to_string(),
3883 group_id: 0,
3884 is_primary: true,
3885 ..Default::default()
3886 }
3887 }]
3888 )
3889 });
3890 }
3891
3892 #[gpui::test]
3893 async fn test_grouped_diagnostics(mut cx: gpui::TestAppContext) {
3894 let fs = Arc::new(FakeFs::new());
3895 let http_client = FakeHttpClient::with_404_response();
3896 let client = Client::new(http_client.clone());
3897 let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http_client, cx));
3898
3899 fs.insert_tree(
3900 "/the-dir",
3901 json!({
3902 "a.rs": "
3903 fn foo(mut v: Vec<usize>) {
3904 for x in &v {
3905 v.push(1);
3906 }
3907 }
3908 "
3909 .unindent(),
3910 }),
3911 )
3912 .await;
3913
3914 let worktree = Worktree::open_local(
3915 client.clone(),
3916 user_store,
3917 "/the-dir".as_ref(),
3918 fs,
3919 Default::default(),
3920 &mut cx.to_async(),
3921 )
3922 .await
3923 .unwrap();
3924
3925 let buffer = worktree
3926 .update(&mut cx, |tree, cx| tree.open_buffer("a.rs", cx))
3927 .await
3928 .unwrap();
3929
3930 let buffer_uri = Url::from_file_path("/the-dir/a.rs").unwrap();
3931 let message = lsp::PublishDiagnosticsParams {
3932 uri: buffer_uri.clone(),
3933 diagnostics: vec![
3934 lsp::Diagnostic {
3935 range: lsp::Range::new(lsp::Position::new(1, 8), lsp::Position::new(1, 9)),
3936 severity: Some(DiagnosticSeverity::WARNING),
3937 message: "error 1".to_string(),
3938 related_information: Some(vec![lsp::DiagnosticRelatedInformation {
3939 location: lsp::Location {
3940 uri: buffer_uri.clone(),
3941 range: lsp::Range::new(
3942 lsp::Position::new(1, 8),
3943 lsp::Position::new(1, 9),
3944 ),
3945 },
3946 message: "error 1 hint 1".to_string(),
3947 }]),
3948 ..Default::default()
3949 },
3950 lsp::Diagnostic {
3951 range: lsp::Range::new(lsp::Position::new(1, 8), lsp::Position::new(1, 9)),
3952 severity: Some(DiagnosticSeverity::HINT),
3953 message: "error 1 hint 1".to_string(),
3954 related_information: Some(vec![lsp::DiagnosticRelatedInformation {
3955 location: lsp::Location {
3956 uri: buffer_uri.clone(),
3957 range: lsp::Range::new(
3958 lsp::Position::new(1, 8),
3959 lsp::Position::new(1, 9),
3960 ),
3961 },
3962 message: "original diagnostic".to_string(),
3963 }]),
3964 ..Default::default()
3965 },
3966 lsp::Diagnostic {
3967 range: lsp::Range::new(lsp::Position::new(2, 8), lsp::Position::new(2, 17)),
3968 severity: Some(DiagnosticSeverity::ERROR),
3969 message: "error 2".to_string(),
3970 related_information: Some(vec![
3971 lsp::DiagnosticRelatedInformation {
3972 location: lsp::Location {
3973 uri: buffer_uri.clone(),
3974 range: lsp::Range::new(
3975 lsp::Position::new(1, 13),
3976 lsp::Position::new(1, 15),
3977 ),
3978 },
3979 message: "error 2 hint 1".to_string(),
3980 },
3981 lsp::DiagnosticRelatedInformation {
3982 location: lsp::Location {
3983 uri: buffer_uri.clone(),
3984 range: lsp::Range::new(
3985 lsp::Position::new(1, 13),
3986 lsp::Position::new(1, 15),
3987 ),
3988 },
3989 message: "error 2 hint 2".to_string(),
3990 },
3991 ]),
3992 ..Default::default()
3993 },
3994 lsp::Diagnostic {
3995 range: lsp::Range::new(lsp::Position::new(1, 13), lsp::Position::new(1, 15)),
3996 severity: Some(DiagnosticSeverity::HINT),
3997 message: "error 2 hint 1".to_string(),
3998 related_information: Some(vec![lsp::DiagnosticRelatedInformation {
3999 location: lsp::Location {
4000 uri: buffer_uri.clone(),
4001 range: lsp::Range::new(
4002 lsp::Position::new(2, 8),
4003 lsp::Position::new(2, 17),
4004 ),
4005 },
4006 message: "original diagnostic".to_string(),
4007 }]),
4008 ..Default::default()
4009 },
4010 lsp::Diagnostic {
4011 range: lsp::Range::new(lsp::Position::new(1, 13), lsp::Position::new(1, 15)),
4012 severity: Some(DiagnosticSeverity::HINT),
4013 message: "error 2 hint 2".to_string(),
4014 related_information: Some(vec![lsp::DiagnosticRelatedInformation {
4015 location: lsp::Location {
4016 uri: buffer_uri.clone(),
4017 range: lsp::Range::new(
4018 lsp::Position::new(2, 8),
4019 lsp::Position::new(2, 17),
4020 ),
4021 },
4022 message: "original diagnostic".to_string(),
4023 }]),
4024 ..Default::default()
4025 },
4026 ],
4027 version: None,
4028 };
4029
4030 worktree
4031 .update(&mut cx, |tree, cx| {
4032 tree.update_diagnostics(message, &Default::default(), cx)
4033 })
4034 .unwrap();
4035 let buffer = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
4036
4037 assert_eq!(
4038 buffer
4039 .diagnostics_in_range::<_, Point>(0..buffer.len())
4040 .collect::<Vec<_>>(),
4041 &[
4042 DiagnosticEntry {
4043 range: Point::new(1, 8)..Point::new(1, 9),
4044 diagnostic: Diagnostic {
4045 severity: DiagnosticSeverity::WARNING,
4046 message: "error 1".to_string(),
4047 group_id: 0,
4048 is_primary: true,
4049 ..Default::default()
4050 }
4051 },
4052 DiagnosticEntry {
4053 range: Point::new(1, 8)..Point::new(1, 9),
4054 diagnostic: Diagnostic {
4055 severity: DiagnosticSeverity::HINT,
4056 message: "error 1 hint 1".to_string(),
4057 group_id: 0,
4058 is_primary: false,
4059 ..Default::default()
4060 }
4061 },
4062 DiagnosticEntry {
4063 range: Point::new(1, 13)..Point::new(1, 15),
4064 diagnostic: Diagnostic {
4065 severity: DiagnosticSeverity::HINT,
4066 message: "error 2 hint 1".to_string(),
4067 group_id: 1,
4068 is_primary: false,
4069 ..Default::default()
4070 }
4071 },
4072 DiagnosticEntry {
4073 range: Point::new(1, 13)..Point::new(1, 15),
4074 diagnostic: Diagnostic {
4075 severity: DiagnosticSeverity::HINT,
4076 message: "error 2 hint 2".to_string(),
4077 group_id: 1,
4078 is_primary: false,
4079 ..Default::default()
4080 }
4081 },
4082 DiagnosticEntry {
4083 range: Point::new(2, 8)..Point::new(2, 17),
4084 diagnostic: Diagnostic {
4085 severity: DiagnosticSeverity::ERROR,
4086 message: "error 2".to_string(),
4087 group_id: 1,
4088 is_primary: true,
4089 ..Default::default()
4090 }
4091 }
4092 ]
4093 );
4094
4095 assert_eq!(
4096 buffer.diagnostic_group::<Point>(0).collect::<Vec<_>>(),
4097 &[
4098 DiagnosticEntry {
4099 range: Point::new(1, 8)..Point::new(1, 9),
4100 diagnostic: Diagnostic {
4101 severity: DiagnosticSeverity::WARNING,
4102 message: "error 1".to_string(),
4103 group_id: 0,
4104 is_primary: true,
4105 ..Default::default()
4106 }
4107 },
4108 DiagnosticEntry {
4109 range: Point::new(1, 8)..Point::new(1, 9),
4110 diagnostic: Diagnostic {
4111 severity: DiagnosticSeverity::HINT,
4112 message: "error 1 hint 1".to_string(),
4113 group_id: 0,
4114 is_primary: false,
4115 ..Default::default()
4116 }
4117 },
4118 ]
4119 );
4120 assert_eq!(
4121 buffer.diagnostic_group::<Point>(1).collect::<Vec<_>>(),
4122 &[
4123 DiagnosticEntry {
4124 range: Point::new(1, 13)..Point::new(1, 15),
4125 diagnostic: Diagnostic {
4126 severity: DiagnosticSeverity::HINT,
4127 message: "error 2 hint 1".to_string(),
4128 group_id: 1,
4129 is_primary: false,
4130 ..Default::default()
4131 }
4132 },
4133 DiagnosticEntry {
4134 range: Point::new(1, 13)..Point::new(1, 15),
4135 diagnostic: Diagnostic {
4136 severity: DiagnosticSeverity::HINT,
4137 message: "error 2 hint 2".to_string(),
4138 group_id: 1,
4139 is_primary: false,
4140 ..Default::default()
4141 }
4142 },
4143 DiagnosticEntry {
4144 range: Point::new(2, 8)..Point::new(2, 17),
4145 diagnostic: Diagnostic {
4146 severity: DiagnosticSeverity::ERROR,
4147 message: "error 2".to_string(),
4148 group_id: 1,
4149 is_primary: true,
4150 ..Default::default()
4151 }
4152 }
4153 ]
4154 );
4155 }
4156
4157 #[gpui::test(iterations = 100)]
4158 fn test_random(mut rng: StdRng) {
4159 let operations = env::var("OPERATIONS")
4160 .map(|o| o.parse().unwrap())
4161 .unwrap_or(40);
4162 let initial_entries = env::var("INITIAL_ENTRIES")
4163 .map(|o| o.parse().unwrap())
4164 .unwrap_or(20);
4165
4166 let root_dir = tempdir::TempDir::new("worktree-test").unwrap();
4167 for _ in 0..initial_entries {
4168 randomly_mutate_tree(root_dir.path(), 1.0, &mut rng).unwrap();
4169 }
4170 log::info!("Generated initial tree");
4171
4172 let (notify_tx, _notify_rx) = smol::channel::unbounded();
4173 let fs = Arc::new(RealFs);
4174 let next_entry_id = Arc::new(AtomicUsize::new(0));
4175 let mut initial_snapshot = Snapshot {
4176 id: WorktreeId::from_usize(0),
4177 scan_id: 0,
4178 abs_path: root_dir.path().into(),
4179 entries_by_path: Default::default(),
4180 entries_by_id: Default::default(),
4181 removed_entry_ids: Default::default(),
4182 ignores: Default::default(),
4183 root_name: Default::default(),
4184 root_char_bag: Default::default(),
4185 next_entry_id: next_entry_id.clone(),
4186 diagnostic_summaries: Default::default(),
4187 };
4188 initial_snapshot.insert_entry(
4189 Entry::new(
4190 Path::new("").into(),
4191 &smol::block_on(fs.metadata(root_dir.path()))
4192 .unwrap()
4193 .unwrap(),
4194 &next_entry_id,
4195 Default::default(),
4196 ),
4197 fs.as_ref(),
4198 );
4199 let mut scanner = BackgroundScanner::new(
4200 Arc::new(Mutex::new(initial_snapshot.clone())),
4201 notify_tx,
4202 fs.clone(),
4203 Arc::new(gpui::executor::Background::new()),
4204 );
4205 smol::block_on(scanner.scan_dirs()).unwrap();
4206 scanner.snapshot().check_invariants();
4207
4208 let mut events = Vec::new();
4209 let mut snapshots = Vec::new();
4210 let mut mutations_len = operations;
4211 while mutations_len > 1 {
4212 if !events.is_empty() && rng.gen_bool(0.4) {
4213 let len = rng.gen_range(0..=events.len());
4214 let to_deliver = events.drain(0..len).collect::<Vec<_>>();
4215 log::info!("Delivering events: {:#?}", to_deliver);
4216 smol::block_on(scanner.process_events(to_deliver));
4217 scanner.snapshot().check_invariants();
4218 } else {
4219 events.extend(randomly_mutate_tree(root_dir.path(), 0.6, &mut rng).unwrap());
4220 mutations_len -= 1;
4221 }
4222
4223 if rng.gen_bool(0.2) {
4224 snapshots.push(scanner.snapshot());
4225 }
4226 }
4227 log::info!("Quiescing: {:#?}", events);
4228 smol::block_on(scanner.process_events(events));
4229 scanner.snapshot().check_invariants();
4230
4231 let (notify_tx, _notify_rx) = smol::channel::unbounded();
4232 let mut new_scanner = BackgroundScanner::new(
4233 Arc::new(Mutex::new(initial_snapshot)),
4234 notify_tx,
4235 scanner.fs.clone(),
4236 scanner.executor.clone(),
4237 );
4238 smol::block_on(new_scanner.scan_dirs()).unwrap();
4239 assert_eq!(
4240 scanner.snapshot().to_vec(true),
4241 new_scanner.snapshot().to_vec(true)
4242 );
4243
4244 for mut prev_snapshot in snapshots {
4245 let include_ignored = rng.gen::<bool>();
4246 if !include_ignored {
4247 let mut entries_by_path_edits = Vec::new();
4248 let mut entries_by_id_edits = Vec::new();
4249 for entry in prev_snapshot
4250 .entries_by_id
4251 .cursor::<()>()
4252 .filter(|e| e.is_ignored)
4253 {
4254 entries_by_path_edits.push(Edit::Remove(PathKey(entry.path.clone())));
4255 entries_by_id_edits.push(Edit::Remove(entry.id));
4256 }
4257
4258 prev_snapshot
4259 .entries_by_path
4260 .edit(entries_by_path_edits, &());
4261 prev_snapshot.entries_by_id.edit(entries_by_id_edits, &());
4262 }
4263
4264 let update = scanner
4265 .snapshot()
4266 .build_update(&prev_snapshot, 0, 0, include_ignored);
4267 prev_snapshot.apply_update(update).unwrap();
4268 assert_eq!(
4269 prev_snapshot.to_vec(true),
4270 scanner.snapshot().to_vec(include_ignored)
4271 );
4272 }
4273 }
4274
4275 fn randomly_mutate_tree(
4276 root_path: &Path,
4277 insertion_probability: f64,
4278 rng: &mut impl Rng,
4279 ) -> Result<Vec<fsevent::Event>> {
4280 let root_path = root_path.canonicalize().unwrap();
4281 let (dirs, files) = read_dir_recursive(root_path.clone());
4282
4283 let mut events = Vec::new();
4284 let mut record_event = |path: PathBuf| {
4285 events.push(fsevent::Event {
4286 event_id: SystemTime::now()
4287 .duration_since(UNIX_EPOCH)
4288 .unwrap()
4289 .as_secs(),
4290 flags: fsevent::StreamFlags::empty(),
4291 path,
4292 });
4293 };
4294
4295 if (files.is_empty() && dirs.len() == 1) || rng.gen_bool(insertion_probability) {
4296 let path = dirs.choose(rng).unwrap();
4297 let new_path = path.join(gen_name(rng));
4298
4299 if rng.gen() {
4300 log::info!("Creating dir {:?}", new_path.strip_prefix(root_path)?);
4301 std::fs::create_dir(&new_path)?;
4302 } else {
4303 log::info!("Creating file {:?}", new_path.strip_prefix(root_path)?);
4304 std::fs::write(&new_path, "")?;
4305 }
4306 record_event(new_path);
4307 } else if rng.gen_bool(0.05) {
4308 let ignore_dir_path = dirs.choose(rng).unwrap();
4309 let ignore_path = ignore_dir_path.join(&*GITIGNORE);
4310
4311 let (subdirs, subfiles) = read_dir_recursive(ignore_dir_path.clone());
4312 let files_to_ignore = {
4313 let len = rng.gen_range(0..=subfiles.len());
4314 subfiles.choose_multiple(rng, len)
4315 };
4316 let dirs_to_ignore = {
4317 let len = rng.gen_range(0..subdirs.len());
4318 subdirs.choose_multiple(rng, len)
4319 };
4320
4321 let mut ignore_contents = String::new();
4322 for path_to_ignore in files_to_ignore.chain(dirs_to_ignore) {
4323 write!(
4324 ignore_contents,
4325 "{}\n",
4326 path_to_ignore
4327 .strip_prefix(&ignore_dir_path)?
4328 .to_str()
4329 .unwrap()
4330 )
4331 .unwrap();
4332 }
4333 log::info!(
4334 "Creating {:?} with contents:\n{}",
4335 ignore_path.strip_prefix(&root_path)?,
4336 ignore_contents
4337 );
4338 std::fs::write(&ignore_path, ignore_contents).unwrap();
4339 record_event(ignore_path);
4340 } else {
4341 let old_path = {
4342 let file_path = files.choose(rng);
4343 let dir_path = dirs[1..].choose(rng);
4344 file_path.into_iter().chain(dir_path).choose(rng).unwrap()
4345 };
4346
4347 let is_rename = rng.gen();
4348 if is_rename {
4349 let new_path_parent = dirs
4350 .iter()
4351 .filter(|d| !d.starts_with(old_path))
4352 .choose(rng)
4353 .unwrap();
4354
4355 let overwrite_existing_dir =
4356 !old_path.starts_with(&new_path_parent) && rng.gen_bool(0.3);
4357 let new_path = if overwrite_existing_dir {
4358 std::fs::remove_dir_all(&new_path_parent).ok();
4359 new_path_parent.to_path_buf()
4360 } else {
4361 new_path_parent.join(gen_name(rng))
4362 };
4363
4364 log::info!(
4365 "Renaming {:?} to {}{:?}",
4366 old_path.strip_prefix(&root_path)?,
4367 if overwrite_existing_dir {
4368 "overwrite "
4369 } else {
4370 ""
4371 },
4372 new_path.strip_prefix(&root_path)?
4373 );
4374 std::fs::rename(&old_path, &new_path)?;
4375 record_event(old_path.clone());
4376 record_event(new_path);
4377 } else if old_path.is_dir() {
4378 let (dirs, files) = read_dir_recursive(old_path.clone());
4379
4380 log::info!("Deleting dir {:?}", old_path.strip_prefix(&root_path)?);
4381 std::fs::remove_dir_all(&old_path).unwrap();
4382 for file in files {
4383 record_event(file);
4384 }
4385 for dir in dirs {
4386 record_event(dir);
4387 }
4388 } else {
4389 log::info!("Deleting file {:?}", old_path.strip_prefix(&root_path)?);
4390 std::fs::remove_file(old_path).unwrap();
4391 record_event(old_path.clone());
4392 }
4393 }
4394
4395 Ok(events)
4396 }
4397
4398 fn read_dir_recursive(path: PathBuf) -> (Vec<PathBuf>, Vec<PathBuf>) {
4399 let child_entries = std::fs::read_dir(&path).unwrap();
4400 let mut dirs = vec![path];
4401 let mut files = Vec::new();
4402 for child_entry in child_entries {
4403 let child_path = child_entry.unwrap().path();
4404 if child_path.is_dir() {
4405 let (child_dirs, child_files) = read_dir_recursive(child_path);
4406 dirs.extend(child_dirs);
4407 files.extend(child_files);
4408 } else {
4409 files.push(child_path);
4410 }
4411 }
4412 (dirs, files)
4413 }
4414
4415 fn gen_name(rng: &mut impl Rng) -> String {
4416 (0..6)
4417 .map(|_| rng.sample(rand::distributions::Alphanumeric))
4418 .map(char::from)
4419 .collect()
4420 }
4421
4422 impl Snapshot {
4423 fn check_invariants(&self) {
4424 let mut files = self.files(true, 0);
4425 let mut visible_files = self.files(false, 0);
4426 for entry in self.entries_by_path.cursor::<()>() {
4427 if entry.is_file() {
4428 assert_eq!(files.next().unwrap().inode, entry.inode);
4429 if !entry.is_ignored {
4430 assert_eq!(visible_files.next().unwrap().inode, entry.inode);
4431 }
4432 }
4433 }
4434 assert!(files.next().is_none());
4435 assert!(visible_files.next().is_none());
4436
4437 let mut bfs_paths = Vec::new();
4438 let mut stack = vec![Path::new("")];
4439 while let Some(path) = stack.pop() {
4440 bfs_paths.push(path);
4441 let ix = stack.len();
4442 for child_entry in self.child_entries(path) {
4443 stack.insert(ix, &child_entry.path);
4444 }
4445 }
4446
4447 let dfs_paths = self
4448 .entries_by_path
4449 .cursor::<()>()
4450 .map(|e| e.path.as_ref())
4451 .collect::<Vec<_>>();
4452 assert_eq!(bfs_paths, dfs_paths);
4453
4454 for (ignore_parent_path, _) in &self.ignores {
4455 assert!(self.entry_for_path(ignore_parent_path).is_some());
4456 assert!(self
4457 .entry_for_path(ignore_parent_path.join(&*GITIGNORE))
4458 .is_some());
4459 }
4460 }
4461
4462 fn to_vec(&self, include_ignored: bool) -> Vec<(&Path, u64, bool)> {
4463 let mut paths = Vec::new();
4464 for entry in self.entries_by_path.cursor::<()>() {
4465 if include_ignored || !entry.is_ignored {
4466 paths.push((entry.path.as_ref(), entry.inode, entry.is_ignored));
4467 }
4468 }
4469 paths.sort_by(|a, b| a.0.cmp(&b.0));
4470 paths
4471 }
4472 }
4473}