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