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