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