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