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