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