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