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