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