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