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