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