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 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 register(
698 &mut self,
699 project_id: u64,
700 cx: &mut ModelContext<Worktree>,
701 ) -> Task<anyhow::Result<()>> {
702 if self.registration != Registration::None {
703 return Task::ready(Ok(()));
704 }
705
706 self.registration = Registration::Pending;
707 let client = self.client.clone();
708 let register_message = proto::RegisterWorktree {
709 project_id,
710 worktree_id: self.id().to_proto(),
711 root_name: self.root_name().to_string(),
712 authorized_logins: self.authorized_logins(),
713 visible: self.visible,
714 };
715 let request = client.request(register_message);
716 cx.spawn(|this, mut cx| async move {
717 let response = request.await;
718 this.update(&mut cx, |this, _| {
719 let worktree = this.as_local_mut().unwrap();
720 match response {
721 Ok(_) => {
722 if worktree.registration == Registration::Pending {
723 worktree.registration = Registration::Done { project_id };
724 }
725 Ok(())
726 }
727 Err(error) => {
728 worktree.registration = Registration::None;
729 Err(error)
730 }
731 }
732 })
733 })
734 }
735
736 pub fn share(&mut self, project_id: u64, cx: &mut ModelContext<Worktree>) -> Task<Result<()>> {
737 let register = self.register(project_id, cx);
738 let (share_tx, share_rx) = oneshot::channel();
739 let (snapshots_to_send_tx, snapshots_to_send_rx) =
740 smol::channel::unbounded::<LocalSnapshot>();
741 if self.share.is_some() {
742 let _ = share_tx.send(Ok(()));
743 } else {
744 let rpc = self.client.clone();
745 let worktree_id = cx.model_id() as u64;
746 let maintain_remote_snapshot = cx.background().spawn({
747 let rpc = rpc.clone();
748 let diagnostic_summaries = self.diagnostic_summaries.clone();
749 async move {
750 let mut prev_snapshot = match snapshots_to_send_rx.recv().await {
751 Ok(snapshot) => {
752 if let Err(error) = rpc
753 .request(proto::UpdateWorktree {
754 project_id,
755 worktree_id,
756 root_name: snapshot.root_name().to_string(),
757 updated_entries: snapshot
758 .entries_by_path
759 .iter()
760 .filter(|e| !e.is_ignored)
761 .map(Into::into)
762 .collect(),
763 removed_entries: Default::default(),
764 })
765 .await
766 {
767 let _ = share_tx.send(Err(error));
768 return Err(anyhow!("failed to send initial update worktree"));
769 } else {
770 let _ = share_tx.send(Ok(()));
771 snapshot
772 }
773 }
774 Err(error) => {
775 let _ = share_tx.send(Err(error.into()));
776 return Err(anyhow!("failed to send initial update worktree"));
777 }
778 };
779
780 for (path, summary) in diagnostic_summaries.iter() {
781 rpc.send(proto::UpdateDiagnosticSummary {
782 project_id,
783 worktree_id,
784 summary: Some(summary.to_proto(&path.0)),
785 })?;
786 }
787
788 while let Ok(snapshot) = snapshots_to_send_rx.recv().await {
789 let message =
790 snapshot.build_update(&prev_snapshot, project_id, worktree_id, false);
791 rpc.request(message).await?;
792 prev_snapshot = snapshot;
793 }
794
795 Ok::<_, anyhow::Error>(())
796 }
797 .log_err()
798 });
799 self.share = Some(ShareState {
800 project_id,
801 snapshots_tx: snapshots_to_send_tx.clone(),
802 _maintain_remote_snapshot: Some(maintain_remote_snapshot),
803 });
804 }
805
806 cx.spawn_weak(|this, cx| async move {
807 register.await?;
808 if let Some(this) = this.upgrade(&cx) {
809 this.read_with(&cx, |this, _| {
810 let this = this.as_local().unwrap();
811 let _ = snapshots_to_send_tx.try_send(this.snapshot());
812 });
813 }
814 share_rx
815 .await
816 .unwrap_or_else(|_| Err(anyhow!("share ended")))
817 })
818 }
819
820 pub fn unregister(&mut self) {
821 self.unshare();
822 self.registration = Registration::None;
823 }
824
825 pub fn unshare(&mut self) {
826 self.share.take();
827 }
828
829 pub fn is_shared(&self) -> bool {
830 self.share.is_some()
831 }
832}
833
834impl RemoteWorktree {
835 fn snapshot(&self) -> Snapshot {
836 self.snapshot.clone()
837 }
838
839 pub fn update_from_remote(
840 &mut self,
841 envelope: TypedEnvelope<proto::UpdateWorktree>,
842 ) -> Result<()> {
843 self.updates_tx
844 .unbounded_send(envelope.payload)
845 .expect("consumer runs to completion");
846
847 Ok(())
848 }
849
850 pub fn update_diagnostic_summary(
851 &mut self,
852 path: Arc<Path>,
853 summary: &proto::DiagnosticSummary,
854 ) {
855 let summary = DiagnosticSummary {
856 error_count: summary.error_count as usize,
857 warning_count: summary.warning_count as usize,
858 };
859 if summary.is_empty() {
860 self.diagnostic_summaries.remove(&PathKey(path.clone()));
861 } else {
862 self.diagnostic_summaries
863 .insert(PathKey(path.clone()), summary);
864 }
865 }
866}
867
868impl Snapshot {
869 pub fn id(&self) -> WorktreeId {
870 self.id
871 }
872
873 pub fn contains_entry(&self, entry_id: ProjectEntryId) -> bool {
874 self.entries_by_id.get(&entry_id, &()).is_some()
875 }
876
877 pub(crate) fn apply_remote_update(&mut self, update: proto::UpdateWorktree) -> Result<()> {
878 let mut entries_by_path_edits = Vec::new();
879 let mut entries_by_id_edits = Vec::new();
880 for entry_id in update.removed_entries {
881 let entry = self
882 .entry_for_id(ProjectEntryId::from_proto(entry_id))
883 .ok_or_else(|| anyhow!("unknown entry"))?;
884 entries_by_path_edits.push(Edit::Remove(PathKey(entry.path.clone())));
885 entries_by_id_edits.push(Edit::Remove(entry.id));
886 }
887
888 for entry in update.updated_entries {
889 let entry = Entry::try_from((&self.root_char_bag, entry))?;
890 if let Some(PathEntry { path, .. }) = self.entries_by_id.get(&entry.id, &()) {
891 entries_by_path_edits.push(Edit::Remove(PathKey(path.clone())));
892 }
893 entries_by_id_edits.push(Edit::Insert(PathEntry {
894 id: entry.id,
895 path: entry.path.clone(),
896 is_ignored: entry.is_ignored,
897 scan_id: 0,
898 }));
899 entries_by_path_edits.push(Edit::Insert(entry));
900 }
901
902 self.entries_by_path.edit(entries_by_path_edits, &());
903 self.entries_by_id.edit(entries_by_id_edits, &());
904
905 Ok(())
906 }
907
908 pub fn file_count(&self) -> usize {
909 self.entries_by_path.summary().file_count
910 }
911
912 pub fn visible_file_count(&self) -> usize {
913 self.entries_by_path.summary().visible_file_count
914 }
915
916 fn traverse_from_offset(
917 &self,
918 include_dirs: bool,
919 include_ignored: bool,
920 start_offset: usize,
921 ) -> Traversal {
922 let mut cursor = self.entries_by_path.cursor();
923 cursor.seek(
924 &TraversalTarget::Count {
925 count: start_offset,
926 include_dirs,
927 include_ignored,
928 },
929 Bias::Right,
930 &(),
931 );
932 Traversal {
933 cursor,
934 include_dirs,
935 include_ignored,
936 }
937 }
938
939 fn traverse_from_path(
940 &self,
941 include_dirs: bool,
942 include_ignored: bool,
943 path: &Path,
944 ) -> Traversal {
945 let mut cursor = self.entries_by_path.cursor();
946 cursor.seek(&TraversalTarget::Path(path), Bias::Left, &());
947 Traversal {
948 cursor,
949 include_dirs,
950 include_ignored,
951 }
952 }
953
954 pub fn files(&self, include_ignored: bool, start: usize) -> Traversal {
955 self.traverse_from_offset(false, include_ignored, start)
956 }
957
958 pub fn entries(&self, include_ignored: bool) -> Traversal {
959 self.traverse_from_offset(true, include_ignored, 0)
960 }
961
962 pub fn paths(&self) -> impl Iterator<Item = &Arc<Path>> {
963 let empty_path = Path::new("");
964 self.entries_by_path
965 .cursor::<()>()
966 .filter(move |entry| entry.path.as_ref() != empty_path)
967 .map(|entry| &entry.path)
968 }
969
970 fn child_entries<'a>(&'a self, parent_path: &'a Path) -> ChildEntriesIter<'a> {
971 let mut cursor = self.entries_by_path.cursor();
972 cursor.seek(&TraversalTarget::Path(parent_path), Bias::Right, &());
973 let traversal = Traversal {
974 cursor,
975 include_dirs: true,
976 include_ignored: true,
977 };
978 ChildEntriesIter {
979 traversal,
980 parent_path,
981 }
982 }
983
984 pub fn root_entry(&self) -> Option<&Entry> {
985 self.entry_for_path("")
986 }
987
988 pub fn root_name(&self) -> &str {
989 &self.root_name
990 }
991
992 pub fn entry_for_path(&self, path: impl AsRef<Path>) -> Option<&Entry> {
993 let path = path.as_ref();
994 self.traverse_from_path(true, true, path)
995 .entry()
996 .and_then(|entry| {
997 if entry.path.as_ref() == path {
998 Some(entry)
999 } else {
1000 None
1001 }
1002 })
1003 }
1004
1005 pub fn entry_for_id(&self, id: ProjectEntryId) -> Option<&Entry> {
1006 let entry = self.entries_by_id.get(&id, &())?;
1007 self.entry_for_path(&entry.path)
1008 }
1009
1010 pub fn inode_for_path(&self, path: impl AsRef<Path>) -> Option<u64> {
1011 self.entry_for_path(path.as_ref()).map(|e| e.inode)
1012 }
1013}
1014
1015impl LocalSnapshot {
1016 pub fn abs_path(&self) -> &Arc<Path> {
1017 &self.abs_path
1018 }
1019
1020 #[cfg(test)]
1021 pub(crate) fn to_proto(
1022 &self,
1023 diagnostic_summaries: &TreeMap<PathKey, DiagnosticSummary>,
1024 visible: bool,
1025 ) -> proto::Worktree {
1026 let root_name = self.root_name.clone();
1027 proto::Worktree {
1028 id: self.id.0 as u64,
1029 root_name,
1030 entries: self
1031 .entries_by_path
1032 .iter()
1033 .filter(|e| !e.is_ignored)
1034 .map(Into::into)
1035 .collect(),
1036 diagnostic_summaries: diagnostic_summaries
1037 .iter()
1038 .map(|(path, summary)| summary.to_proto(&path.0))
1039 .collect(),
1040 visible,
1041 }
1042 }
1043
1044 pub(crate) fn build_update(
1045 &self,
1046 other: &Self,
1047 project_id: u64,
1048 worktree_id: u64,
1049 include_ignored: bool,
1050 ) -> proto::UpdateWorktree {
1051 let mut updated_entries = Vec::new();
1052 let mut removed_entries = Vec::new();
1053 let mut self_entries = self
1054 .entries_by_id
1055 .cursor::<()>()
1056 .filter(|e| include_ignored || !e.is_ignored)
1057 .peekable();
1058 let mut other_entries = other
1059 .entries_by_id
1060 .cursor::<()>()
1061 .filter(|e| include_ignored || !e.is_ignored)
1062 .peekable();
1063 loop {
1064 match (self_entries.peek(), other_entries.peek()) {
1065 (Some(self_entry), Some(other_entry)) => {
1066 match Ord::cmp(&self_entry.id, &other_entry.id) {
1067 Ordering::Less => {
1068 let entry = self.entry_for_id(self_entry.id).unwrap().into();
1069 updated_entries.push(entry);
1070 self_entries.next();
1071 }
1072 Ordering::Equal => {
1073 if self_entry.scan_id != other_entry.scan_id {
1074 let entry = self.entry_for_id(self_entry.id).unwrap().into();
1075 updated_entries.push(entry);
1076 }
1077
1078 self_entries.next();
1079 other_entries.next();
1080 }
1081 Ordering::Greater => {
1082 removed_entries.push(other_entry.id.to_proto());
1083 other_entries.next();
1084 }
1085 }
1086 }
1087 (Some(self_entry), None) => {
1088 let entry = self.entry_for_id(self_entry.id).unwrap().into();
1089 updated_entries.push(entry);
1090 self_entries.next();
1091 }
1092 (None, Some(other_entry)) => {
1093 removed_entries.push(other_entry.id.to_proto());
1094 other_entries.next();
1095 }
1096 (None, None) => break,
1097 }
1098 }
1099
1100 proto::UpdateWorktree {
1101 project_id,
1102 worktree_id,
1103 root_name: self.root_name().to_string(),
1104 updated_entries,
1105 removed_entries,
1106 }
1107 }
1108
1109 fn insert_entry(&mut self, mut entry: Entry, fs: &dyn Fs) -> Entry {
1110 if !entry.is_dir() && entry.path.file_name() == Some(&GITIGNORE) {
1111 let abs_path = self.abs_path.join(&entry.path);
1112 match build_gitignore(&abs_path, fs) {
1113 Ok(ignore) => {
1114 let ignore_dir_path = entry.path.parent().unwrap();
1115 self.ignores
1116 .insert(ignore_dir_path.into(), (Arc::new(ignore), self.scan_id));
1117 }
1118 Err(error) => {
1119 log::error!(
1120 "error loading .gitignore file {:?} - {:?}",
1121 &entry.path,
1122 error
1123 );
1124 }
1125 }
1126 }
1127
1128 self.reuse_entry_id(&mut entry);
1129 self.entries_by_path.insert_or_replace(entry.clone(), &());
1130 let scan_id = self.scan_id;
1131 self.entries_by_id.insert_or_replace(
1132 PathEntry {
1133 id: entry.id,
1134 path: entry.path.clone(),
1135 is_ignored: entry.is_ignored,
1136 scan_id,
1137 },
1138 &(),
1139 );
1140 entry
1141 }
1142
1143 fn populate_dir(
1144 &mut self,
1145 parent_path: Arc<Path>,
1146 entries: impl IntoIterator<Item = Entry>,
1147 ignore: Option<Arc<Gitignore>>,
1148 ) {
1149 let mut parent_entry = self
1150 .entries_by_path
1151 .get(&PathKey(parent_path.clone()), &())
1152 .unwrap()
1153 .clone();
1154 if let Some(ignore) = ignore {
1155 self.ignores.insert(parent_path, (ignore, self.scan_id));
1156 }
1157 if matches!(parent_entry.kind, EntryKind::PendingDir) {
1158 parent_entry.kind = EntryKind::Dir;
1159 } else {
1160 unreachable!();
1161 }
1162
1163 let mut entries_by_path_edits = vec![Edit::Insert(parent_entry)];
1164 let mut entries_by_id_edits = Vec::new();
1165
1166 for mut entry in entries {
1167 self.reuse_entry_id(&mut entry);
1168 entries_by_id_edits.push(Edit::Insert(PathEntry {
1169 id: entry.id,
1170 path: entry.path.clone(),
1171 is_ignored: entry.is_ignored,
1172 scan_id: self.scan_id,
1173 }));
1174 entries_by_path_edits.push(Edit::Insert(entry));
1175 }
1176
1177 self.entries_by_path.edit(entries_by_path_edits, &());
1178 self.entries_by_id.edit(entries_by_id_edits, &());
1179 }
1180
1181 fn reuse_entry_id(&mut self, entry: &mut Entry) {
1182 if let Some(removed_entry_id) = self.removed_entry_ids.remove(&entry.inode) {
1183 entry.id = removed_entry_id;
1184 } else if let Some(existing_entry) = self.entry_for_path(&entry.path) {
1185 entry.id = existing_entry.id;
1186 }
1187 }
1188
1189 fn remove_path(&mut self, path: &Path) {
1190 let mut new_entries;
1191 let removed_entries;
1192 {
1193 let mut cursor = self.entries_by_path.cursor::<TraversalProgress>();
1194 new_entries = cursor.slice(&TraversalTarget::Path(path), Bias::Left, &());
1195 removed_entries = cursor.slice(&TraversalTarget::PathSuccessor(path), Bias::Left, &());
1196 new_entries.push_tree(cursor.suffix(&()), &());
1197 }
1198 self.entries_by_path = new_entries;
1199
1200 let mut entries_by_id_edits = Vec::new();
1201 for entry in removed_entries.cursor::<()>() {
1202 let removed_entry_id = self
1203 .removed_entry_ids
1204 .entry(entry.inode)
1205 .or_insert(entry.id);
1206 *removed_entry_id = cmp::max(*removed_entry_id, entry.id);
1207 entries_by_id_edits.push(Edit::Remove(entry.id));
1208 }
1209 self.entries_by_id.edit(entries_by_id_edits, &());
1210
1211 if path.file_name() == Some(&GITIGNORE) {
1212 if let Some((_, scan_id)) = self.ignores.get_mut(path.parent().unwrap()) {
1213 *scan_id = self.scan_id;
1214 }
1215 }
1216 }
1217
1218 fn ignore_stack_for_path(&self, path: &Path, is_dir: bool) -> Arc<IgnoreStack> {
1219 let mut new_ignores = Vec::new();
1220 for ancestor in path.ancestors().skip(1) {
1221 if let Some((ignore, _)) = self.ignores.get(ancestor) {
1222 new_ignores.push((ancestor, Some(ignore.clone())));
1223 } else {
1224 new_ignores.push((ancestor, None));
1225 }
1226 }
1227
1228 let mut ignore_stack = IgnoreStack::none();
1229 for (parent_path, ignore) in new_ignores.into_iter().rev() {
1230 if ignore_stack.is_path_ignored(&parent_path, true) {
1231 ignore_stack = IgnoreStack::all();
1232 break;
1233 } else if let Some(ignore) = ignore {
1234 ignore_stack = ignore_stack.append(Arc::from(parent_path), ignore);
1235 }
1236 }
1237
1238 if ignore_stack.is_path_ignored(path, is_dir) {
1239 ignore_stack = IgnoreStack::all();
1240 }
1241
1242 ignore_stack
1243 }
1244}
1245
1246fn build_gitignore(abs_path: &Path, fs: &dyn Fs) -> Result<Gitignore> {
1247 let contents = smol::block_on(fs.load(&abs_path))?;
1248 let parent = abs_path.parent().unwrap_or(Path::new("/"));
1249 let mut builder = GitignoreBuilder::new(parent);
1250 for line in contents.lines() {
1251 builder.add_line(Some(abs_path.into()), line)?;
1252 }
1253 Ok(builder.build()?)
1254}
1255
1256impl WorktreeId {
1257 pub fn from_usize(handle_id: usize) -> Self {
1258 Self(handle_id)
1259 }
1260
1261 pub(crate) fn from_proto(id: u64) -> Self {
1262 Self(id as usize)
1263 }
1264
1265 pub fn to_proto(&self) -> u64 {
1266 self.0 as u64
1267 }
1268
1269 pub fn to_usize(&self) -> usize {
1270 self.0
1271 }
1272}
1273
1274impl fmt::Display for WorktreeId {
1275 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1276 self.0.fmt(f)
1277 }
1278}
1279
1280impl Deref for Worktree {
1281 type Target = Snapshot;
1282
1283 fn deref(&self) -> &Self::Target {
1284 match self {
1285 Worktree::Local(worktree) => &worktree.snapshot,
1286 Worktree::Remote(worktree) => &worktree.snapshot,
1287 }
1288 }
1289}
1290
1291impl Deref for LocalWorktree {
1292 type Target = LocalSnapshot;
1293
1294 fn deref(&self) -> &Self::Target {
1295 &self.snapshot
1296 }
1297}
1298
1299impl Deref for RemoteWorktree {
1300 type Target = Snapshot;
1301
1302 fn deref(&self) -> &Self::Target {
1303 &self.snapshot
1304 }
1305}
1306
1307impl fmt::Debug for LocalWorktree {
1308 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1309 self.snapshot.fmt(f)
1310 }
1311}
1312
1313impl fmt::Debug for Snapshot {
1314 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1315 struct EntriesById<'a>(&'a SumTree<PathEntry>);
1316 struct EntriesByPath<'a>(&'a SumTree<Entry>);
1317
1318 impl<'a> fmt::Debug for EntriesByPath<'a> {
1319 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1320 f.debug_map()
1321 .entries(self.0.iter().map(|entry| (&entry.path, entry.id)))
1322 .finish()
1323 }
1324 }
1325
1326 impl<'a> fmt::Debug for EntriesById<'a> {
1327 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1328 f.debug_list().entries(self.0.iter()).finish()
1329 }
1330 }
1331
1332 f.debug_struct("Snapshot")
1333 .field("id", &self.id)
1334 .field("root_name", &self.root_name)
1335 .field("entries_by_path", &EntriesByPath(&self.entries_by_path))
1336 .field("entries_by_id", &EntriesById(&self.entries_by_id))
1337 .finish()
1338 }
1339}
1340
1341#[derive(Clone, PartialEq)]
1342pub struct File {
1343 pub worktree: ModelHandle<Worktree>,
1344 pub path: Arc<Path>,
1345 pub mtime: SystemTime,
1346 pub(crate) entry_id: Option<ProjectEntryId>,
1347 pub(crate) is_local: bool,
1348}
1349
1350impl language::File for File {
1351 fn as_local(&self) -> Option<&dyn language::LocalFile> {
1352 if self.is_local {
1353 Some(self)
1354 } else {
1355 None
1356 }
1357 }
1358
1359 fn mtime(&self) -> SystemTime {
1360 self.mtime
1361 }
1362
1363 fn path(&self) -> &Arc<Path> {
1364 &self.path
1365 }
1366
1367 fn full_path(&self, cx: &AppContext) -> PathBuf {
1368 let mut full_path = PathBuf::new();
1369 full_path.push(self.worktree.read(cx).root_name());
1370 if self.path.components().next().is_some() {
1371 full_path.push(&self.path);
1372 }
1373 full_path
1374 }
1375
1376 /// Returns the last component of this handle's absolute path. If this handle refers to the root
1377 /// of its worktree, then this method will return the name of the worktree itself.
1378 fn file_name(&self, cx: &AppContext) -> OsString {
1379 self.path
1380 .file_name()
1381 .map(|name| name.into())
1382 .unwrap_or_else(|| OsString::from(&self.worktree.read(cx).root_name))
1383 }
1384
1385 fn is_deleted(&self) -> bool {
1386 self.entry_id.is_none()
1387 }
1388
1389 fn save(
1390 &self,
1391 buffer_id: u64,
1392 text: Rope,
1393 version: clock::Global,
1394 cx: &mut MutableAppContext,
1395 ) -> Task<Result<(clock::Global, SystemTime)>> {
1396 self.worktree.update(cx, |worktree, cx| match worktree {
1397 Worktree::Local(worktree) => {
1398 let rpc = worktree.client.clone();
1399 let project_id = worktree.share.as_ref().map(|share| share.project_id);
1400 let save = worktree.save(self.path.clone(), text, cx);
1401 cx.background().spawn(async move {
1402 let entry = save.await?;
1403 if let Some(project_id) = project_id {
1404 rpc.send(proto::BufferSaved {
1405 project_id,
1406 buffer_id,
1407 version: serialize_version(&version),
1408 mtime: Some(entry.mtime.into()),
1409 })?;
1410 }
1411 Ok((version, entry.mtime))
1412 })
1413 }
1414 Worktree::Remote(worktree) => {
1415 let rpc = worktree.client.clone();
1416 let project_id = worktree.project_id;
1417 cx.foreground().spawn(async move {
1418 let response = rpc
1419 .request(proto::SaveBuffer {
1420 project_id,
1421 buffer_id,
1422 version: serialize_version(&version),
1423 })
1424 .await?;
1425 let version = deserialize_version(response.version);
1426 let mtime = response
1427 .mtime
1428 .ok_or_else(|| anyhow!("missing mtime"))?
1429 .into();
1430 Ok((version, mtime))
1431 })
1432 }
1433 })
1434 }
1435
1436 fn as_any(&self) -> &dyn Any {
1437 self
1438 }
1439
1440 fn to_proto(&self) -> rpc::proto::File {
1441 rpc::proto::File {
1442 worktree_id: self.worktree.id() as u64,
1443 entry_id: self.entry_id.map(|entry_id| entry_id.to_proto()),
1444 path: self.path.to_string_lossy().into(),
1445 mtime: Some(self.mtime.into()),
1446 }
1447 }
1448}
1449
1450impl language::LocalFile for File {
1451 fn abs_path(&self, cx: &AppContext) -> PathBuf {
1452 self.worktree
1453 .read(cx)
1454 .as_local()
1455 .unwrap()
1456 .abs_path
1457 .join(&self.path)
1458 }
1459
1460 fn load(&self, cx: &AppContext) -> Task<Result<String>> {
1461 let worktree = self.worktree.read(cx).as_local().unwrap();
1462 let abs_path = worktree.absolutize(&self.path);
1463 let fs = worktree.fs.clone();
1464 cx.background()
1465 .spawn(async move { fs.load(&abs_path).await })
1466 }
1467
1468 fn buffer_reloaded(
1469 &self,
1470 buffer_id: u64,
1471 version: &clock::Global,
1472 mtime: SystemTime,
1473 cx: &mut MutableAppContext,
1474 ) {
1475 let worktree = self.worktree.read(cx).as_local().unwrap();
1476 if let Some(project_id) = worktree.share.as_ref().map(|share| share.project_id) {
1477 worktree
1478 .client
1479 .send(proto::BufferReloaded {
1480 project_id,
1481 buffer_id,
1482 version: serialize_version(&version),
1483 mtime: Some(mtime.into()),
1484 })
1485 .log_err();
1486 }
1487 }
1488}
1489
1490impl File {
1491 pub fn from_proto(
1492 proto: rpc::proto::File,
1493 worktree: ModelHandle<Worktree>,
1494 cx: &AppContext,
1495 ) -> Result<Self> {
1496 let worktree_id = worktree
1497 .read(cx)
1498 .as_remote()
1499 .ok_or_else(|| anyhow!("not remote"))?
1500 .id();
1501
1502 if worktree_id.to_proto() != proto.worktree_id {
1503 return Err(anyhow!("worktree id does not match file"));
1504 }
1505
1506 Ok(Self {
1507 worktree,
1508 path: Path::new(&proto.path).into(),
1509 mtime: proto.mtime.ok_or_else(|| anyhow!("no timestamp"))?.into(),
1510 entry_id: proto.entry_id.map(ProjectEntryId::from_proto),
1511 is_local: false,
1512 })
1513 }
1514
1515 pub fn from_dyn(file: Option<&dyn language::File>) -> Option<&Self> {
1516 file.and_then(|f| f.as_any().downcast_ref())
1517 }
1518
1519 pub fn worktree_id(&self, cx: &AppContext) -> WorktreeId {
1520 self.worktree.read(cx).id()
1521 }
1522
1523 pub fn project_entry_id(&self, _: &AppContext) -> Option<ProjectEntryId> {
1524 self.entry_id
1525 }
1526}
1527
1528#[derive(Clone, Debug, PartialEq, Eq)]
1529pub struct Entry {
1530 pub id: ProjectEntryId,
1531 pub kind: EntryKind,
1532 pub path: Arc<Path>,
1533 pub inode: u64,
1534 pub mtime: SystemTime,
1535 pub is_symlink: bool,
1536 pub is_ignored: bool,
1537}
1538
1539#[derive(Clone, Debug, PartialEq, Eq)]
1540pub enum EntryKind {
1541 PendingDir,
1542 Dir,
1543 File(CharBag),
1544}
1545
1546impl Entry {
1547 fn new(
1548 path: Arc<Path>,
1549 metadata: &fs::Metadata,
1550 next_entry_id: &AtomicUsize,
1551 root_char_bag: CharBag,
1552 ) -> Self {
1553 Self {
1554 id: ProjectEntryId::new(next_entry_id),
1555 kind: if metadata.is_dir {
1556 EntryKind::PendingDir
1557 } else {
1558 EntryKind::File(char_bag_for_path(root_char_bag, &path))
1559 },
1560 path,
1561 inode: metadata.inode,
1562 mtime: metadata.mtime,
1563 is_symlink: metadata.is_symlink,
1564 is_ignored: false,
1565 }
1566 }
1567
1568 pub fn is_dir(&self) -> bool {
1569 matches!(self.kind, EntryKind::Dir | EntryKind::PendingDir)
1570 }
1571
1572 pub fn is_file(&self) -> bool {
1573 matches!(self.kind, EntryKind::File(_))
1574 }
1575}
1576
1577impl sum_tree::Item for Entry {
1578 type Summary = EntrySummary;
1579
1580 fn summary(&self) -> Self::Summary {
1581 let visible_count = if self.is_ignored { 0 } else { 1 };
1582 let file_count;
1583 let visible_file_count;
1584 if self.is_file() {
1585 file_count = 1;
1586 visible_file_count = visible_count;
1587 } else {
1588 file_count = 0;
1589 visible_file_count = 0;
1590 }
1591
1592 EntrySummary {
1593 max_path: self.path.clone(),
1594 count: 1,
1595 visible_count,
1596 file_count,
1597 visible_file_count,
1598 }
1599 }
1600}
1601
1602impl sum_tree::KeyedItem for Entry {
1603 type Key = PathKey;
1604
1605 fn key(&self) -> Self::Key {
1606 PathKey(self.path.clone())
1607 }
1608}
1609
1610#[derive(Clone, Debug)]
1611pub struct EntrySummary {
1612 max_path: Arc<Path>,
1613 count: usize,
1614 visible_count: usize,
1615 file_count: usize,
1616 visible_file_count: usize,
1617}
1618
1619impl Default for EntrySummary {
1620 fn default() -> Self {
1621 Self {
1622 max_path: Arc::from(Path::new("")),
1623 count: 0,
1624 visible_count: 0,
1625 file_count: 0,
1626 visible_file_count: 0,
1627 }
1628 }
1629}
1630
1631impl sum_tree::Summary for EntrySummary {
1632 type Context = ();
1633
1634 fn add_summary(&mut self, rhs: &Self, _: &()) {
1635 self.max_path = rhs.max_path.clone();
1636 self.visible_count += rhs.visible_count;
1637 self.file_count += rhs.file_count;
1638 self.visible_file_count += rhs.visible_file_count;
1639 }
1640}
1641
1642#[derive(Clone, Debug)]
1643struct PathEntry {
1644 id: ProjectEntryId,
1645 path: Arc<Path>,
1646 is_ignored: bool,
1647 scan_id: usize,
1648}
1649
1650impl sum_tree::Item for PathEntry {
1651 type Summary = PathEntrySummary;
1652
1653 fn summary(&self) -> Self::Summary {
1654 PathEntrySummary { max_id: self.id }
1655 }
1656}
1657
1658impl sum_tree::KeyedItem for PathEntry {
1659 type Key = ProjectEntryId;
1660
1661 fn key(&self) -> Self::Key {
1662 self.id
1663 }
1664}
1665
1666#[derive(Clone, Debug, Default)]
1667struct PathEntrySummary {
1668 max_id: ProjectEntryId,
1669}
1670
1671impl sum_tree::Summary for PathEntrySummary {
1672 type Context = ();
1673
1674 fn add_summary(&mut self, summary: &Self, _: &Self::Context) {
1675 self.max_id = summary.max_id;
1676 }
1677}
1678
1679impl<'a> sum_tree::Dimension<'a, PathEntrySummary> for ProjectEntryId {
1680 fn add_summary(&mut self, summary: &'a PathEntrySummary, _: &()) {
1681 *self = summary.max_id;
1682 }
1683}
1684
1685#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
1686pub struct PathKey(Arc<Path>);
1687
1688impl Default for PathKey {
1689 fn default() -> Self {
1690 Self(Path::new("").into())
1691 }
1692}
1693
1694impl<'a> sum_tree::Dimension<'a, EntrySummary> for PathKey {
1695 fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
1696 self.0 = summary.max_path.clone();
1697 }
1698}
1699
1700struct BackgroundScanner {
1701 fs: Arc<dyn Fs>,
1702 snapshot: Arc<Mutex<LocalSnapshot>>,
1703 notify: UnboundedSender<ScanState>,
1704 executor: Arc<executor::Background>,
1705}
1706
1707impl BackgroundScanner {
1708 fn new(
1709 snapshot: Arc<Mutex<LocalSnapshot>>,
1710 notify: UnboundedSender<ScanState>,
1711 fs: Arc<dyn Fs>,
1712 executor: Arc<executor::Background>,
1713 ) -> Self {
1714 Self {
1715 fs,
1716 snapshot,
1717 notify,
1718 executor,
1719 }
1720 }
1721
1722 fn abs_path(&self) -> Arc<Path> {
1723 self.snapshot.lock().abs_path.clone()
1724 }
1725
1726 fn snapshot(&self) -> LocalSnapshot {
1727 self.snapshot.lock().clone()
1728 }
1729
1730 async fn run(mut self, events_rx: impl Stream<Item = Vec<fsevent::Event>>) {
1731 if self.notify.unbounded_send(ScanState::Scanning).is_err() {
1732 return;
1733 }
1734
1735 if let Err(err) = self.scan_dirs().await {
1736 if self
1737 .notify
1738 .unbounded_send(ScanState::Err(Arc::new(err)))
1739 .is_err()
1740 {
1741 return;
1742 }
1743 }
1744
1745 if self.notify.unbounded_send(ScanState::Idle).is_err() {
1746 return;
1747 }
1748
1749 futures::pin_mut!(events_rx);
1750 while let Some(events) = events_rx.next().await {
1751 if self.notify.unbounded_send(ScanState::Scanning).is_err() {
1752 break;
1753 }
1754
1755 if !self.process_events(events).await {
1756 break;
1757 }
1758
1759 if self.notify.unbounded_send(ScanState::Idle).is_err() {
1760 break;
1761 }
1762 }
1763 }
1764
1765 async fn scan_dirs(&mut self) -> Result<()> {
1766 let root_char_bag;
1767 let next_entry_id;
1768 let is_dir;
1769 {
1770 let snapshot = self.snapshot.lock();
1771 root_char_bag = snapshot.root_char_bag;
1772 next_entry_id = snapshot.next_entry_id.clone();
1773 is_dir = snapshot.root_entry().map_or(false, |e| e.is_dir())
1774 };
1775
1776 if is_dir {
1777 let path: Arc<Path> = Arc::from(Path::new(""));
1778 let abs_path = self.abs_path();
1779 let (tx, rx) = channel::unbounded();
1780 tx.send(ScanJob {
1781 abs_path: abs_path.to_path_buf(),
1782 path,
1783 ignore_stack: IgnoreStack::none(),
1784 scan_queue: tx.clone(),
1785 })
1786 .await
1787 .unwrap();
1788 drop(tx);
1789
1790 self.executor
1791 .scoped(|scope| {
1792 for _ in 0..self.executor.num_cpus() {
1793 scope.spawn(async {
1794 while let Ok(job) = rx.recv().await {
1795 if let Err(err) = self
1796 .scan_dir(root_char_bag, next_entry_id.clone(), &job)
1797 .await
1798 {
1799 log::error!("error scanning {:?}: {}", job.abs_path, err);
1800 }
1801 }
1802 });
1803 }
1804 })
1805 .await;
1806 }
1807
1808 Ok(())
1809 }
1810
1811 async fn scan_dir(
1812 &self,
1813 root_char_bag: CharBag,
1814 next_entry_id: Arc<AtomicUsize>,
1815 job: &ScanJob,
1816 ) -> Result<()> {
1817 let mut new_entries: Vec<Entry> = Vec::new();
1818 let mut new_jobs: Vec<ScanJob> = Vec::new();
1819 let mut ignore_stack = job.ignore_stack.clone();
1820 let mut new_ignore = None;
1821
1822 let mut child_paths = self.fs.read_dir(&job.abs_path).await?;
1823 while let Some(child_abs_path) = child_paths.next().await {
1824 let child_abs_path = match child_abs_path {
1825 Ok(child_abs_path) => child_abs_path,
1826 Err(error) => {
1827 log::error!("error processing entry {:?}", error);
1828 continue;
1829 }
1830 };
1831 let child_name = child_abs_path.file_name().unwrap();
1832 let child_path: Arc<Path> = job.path.join(child_name).into();
1833 let child_metadata = match self.fs.metadata(&child_abs_path).await? {
1834 Some(metadata) => metadata,
1835 None => continue,
1836 };
1837
1838 // If we find a .gitignore, add it to the stack of ignores used to determine which paths are ignored
1839 if child_name == *GITIGNORE {
1840 match build_gitignore(&child_abs_path, self.fs.as_ref()) {
1841 Ok(ignore) => {
1842 let ignore = Arc::new(ignore);
1843 ignore_stack = ignore_stack.append(job.path.clone(), ignore.clone());
1844 new_ignore = Some(ignore);
1845 }
1846 Err(error) => {
1847 log::error!(
1848 "error loading .gitignore file {:?} - {:?}",
1849 child_name,
1850 error
1851 );
1852 }
1853 }
1854
1855 // Update ignore status of any child entries we've already processed to reflect the
1856 // ignore file in the current directory. Because `.gitignore` starts with a `.`,
1857 // there should rarely be too numerous. Update the ignore stack associated with any
1858 // new jobs as well.
1859 let mut new_jobs = new_jobs.iter_mut();
1860 for entry in &mut new_entries {
1861 entry.is_ignored = ignore_stack.is_path_ignored(&entry.path, entry.is_dir());
1862 if entry.is_dir() {
1863 new_jobs.next().unwrap().ignore_stack = if entry.is_ignored {
1864 IgnoreStack::all()
1865 } else {
1866 ignore_stack.clone()
1867 };
1868 }
1869 }
1870 }
1871
1872 let mut child_entry = Entry::new(
1873 child_path.clone(),
1874 &child_metadata,
1875 &next_entry_id,
1876 root_char_bag,
1877 );
1878
1879 if child_metadata.is_dir {
1880 let is_ignored = ignore_stack.is_path_ignored(&child_path, true);
1881 child_entry.is_ignored = is_ignored;
1882 new_entries.push(child_entry);
1883 new_jobs.push(ScanJob {
1884 abs_path: child_abs_path,
1885 path: child_path,
1886 ignore_stack: if is_ignored {
1887 IgnoreStack::all()
1888 } else {
1889 ignore_stack.clone()
1890 },
1891 scan_queue: job.scan_queue.clone(),
1892 });
1893 } else {
1894 child_entry.is_ignored = ignore_stack.is_path_ignored(&child_path, false);
1895 new_entries.push(child_entry);
1896 };
1897 }
1898
1899 self.snapshot
1900 .lock()
1901 .populate_dir(job.path.clone(), new_entries, new_ignore);
1902 for new_job in new_jobs {
1903 job.scan_queue.send(new_job).await.unwrap();
1904 }
1905
1906 Ok(())
1907 }
1908
1909 async fn process_events(&mut self, mut events: Vec<fsevent::Event>) -> bool {
1910 let mut snapshot = self.snapshot();
1911 snapshot.scan_id += 1;
1912
1913 let root_abs_path = if let Ok(abs_path) = self.fs.canonicalize(&snapshot.abs_path).await {
1914 abs_path
1915 } else {
1916 return false;
1917 };
1918 let root_char_bag = snapshot.root_char_bag;
1919 let next_entry_id = snapshot.next_entry_id.clone();
1920
1921 events.sort_unstable_by(|a, b| a.path.cmp(&b.path));
1922 events.dedup_by(|a, b| a.path.starts_with(&b.path));
1923
1924 for event in &events {
1925 match event.path.strip_prefix(&root_abs_path) {
1926 Ok(path) => snapshot.remove_path(&path),
1927 Err(_) => {
1928 log::error!(
1929 "unexpected event {:?} for root path {:?}",
1930 event.path,
1931 root_abs_path
1932 );
1933 continue;
1934 }
1935 }
1936 }
1937
1938 let (scan_queue_tx, scan_queue_rx) = channel::unbounded();
1939 for event in events {
1940 let path: Arc<Path> = match event.path.strip_prefix(&root_abs_path) {
1941 Ok(path) => Arc::from(path.to_path_buf()),
1942 Err(_) => {
1943 log::error!(
1944 "unexpected event {:?} for root path {:?}",
1945 event.path,
1946 root_abs_path
1947 );
1948 continue;
1949 }
1950 };
1951
1952 match self.fs.metadata(&event.path).await {
1953 Ok(Some(metadata)) => {
1954 let ignore_stack = snapshot.ignore_stack_for_path(&path, metadata.is_dir);
1955 let mut fs_entry = Entry::new(
1956 path.clone(),
1957 &metadata,
1958 snapshot.next_entry_id.as_ref(),
1959 snapshot.root_char_bag,
1960 );
1961 fs_entry.is_ignored = ignore_stack.is_all();
1962 snapshot.insert_entry(fs_entry, self.fs.as_ref());
1963 if metadata.is_dir {
1964 scan_queue_tx
1965 .send(ScanJob {
1966 abs_path: event.path,
1967 path,
1968 ignore_stack,
1969 scan_queue: scan_queue_tx.clone(),
1970 })
1971 .await
1972 .unwrap();
1973 }
1974 }
1975 Ok(None) => {}
1976 Err(err) => {
1977 // TODO - create a special 'error' entry in the entries tree to mark this
1978 log::error!("error reading file on event {:?}", err);
1979 }
1980 }
1981 }
1982
1983 *self.snapshot.lock() = snapshot;
1984
1985 // Scan any directories that were created as part of this event batch.
1986 drop(scan_queue_tx);
1987 self.executor
1988 .scoped(|scope| {
1989 for _ in 0..self.executor.num_cpus() {
1990 scope.spawn(async {
1991 while let Ok(job) = scan_queue_rx.recv().await {
1992 if let Err(err) = self
1993 .scan_dir(root_char_bag, next_entry_id.clone(), &job)
1994 .await
1995 {
1996 log::error!("error scanning {:?}: {}", job.abs_path, err);
1997 }
1998 }
1999 });
2000 }
2001 })
2002 .await;
2003
2004 // Attempt to detect renames only over a single batch of file-system events.
2005 self.snapshot.lock().removed_entry_ids.clear();
2006
2007 self.update_ignore_statuses().await;
2008 true
2009 }
2010
2011 async fn update_ignore_statuses(&self) {
2012 let mut snapshot = self.snapshot();
2013
2014 let mut ignores_to_update = Vec::new();
2015 let mut ignores_to_delete = Vec::new();
2016 for (parent_path, (_, scan_id)) in &snapshot.ignores {
2017 if *scan_id == snapshot.scan_id && snapshot.entry_for_path(parent_path).is_some() {
2018 ignores_to_update.push(parent_path.clone());
2019 }
2020
2021 let ignore_path = parent_path.join(&*GITIGNORE);
2022 if snapshot.entry_for_path(ignore_path).is_none() {
2023 ignores_to_delete.push(parent_path.clone());
2024 }
2025 }
2026
2027 for parent_path in ignores_to_delete {
2028 snapshot.ignores.remove(&parent_path);
2029 self.snapshot.lock().ignores.remove(&parent_path);
2030 }
2031
2032 let (ignore_queue_tx, ignore_queue_rx) = channel::unbounded();
2033 ignores_to_update.sort_unstable();
2034 let mut ignores_to_update = ignores_to_update.into_iter().peekable();
2035 while let Some(parent_path) = ignores_to_update.next() {
2036 while ignores_to_update
2037 .peek()
2038 .map_or(false, |p| p.starts_with(&parent_path))
2039 {
2040 ignores_to_update.next().unwrap();
2041 }
2042
2043 let ignore_stack = snapshot.ignore_stack_for_path(&parent_path, true);
2044 ignore_queue_tx
2045 .send(UpdateIgnoreStatusJob {
2046 path: parent_path,
2047 ignore_stack,
2048 ignore_queue: ignore_queue_tx.clone(),
2049 })
2050 .await
2051 .unwrap();
2052 }
2053 drop(ignore_queue_tx);
2054
2055 self.executor
2056 .scoped(|scope| {
2057 for _ in 0..self.executor.num_cpus() {
2058 scope.spawn(async {
2059 while let Ok(job) = ignore_queue_rx.recv().await {
2060 self.update_ignore_status(job, &snapshot).await;
2061 }
2062 });
2063 }
2064 })
2065 .await;
2066 }
2067
2068 async fn update_ignore_status(&self, job: UpdateIgnoreStatusJob, snapshot: &LocalSnapshot) {
2069 let mut ignore_stack = job.ignore_stack;
2070 if let Some((ignore, _)) = snapshot.ignores.get(&job.path) {
2071 ignore_stack = ignore_stack.append(job.path.clone(), ignore.clone());
2072 }
2073
2074 let mut entries_by_id_edits = Vec::new();
2075 let mut entries_by_path_edits = Vec::new();
2076 for mut entry in snapshot.child_entries(&job.path).cloned() {
2077 let was_ignored = entry.is_ignored;
2078 entry.is_ignored = ignore_stack.is_path_ignored(&entry.path, entry.is_dir());
2079 if entry.is_dir() {
2080 let child_ignore_stack = if entry.is_ignored {
2081 IgnoreStack::all()
2082 } else {
2083 ignore_stack.clone()
2084 };
2085 job.ignore_queue
2086 .send(UpdateIgnoreStatusJob {
2087 path: entry.path.clone(),
2088 ignore_stack: child_ignore_stack,
2089 ignore_queue: job.ignore_queue.clone(),
2090 })
2091 .await
2092 .unwrap();
2093 }
2094
2095 if entry.is_ignored != was_ignored {
2096 let mut path_entry = snapshot.entries_by_id.get(&entry.id, &()).unwrap().clone();
2097 path_entry.scan_id = snapshot.scan_id;
2098 path_entry.is_ignored = entry.is_ignored;
2099 entries_by_id_edits.push(Edit::Insert(path_entry));
2100 entries_by_path_edits.push(Edit::Insert(entry));
2101 }
2102 }
2103
2104 let mut snapshot = self.snapshot.lock();
2105 snapshot.entries_by_path.edit(entries_by_path_edits, &());
2106 snapshot.entries_by_id.edit(entries_by_id_edits, &());
2107 }
2108}
2109
2110async fn refresh_entry(
2111 fs: &dyn Fs,
2112 snapshot: &Mutex<LocalSnapshot>,
2113 path: Arc<Path>,
2114 abs_path: &Path,
2115) -> Result<Entry> {
2116 let root_char_bag;
2117 let next_entry_id;
2118 {
2119 let snapshot = snapshot.lock();
2120 root_char_bag = snapshot.root_char_bag;
2121 next_entry_id = snapshot.next_entry_id.clone();
2122 }
2123 let entry = Entry::new(
2124 path,
2125 &fs.metadata(abs_path)
2126 .await?
2127 .ok_or_else(|| anyhow!("could not read saved file metadata"))?,
2128 &next_entry_id,
2129 root_char_bag,
2130 );
2131 Ok(snapshot.lock().insert_entry(entry, fs))
2132}
2133
2134fn char_bag_for_path(root_char_bag: CharBag, path: &Path) -> CharBag {
2135 let mut result = root_char_bag;
2136 result.extend(
2137 path.to_string_lossy()
2138 .chars()
2139 .map(|c| c.to_ascii_lowercase()),
2140 );
2141 result
2142}
2143
2144struct ScanJob {
2145 abs_path: PathBuf,
2146 path: Arc<Path>,
2147 ignore_stack: Arc<IgnoreStack>,
2148 scan_queue: Sender<ScanJob>,
2149}
2150
2151struct UpdateIgnoreStatusJob {
2152 path: Arc<Path>,
2153 ignore_stack: Arc<IgnoreStack>,
2154 ignore_queue: Sender<UpdateIgnoreStatusJob>,
2155}
2156
2157pub trait WorktreeHandle {
2158 #[cfg(any(test, feature = "test-support"))]
2159 fn flush_fs_events<'a>(
2160 &self,
2161 cx: &'a gpui::TestAppContext,
2162 ) -> futures::future::LocalBoxFuture<'a, ()>;
2163}
2164
2165impl WorktreeHandle for ModelHandle<Worktree> {
2166 // When the worktree's FS event stream sometimes delivers "redundant" events for FS changes that
2167 // occurred before the worktree was constructed. These events can cause the worktree to perfrom
2168 // extra directory scans, and emit extra scan-state notifications.
2169 //
2170 // This function mutates the worktree's directory and waits for those mutations to be picked up,
2171 // to ensure that all redundant FS events have already been processed.
2172 #[cfg(any(test, feature = "test-support"))]
2173 fn flush_fs_events<'a>(
2174 &self,
2175 cx: &'a gpui::TestAppContext,
2176 ) -> futures::future::LocalBoxFuture<'a, ()> {
2177 use smol::future::FutureExt;
2178
2179 let filename = "fs-event-sentinel";
2180 let tree = self.clone();
2181 let (fs, root_path) = self.read_with(cx, |tree, _| {
2182 let tree = tree.as_local().unwrap();
2183 (tree.fs.clone(), tree.abs_path().clone())
2184 });
2185
2186 async move {
2187 fs.create_file(&root_path.join(filename), Default::default())
2188 .await
2189 .unwrap();
2190 tree.condition(&cx, |tree, _| tree.entry_for_path(filename).is_some())
2191 .await;
2192
2193 fs.remove_file(&root_path.join(filename), Default::default())
2194 .await
2195 .unwrap();
2196 tree.condition(&cx, |tree, _| tree.entry_for_path(filename).is_none())
2197 .await;
2198
2199 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2200 .await;
2201 }
2202 .boxed_local()
2203 }
2204}
2205
2206#[derive(Clone, Debug)]
2207struct TraversalProgress<'a> {
2208 max_path: &'a Path,
2209 count: usize,
2210 visible_count: usize,
2211 file_count: usize,
2212 visible_file_count: usize,
2213}
2214
2215impl<'a> TraversalProgress<'a> {
2216 fn count(&self, include_dirs: bool, include_ignored: bool) -> usize {
2217 match (include_ignored, include_dirs) {
2218 (true, true) => self.count,
2219 (true, false) => self.file_count,
2220 (false, true) => self.visible_count,
2221 (false, false) => self.visible_file_count,
2222 }
2223 }
2224}
2225
2226impl<'a> sum_tree::Dimension<'a, EntrySummary> for TraversalProgress<'a> {
2227 fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
2228 self.max_path = summary.max_path.as_ref();
2229 self.count += summary.count;
2230 self.visible_count += summary.visible_count;
2231 self.file_count += summary.file_count;
2232 self.visible_file_count += summary.visible_file_count;
2233 }
2234}
2235
2236impl<'a> Default for TraversalProgress<'a> {
2237 fn default() -> Self {
2238 Self {
2239 max_path: Path::new(""),
2240 count: 0,
2241 visible_count: 0,
2242 file_count: 0,
2243 visible_file_count: 0,
2244 }
2245 }
2246}
2247
2248pub struct Traversal<'a> {
2249 cursor: sum_tree::Cursor<'a, Entry, TraversalProgress<'a>>,
2250 include_ignored: bool,
2251 include_dirs: bool,
2252}
2253
2254impl<'a> Traversal<'a> {
2255 pub fn advance(&mut self) -> bool {
2256 self.advance_to_offset(self.offset() + 1)
2257 }
2258
2259 pub fn advance_to_offset(&mut self, offset: usize) -> bool {
2260 self.cursor.seek_forward(
2261 &TraversalTarget::Count {
2262 count: offset,
2263 include_dirs: self.include_dirs,
2264 include_ignored: self.include_ignored,
2265 },
2266 Bias::Right,
2267 &(),
2268 )
2269 }
2270
2271 pub fn advance_to_sibling(&mut self) -> bool {
2272 while let Some(entry) = self.cursor.item() {
2273 self.cursor.seek_forward(
2274 &TraversalTarget::PathSuccessor(&entry.path),
2275 Bias::Left,
2276 &(),
2277 );
2278 if let Some(entry) = self.cursor.item() {
2279 if (self.include_dirs || !entry.is_dir())
2280 && (self.include_ignored || !entry.is_ignored)
2281 {
2282 return true;
2283 }
2284 }
2285 }
2286 false
2287 }
2288
2289 pub fn entry(&self) -> Option<&'a Entry> {
2290 self.cursor.item()
2291 }
2292
2293 pub fn offset(&self) -> usize {
2294 self.cursor
2295 .start()
2296 .count(self.include_dirs, self.include_ignored)
2297 }
2298}
2299
2300impl<'a> Iterator for Traversal<'a> {
2301 type Item = &'a Entry;
2302
2303 fn next(&mut self) -> Option<Self::Item> {
2304 if let Some(item) = self.entry() {
2305 self.advance();
2306 Some(item)
2307 } else {
2308 None
2309 }
2310 }
2311}
2312
2313#[derive(Debug)]
2314enum TraversalTarget<'a> {
2315 Path(&'a Path),
2316 PathSuccessor(&'a Path),
2317 Count {
2318 count: usize,
2319 include_ignored: bool,
2320 include_dirs: bool,
2321 },
2322}
2323
2324impl<'a, 'b> SeekTarget<'a, EntrySummary, TraversalProgress<'a>> for TraversalTarget<'b> {
2325 fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: &()) -> Ordering {
2326 match self {
2327 TraversalTarget::Path(path) => path.cmp(&cursor_location.max_path),
2328 TraversalTarget::PathSuccessor(path) => {
2329 if !cursor_location.max_path.starts_with(path) {
2330 Ordering::Equal
2331 } else {
2332 Ordering::Greater
2333 }
2334 }
2335 TraversalTarget::Count {
2336 count,
2337 include_dirs,
2338 include_ignored,
2339 } => Ord::cmp(
2340 count,
2341 &cursor_location.count(*include_dirs, *include_ignored),
2342 ),
2343 }
2344 }
2345}
2346
2347struct ChildEntriesIter<'a> {
2348 parent_path: &'a Path,
2349 traversal: Traversal<'a>,
2350}
2351
2352impl<'a> Iterator for ChildEntriesIter<'a> {
2353 type Item = &'a Entry;
2354
2355 fn next(&mut self) -> Option<Self::Item> {
2356 if let Some(item) = self.traversal.entry() {
2357 if item.path.starts_with(&self.parent_path) {
2358 self.traversal.advance_to_sibling();
2359 return Some(item);
2360 }
2361 }
2362 None
2363 }
2364}
2365
2366impl<'a> From<&'a Entry> for proto::Entry {
2367 fn from(entry: &'a Entry) -> Self {
2368 Self {
2369 id: entry.id.to_proto(),
2370 is_dir: entry.is_dir(),
2371 path: entry.path.to_string_lossy().to_string(),
2372 inode: entry.inode,
2373 mtime: Some(entry.mtime.into()),
2374 is_symlink: entry.is_symlink,
2375 is_ignored: entry.is_ignored,
2376 }
2377 }
2378}
2379
2380impl<'a> TryFrom<(&'a CharBag, proto::Entry)> for Entry {
2381 type Error = anyhow::Error;
2382
2383 fn try_from((root_char_bag, entry): (&'a CharBag, proto::Entry)) -> Result<Self> {
2384 if let Some(mtime) = entry.mtime {
2385 let kind = if entry.is_dir {
2386 EntryKind::Dir
2387 } else {
2388 let mut char_bag = root_char_bag.clone();
2389 char_bag.extend(entry.path.chars().map(|c| c.to_ascii_lowercase()));
2390 EntryKind::File(char_bag)
2391 };
2392 let path: Arc<Path> = Arc::from(Path::new(&entry.path));
2393 Ok(Entry {
2394 id: ProjectEntryId::from_proto(entry.id),
2395 kind,
2396 path: path.clone(),
2397 inode: entry.inode,
2398 mtime: mtime.into(),
2399 is_symlink: entry.is_symlink,
2400 is_ignored: entry.is_ignored,
2401 })
2402 } else {
2403 Err(anyhow!(
2404 "missing mtime in remote worktree entry {:?}",
2405 entry.path
2406 ))
2407 }
2408 }
2409}
2410
2411#[cfg(test)]
2412mod tests {
2413 use super::*;
2414 use crate::fs::FakeFs;
2415 use anyhow::Result;
2416 use client::test::FakeHttpClient;
2417 use fs::RealFs;
2418 use rand::prelude::*;
2419 use serde_json::json;
2420 use std::{
2421 env,
2422 fmt::Write,
2423 time::{SystemTime, UNIX_EPOCH},
2424 };
2425 use util::test::temp_tree;
2426
2427 #[gpui::test]
2428 async fn test_traversal(cx: &mut gpui::TestAppContext) {
2429 let fs = FakeFs::new(cx.background());
2430 fs.insert_tree(
2431 "/root",
2432 json!({
2433 ".gitignore": "a/b\n",
2434 "a": {
2435 "b": "",
2436 "c": "",
2437 }
2438 }),
2439 )
2440 .await;
2441
2442 let http_client = FakeHttpClient::with_404_response();
2443 let client = Client::new(http_client);
2444
2445 let tree = Worktree::local(
2446 client,
2447 Arc::from(Path::new("/root")),
2448 true,
2449 fs,
2450 Default::default(),
2451 &mut cx.to_async(),
2452 )
2453 .await
2454 .unwrap();
2455 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2456 .await;
2457
2458 tree.read_with(cx, |tree, _| {
2459 assert_eq!(
2460 tree.entries(false)
2461 .map(|entry| entry.path.as_ref())
2462 .collect::<Vec<_>>(),
2463 vec![
2464 Path::new(""),
2465 Path::new(".gitignore"),
2466 Path::new("a"),
2467 Path::new("a/c"),
2468 ]
2469 );
2470 })
2471 }
2472
2473 #[gpui::test]
2474 async fn test_rescan_with_gitignore(cx: &mut gpui::TestAppContext) {
2475 let dir = temp_tree(json!({
2476 ".git": {},
2477 ".gitignore": "ignored-dir\n",
2478 "tracked-dir": {
2479 "tracked-file1": "tracked contents",
2480 },
2481 "ignored-dir": {
2482 "ignored-file1": "ignored contents",
2483 }
2484 }));
2485
2486 let http_client = FakeHttpClient::with_404_response();
2487 let client = Client::new(http_client.clone());
2488
2489 let tree = Worktree::local(
2490 client,
2491 dir.path(),
2492 true,
2493 Arc::new(RealFs),
2494 Default::default(),
2495 &mut cx.to_async(),
2496 )
2497 .await
2498 .unwrap();
2499 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2500 .await;
2501 tree.flush_fs_events(&cx).await;
2502 cx.read(|cx| {
2503 let tree = tree.read(cx);
2504 let tracked = tree.entry_for_path("tracked-dir/tracked-file1").unwrap();
2505 let ignored = tree.entry_for_path("ignored-dir/ignored-file1").unwrap();
2506 assert_eq!(tracked.is_ignored, false);
2507 assert_eq!(ignored.is_ignored, true);
2508 });
2509
2510 std::fs::write(dir.path().join("tracked-dir/tracked-file2"), "").unwrap();
2511 std::fs::write(dir.path().join("ignored-dir/ignored-file2"), "").unwrap();
2512 tree.flush_fs_events(&cx).await;
2513 cx.read(|cx| {
2514 let tree = tree.read(cx);
2515 let dot_git = tree.entry_for_path(".git").unwrap();
2516 let tracked = tree.entry_for_path("tracked-dir/tracked-file2").unwrap();
2517 let ignored = tree.entry_for_path("ignored-dir/ignored-file2").unwrap();
2518 assert_eq!(tracked.is_ignored, false);
2519 assert_eq!(ignored.is_ignored, true);
2520 assert_eq!(dot_git.is_ignored, true);
2521 });
2522 }
2523
2524 #[gpui::test(iterations = 100)]
2525 fn test_random(mut rng: StdRng) {
2526 let operations = env::var("OPERATIONS")
2527 .map(|o| o.parse().unwrap())
2528 .unwrap_or(40);
2529 let initial_entries = env::var("INITIAL_ENTRIES")
2530 .map(|o| o.parse().unwrap())
2531 .unwrap_or(20);
2532
2533 let root_dir = tempdir::TempDir::new("worktree-test").unwrap();
2534 for _ in 0..initial_entries {
2535 randomly_mutate_tree(root_dir.path(), 1.0, &mut rng).unwrap();
2536 }
2537 log::info!("Generated initial tree");
2538
2539 let (notify_tx, _notify_rx) = mpsc::unbounded();
2540 let fs = Arc::new(RealFs);
2541 let next_entry_id = Arc::new(AtomicUsize::new(0));
2542 let mut initial_snapshot = LocalSnapshot {
2543 abs_path: root_dir.path().into(),
2544 scan_id: 0,
2545 removed_entry_ids: Default::default(),
2546 ignores: Default::default(),
2547 next_entry_id: next_entry_id.clone(),
2548 snapshot: Snapshot {
2549 id: WorktreeId::from_usize(0),
2550 entries_by_path: Default::default(),
2551 entries_by_id: Default::default(),
2552 root_name: Default::default(),
2553 root_char_bag: Default::default(),
2554 },
2555 };
2556 initial_snapshot.insert_entry(
2557 Entry::new(
2558 Path::new("").into(),
2559 &smol::block_on(fs.metadata(root_dir.path()))
2560 .unwrap()
2561 .unwrap(),
2562 &next_entry_id,
2563 Default::default(),
2564 ),
2565 fs.as_ref(),
2566 );
2567 let mut scanner = BackgroundScanner::new(
2568 Arc::new(Mutex::new(initial_snapshot.clone())),
2569 notify_tx,
2570 fs.clone(),
2571 Arc::new(gpui::executor::Background::new()),
2572 );
2573 smol::block_on(scanner.scan_dirs()).unwrap();
2574 scanner.snapshot().check_invariants();
2575
2576 let mut events = Vec::new();
2577 let mut snapshots = Vec::new();
2578 let mut mutations_len = operations;
2579 while mutations_len > 1 {
2580 if !events.is_empty() && rng.gen_bool(0.4) {
2581 let len = rng.gen_range(0..=events.len());
2582 let to_deliver = events.drain(0..len).collect::<Vec<_>>();
2583 log::info!("Delivering events: {:#?}", to_deliver);
2584 smol::block_on(scanner.process_events(to_deliver));
2585 scanner.snapshot().check_invariants();
2586 } else {
2587 events.extend(randomly_mutate_tree(root_dir.path(), 0.6, &mut rng).unwrap());
2588 mutations_len -= 1;
2589 }
2590
2591 if rng.gen_bool(0.2) {
2592 snapshots.push(scanner.snapshot());
2593 }
2594 }
2595 log::info!("Quiescing: {:#?}", events);
2596 smol::block_on(scanner.process_events(events));
2597 scanner.snapshot().check_invariants();
2598
2599 let (notify_tx, _notify_rx) = mpsc::unbounded();
2600 let mut new_scanner = BackgroundScanner::new(
2601 Arc::new(Mutex::new(initial_snapshot)),
2602 notify_tx,
2603 scanner.fs.clone(),
2604 scanner.executor.clone(),
2605 );
2606 smol::block_on(new_scanner.scan_dirs()).unwrap();
2607 assert_eq!(
2608 scanner.snapshot().to_vec(true),
2609 new_scanner.snapshot().to_vec(true)
2610 );
2611
2612 for mut prev_snapshot in snapshots {
2613 let include_ignored = rng.gen::<bool>();
2614 if !include_ignored {
2615 let mut entries_by_path_edits = Vec::new();
2616 let mut entries_by_id_edits = Vec::new();
2617 for entry in prev_snapshot
2618 .entries_by_id
2619 .cursor::<()>()
2620 .filter(|e| e.is_ignored)
2621 {
2622 entries_by_path_edits.push(Edit::Remove(PathKey(entry.path.clone())));
2623 entries_by_id_edits.push(Edit::Remove(entry.id));
2624 }
2625
2626 prev_snapshot
2627 .entries_by_path
2628 .edit(entries_by_path_edits, &());
2629 prev_snapshot.entries_by_id.edit(entries_by_id_edits, &());
2630 }
2631
2632 let update = scanner
2633 .snapshot()
2634 .build_update(&prev_snapshot, 0, 0, include_ignored);
2635 prev_snapshot.apply_remote_update(update).unwrap();
2636 assert_eq!(
2637 prev_snapshot.to_vec(true),
2638 scanner.snapshot().to_vec(include_ignored)
2639 );
2640 }
2641 }
2642
2643 fn randomly_mutate_tree(
2644 root_path: &Path,
2645 insertion_probability: f64,
2646 rng: &mut impl Rng,
2647 ) -> Result<Vec<fsevent::Event>> {
2648 let root_path = root_path.canonicalize().unwrap();
2649 let (dirs, files) = read_dir_recursive(root_path.clone());
2650
2651 let mut events = Vec::new();
2652 let mut record_event = |path: PathBuf| {
2653 events.push(fsevent::Event {
2654 event_id: SystemTime::now()
2655 .duration_since(UNIX_EPOCH)
2656 .unwrap()
2657 .as_secs(),
2658 flags: fsevent::StreamFlags::empty(),
2659 path,
2660 });
2661 };
2662
2663 if (files.is_empty() && dirs.len() == 1) || rng.gen_bool(insertion_probability) {
2664 let path = dirs.choose(rng).unwrap();
2665 let new_path = path.join(gen_name(rng));
2666
2667 if rng.gen() {
2668 log::info!("Creating dir {:?}", new_path.strip_prefix(root_path)?);
2669 std::fs::create_dir(&new_path)?;
2670 } else {
2671 log::info!("Creating file {:?}", new_path.strip_prefix(root_path)?);
2672 std::fs::write(&new_path, "")?;
2673 }
2674 record_event(new_path);
2675 } else if rng.gen_bool(0.05) {
2676 let ignore_dir_path = dirs.choose(rng).unwrap();
2677 let ignore_path = ignore_dir_path.join(&*GITIGNORE);
2678
2679 let (subdirs, subfiles) = read_dir_recursive(ignore_dir_path.clone());
2680 let files_to_ignore = {
2681 let len = rng.gen_range(0..=subfiles.len());
2682 subfiles.choose_multiple(rng, len)
2683 };
2684 let dirs_to_ignore = {
2685 let len = rng.gen_range(0..subdirs.len());
2686 subdirs.choose_multiple(rng, len)
2687 };
2688
2689 let mut ignore_contents = String::new();
2690 for path_to_ignore in files_to_ignore.chain(dirs_to_ignore) {
2691 write!(
2692 ignore_contents,
2693 "{}\n",
2694 path_to_ignore
2695 .strip_prefix(&ignore_dir_path)?
2696 .to_str()
2697 .unwrap()
2698 )
2699 .unwrap();
2700 }
2701 log::info!(
2702 "Creating {:?} with contents:\n{}",
2703 ignore_path.strip_prefix(&root_path)?,
2704 ignore_contents
2705 );
2706 std::fs::write(&ignore_path, ignore_contents).unwrap();
2707 record_event(ignore_path);
2708 } else {
2709 let old_path = {
2710 let file_path = files.choose(rng);
2711 let dir_path = dirs[1..].choose(rng);
2712 file_path.into_iter().chain(dir_path).choose(rng).unwrap()
2713 };
2714
2715 let is_rename = rng.gen();
2716 if is_rename {
2717 let new_path_parent = dirs
2718 .iter()
2719 .filter(|d| !d.starts_with(old_path))
2720 .choose(rng)
2721 .unwrap();
2722
2723 let overwrite_existing_dir =
2724 !old_path.starts_with(&new_path_parent) && rng.gen_bool(0.3);
2725 let new_path = if overwrite_existing_dir {
2726 std::fs::remove_dir_all(&new_path_parent).ok();
2727 new_path_parent.to_path_buf()
2728 } else {
2729 new_path_parent.join(gen_name(rng))
2730 };
2731
2732 log::info!(
2733 "Renaming {:?} to {}{:?}",
2734 old_path.strip_prefix(&root_path)?,
2735 if overwrite_existing_dir {
2736 "overwrite "
2737 } else {
2738 ""
2739 },
2740 new_path.strip_prefix(&root_path)?
2741 );
2742 std::fs::rename(&old_path, &new_path)?;
2743 record_event(old_path.clone());
2744 record_event(new_path);
2745 } else if old_path.is_dir() {
2746 let (dirs, files) = read_dir_recursive(old_path.clone());
2747
2748 log::info!("Deleting dir {:?}", old_path.strip_prefix(&root_path)?);
2749 std::fs::remove_dir_all(&old_path).unwrap();
2750 for file in files {
2751 record_event(file);
2752 }
2753 for dir in dirs {
2754 record_event(dir);
2755 }
2756 } else {
2757 log::info!("Deleting file {:?}", old_path.strip_prefix(&root_path)?);
2758 std::fs::remove_file(old_path).unwrap();
2759 record_event(old_path.clone());
2760 }
2761 }
2762
2763 Ok(events)
2764 }
2765
2766 fn read_dir_recursive(path: PathBuf) -> (Vec<PathBuf>, Vec<PathBuf>) {
2767 let child_entries = std::fs::read_dir(&path).unwrap();
2768 let mut dirs = vec![path];
2769 let mut files = Vec::new();
2770 for child_entry in child_entries {
2771 let child_path = child_entry.unwrap().path();
2772 if child_path.is_dir() {
2773 let (child_dirs, child_files) = read_dir_recursive(child_path);
2774 dirs.extend(child_dirs);
2775 files.extend(child_files);
2776 } else {
2777 files.push(child_path);
2778 }
2779 }
2780 (dirs, files)
2781 }
2782
2783 fn gen_name(rng: &mut impl Rng) -> String {
2784 (0..6)
2785 .map(|_| rng.sample(rand::distributions::Alphanumeric))
2786 .map(char::from)
2787 .collect()
2788 }
2789
2790 impl LocalSnapshot {
2791 fn check_invariants(&self) {
2792 let mut files = self.files(true, 0);
2793 let mut visible_files = self.files(false, 0);
2794 for entry in self.entries_by_path.cursor::<()>() {
2795 if entry.is_file() {
2796 assert_eq!(files.next().unwrap().inode, entry.inode);
2797 if !entry.is_ignored {
2798 assert_eq!(visible_files.next().unwrap().inode, entry.inode);
2799 }
2800 }
2801 }
2802 assert!(files.next().is_none());
2803 assert!(visible_files.next().is_none());
2804
2805 let mut bfs_paths = Vec::new();
2806 let mut stack = vec![Path::new("")];
2807 while let Some(path) = stack.pop() {
2808 bfs_paths.push(path);
2809 let ix = stack.len();
2810 for child_entry in self.child_entries(path) {
2811 stack.insert(ix, &child_entry.path);
2812 }
2813 }
2814
2815 let dfs_paths = self
2816 .entries_by_path
2817 .cursor::<()>()
2818 .map(|e| e.path.as_ref())
2819 .collect::<Vec<_>>();
2820 assert_eq!(bfs_paths, dfs_paths);
2821
2822 for (ignore_parent_path, _) in &self.ignores {
2823 assert!(self.entry_for_path(ignore_parent_path).is_some());
2824 assert!(self
2825 .entry_for_path(ignore_parent_path.join(&*GITIGNORE))
2826 .is_some());
2827 }
2828 }
2829
2830 fn to_vec(&self, include_ignored: bool) -> Vec<(&Path, u64, bool)> {
2831 let mut paths = Vec::new();
2832 for entry in self.entries_by_path.cursor::<()>() {
2833 if include_ignored || !entry.is_ignored {
2834 paths.push((entry.path.as_ref(), entry.inode, entry.is_ignored));
2835 }
2836 }
2837 paths.sort_by(|a, b| a.0.cmp(&b.0));
2838 paths
2839 }
2840 }
2841}