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