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