1use crate::{
2 copy_recursive, ignore::IgnoreStack, DiagnosticSummary, ProjectEntryId, RemoveOptions,
3};
4use ::ignore::gitignore::{Gitignore, GitignoreBuilder};
5use anyhow::{anyhow, Context, Result};
6use client::{proto, Client};
7use clock::ReplicaId;
8use collections::{HashMap, VecDeque};
9use fs::{
10 repository::{GitFileStatus, GitRepository, RepoPath, RepoPathDescendants},
11 Fs, LineEnding,
12};
13use futures::{
14 channel::{
15 mpsc::{self, UnboundedSender},
16 oneshot,
17 },
18 select_biased,
19 task::Poll,
20 Stream, StreamExt,
21};
22use fuzzy::CharBag;
23use git::{DOT_GIT, GITIGNORE};
24use gpui::{executor, AppContext, AsyncAppContext, Entity, ModelContext, ModelHandle, Task};
25use language::{
26 proto::{
27 deserialize_fingerprint, deserialize_version, serialize_fingerprint, serialize_line_ending,
28 serialize_version,
29 },
30 Buffer, DiagnosticEntry, File as _, PointUtf16, Rope, RopeFingerprint, Unclipped,
31};
32use lsp::LanguageServerId;
33use parking_lot::Mutex;
34use postage::{
35 barrier,
36 prelude::{Sink as _, Stream as _},
37 watch,
38};
39use smol::channel::{self, Sender};
40use std::{
41 any::Any,
42 cmp::{self, Ordering},
43 convert::TryFrom,
44 ffi::OsStr,
45 fmt,
46 future::Future,
47 mem,
48 ops::{Deref, DerefMut},
49 path::{Path, PathBuf},
50 pin::Pin,
51 sync::{
52 atomic::{AtomicUsize, Ordering::SeqCst},
53 Arc,
54 },
55 time::{Duration, SystemTime},
56};
57use sum_tree::{Bias, Edit, SeekTarget, SumTree, TreeMap, TreeSet};
58use util::{paths::HOME, ResultExt, TakeUntilExt, TryFutureExt};
59
60#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash, PartialOrd, Ord)]
61pub struct WorktreeId(usize);
62
63pub enum Worktree {
64 Local(LocalWorktree),
65 Remote(RemoteWorktree),
66}
67
68pub struct LocalWorktree {
69 snapshot: LocalSnapshot,
70 path_changes_tx: channel::Sender<(Vec<PathBuf>, barrier::Sender)>,
71 is_scanning: (watch::Sender<bool>, watch::Receiver<bool>),
72 _background_scanner_task: Task<()>,
73 share: Option<ShareState>,
74 diagnostics: HashMap<
75 Arc<Path>,
76 Vec<(
77 LanguageServerId,
78 Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
79 )>,
80 >,
81 diagnostic_summaries: HashMap<Arc<Path>, HashMap<LanguageServerId, DiagnosticSummary>>,
82 client: Arc<Client>,
83 fs: Arc<dyn Fs>,
84 visible: bool,
85}
86
87pub struct RemoteWorktree {
88 snapshot: Snapshot,
89 background_snapshot: Arc<Mutex<Snapshot>>,
90 project_id: u64,
91 client: Arc<Client>,
92 updates_tx: Option<UnboundedSender<proto::UpdateWorktree>>,
93 snapshot_subscriptions: VecDeque<(usize, oneshot::Sender<()>)>,
94 replica_id: ReplicaId,
95 diagnostic_summaries: HashMap<Arc<Path>, HashMap<LanguageServerId, DiagnosticSummary>>,
96 visible: bool,
97 disconnected: bool,
98}
99
100#[derive(Clone)]
101pub struct Snapshot {
102 id: WorktreeId,
103 abs_path: Arc<Path>,
104 root_name: String,
105 root_char_bag: CharBag,
106 entries_by_path: SumTree<Entry>,
107 entries_by_id: SumTree<PathEntry>,
108 repository_entries: TreeMap<RepositoryWorkDirectory, RepositoryEntry>,
109
110 /// A number that increases every time the worktree begins scanning
111 /// a set of paths from the filesystem. This scanning could be caused
112 /// by some operation performed on the worktree, such as reading or
113 /// writing a file, or by an event reported by the filesystem.
114 scan_id: usize,
115
116 /// The latest scan id that has completed, and whose preceding scans
117 /// have all completed. The current `scan_id` could be more than one
118 /// greater than the `completed_scan_id` if operations are performed
119 /// on the worktree while it is processing a file-system event.
120 completed_scan_id: usize,
121}
122
123#[derive(Clone, Debug, PartialEq, Eq)]
124pub struct RepositoryEntry {
125 pub(crate) work_directory: WorkDirectoryEntry,
126 pub(crate) branch: Option<Arc<str>>,
127 pub(crate) statuses: TreeMap<RepoPath, GitFileStatus>,
128}
129
130fn read_git_status(git_status: i32) -> Option<GitFileStatus> {
131 proto::GitStatus::from_i32(git_status).map(|status| match status {
132 proto::GitStatus::Added => GitFileStatus::Added,
133 proto::GitStatus::Modified => GitFileStatus::Modified,
134 proto::GitStatus::Conflict => GitFileStatus::Conflict,
135 })
136}
137
138impl RepositoryEntry {
139 pub fn branch(&self) -> Option<Arc<str>> {
140 self.branch.clone()
141 }
142
143 pub fn work_directory_id(&self) -> ProjectEntryId {
144 *self.work_directory
145 }
146
147 pub fn work_directory(&self, snapshot: &Snapshot) -> Option<RepositoryWorkDirectory> {
148 snapshot
149 .entry_for_id(self.work_directory_id())
150 .map(|entry| RepositoryWorkDirectory(entry.path.clone()))
151 }
152
153 pub fn status_for_file(&self, snapshot: &Snapshot, path: &Path) -> Option<GitFileStatus> {
154 self.work_directory
155 .relativize(snapshot, path)
156 .and_then(|repo_path| self.statuses.get(&repo_path))
157 .cloned()
158 }
159
160 pub fn status_for_path(&self, snapshot: &Snapshot, path: &Path) -> Option<GitFileStatus> {
161 self.work_directory
162 .relativize(snapshot, path)
163 .and_then(|repo_path| {
164 self.statuses
165 .iter_from(&repo_path)
166 .take_while(|(key, _)| key.starts_with(&repo_path))
167 // Short circut once we've found the highest level
168 .take_until(|(_, status)| status == &&GitFileStatus::Conflict)
169 .map(|(_, status)| status)
170 .reduce(
171 |status_first, status_second| match (status_first, status_second) {
172 (GitFileStatus::Conflict, _) | (_, GitFileStatus::Conflict) => {
173 &GitFileStatus::Conflict
174 }
175 (GitFileStatus::Modified, _) | (_, GitFileStatus::Modified) => {
176 &GitFileStatus::Modified
177 }
178 _ => &GitFileStatus::Added,
179 },
180 )
181 .copied()
182 })
183 }
184
185 pub fn build_update(&self, other: &Self) -> proto::RepositoryEntry {
186 let mut updated_statuses: Vec<proto::StatusEntry> = Vec::new();
187 let mut removed_statuses: Vec<String> = Vec::new();
188
189 let mut self_statuses = self.statuses.iter().peekable();
190 let mut other_statuses = other.statuses.iter().peekable();
191 loop {
192 match (self_statuses.peek(), other_statuses.peek()) {
193 (Some((self_repo_path, self_status)), Some((other_repo_path, other_status))) => {
194 match Ord::cmp(self_repo_path, other_repo_path) {
195 Ordering::Less => {
196 updated_statuses.push(make_status_entry(self_repo_path, self_status));
197 self_statuses.next();
198 }
199 Ordering::Equal => {
200 if self_status != other_status {
201 updated_statuses
202 .push(make_status_entry(self_repo_path, self_status));
203 }
204
205 self_statuses.next();
206 other_statuses.next();
207 }
208 Ordering::Greater => {
209 removed_statuses.push(make_repo_path(other_repo_path));
210 other_statuses.next();
211 }
212 }
213 }
214 (Some((self_repo_path, self_status)), None) => {
215 updated_statuses.push(make_status_entry(self_repo_path, self_status));
216 self_statuses.next();
217 }
218 (None, Some((other_repo_path, _))) => {
219 removed_statuses.push(make_repo_path(other_repo_path));
220 other_statuses.next();
221 }
222 (None, None) => break,
223 }
224 }
225
226 proto::RepositoryEntry {
227 work_directory_id: self.work_directory_id().to_proto(),
228 branch: self.branch.as_ref().map(|str| str.to_string()),
229 removed_repo_paths: removed_statuses,
230 updated_statuses,
231 }
232 }
233}
234
235fn make_repo_path(path: &RepoPath) -> String {
236 path.as_os_str().to_string_lossy().to_string()
237}
238
239fn make_status_entry(path: &RepoPath, status: &GitFileStatus) -> proto::StatusEntry {
240 proto::StatusEntry {
241 repo_path: make_repo_path(path),
242 status: match status {
243 GitFileStatus::Added => proto::GitStatus::Added.into(),
244 GitFileStatus::Modified => proto::GitStatus::Modified.into(),
245 GitFileStatus::Conflict => proto::GitStatus::Conflict.into(),
246 },
247 }
248}
249
250impl From<&RepositoryEntry> for proto::RepositoryEntry {
251 fn from(value: &RepositoryEntry) -> Self {
252 proto::RepositoryEntry {
253 work_directory_id: value.work_directory.to_proto(),
254 branch: value.branch.as_ref().map(|str| str.to_string()),
255 updated_statuses: value
256 .statuses
257 .iter()
258 .map(|(repo_path, status)| make_status_entry(repo_path, status))
259 .collect(),
260 removed_repo_paths: Default::default(),
261 }
262 }
263}
264
265/// This path corresponds to the 'content path' (the folder that contains the .git)
266#[derive(Clone, Debug, Ord, PartialOrd, Eq, PartialEq)]
267pub struct RepositoryWorkDirectory(Arc<Path>);
268
269impl Default for RepositoryWorkDirectory {
270 fn default() -> Self {
271 RepositoryWorkDirectory(Arc::from(Path::new("")))
272 }
273}
274
275impl AsRef<Path> for RepositoryWorkDirectory {
276 fn as_ref(&self) -> &Path {
277 self.0.as_ref()
278 }
279}
280
281#[derive(Clone, Debug, Ord, PartialOrd, Eq, PartialEq)]
282pub struct WorkDirectoryEntry(ProjectEntryId);
283
284impl WorkDirectoryEntry {
285 pub(crate) fn relativize(&self, worktree: &Snapshot, path: &Path) -> Option<RepoPath> {
286 worktree.entry_for_id(self.0).and_then(|entry| {
287 path.strip_prefix(&entry.path)
288 .ok()
289 .map(move |path| path.into())
290 })
291 }
292}
293
294impl Deref for WorkDirectoryEntry {
295 type Target = ProjectEntryId;
296
297 fn deref(&self) -> &Self::Target {
298 &self.0
299 }
300}
301
302impl<'a> From<ProjectEntryId> for WorkDirectoryEntry {
303 fn from(value: ProjectEntryId) -> Self {
304 WorkDirectoryEntry(value)
305 }
306}
307
308#[derive(Debug, Clone)]
309pub struct LocalSnapshot {
310 snapshot: Snapshot,
311 /// All of the gitignore files in the worktree, indexed by their relative path.
312 /// The boolean indicates whether the gitignore needs to be updated.
313 ignores_by_parent_abs_path: HashMap<Arc<Path>, (Arc<Gitignore>, bool)>,
314 /// All of the git repositories in the worktree, indexed by the project entry
315 /// id of their parent directory.
316 git_repositories: TreeMap<ProjectEntryId, LocalRepositoryEntry>,
317}
318
319pub struct LocalMutableSnapshot {
320 snapshot: LocalSnapshot,
321 /// The ids of all of the entries that were removed from the snapshot
322 /// as part of the current update. These entry ids may be re-used
323 /// if the same inode is discovered at a new path, or if the given
324 /// path is re-created after being deleted.
325 removed_entry_ids: HashMap<u64, ProjectEntryId>,
326}
327
328#[derive(Debug, Clone)]
329pub struct LocalRepositoryEntry {
330 pub(crate) scan_id: usize,
331 pub(crate) full_scan_id: usize,
332 pub(crate) repo_ptr: Arc<Mutex<dyn GitRepository>>,
333 /// Path to the actual .git folder.
334 /// Note: if .git is a file, this points to the folder indicated by the .git file
335 pub(crate) git_dir_path: Arc<Path>,
336}
337
338impl LocalRepositoryEntry {
339 // Note that this path should be relative to the worktree root.
340 pub(crate) fn in_dot_git(&self, path: &Path) -> bool {
341 path.starts_with(self.git_dir_path.as_ref())
342 }
343}
344
345impl Deref for LocalSnapshot {
346 type Target = Snapshot;
347
348 fn deref(&self) -> &Self::Target {
349 &self.snapshot
350 }
351}
352
353impl DerefMut for LocalSnapshot {
354 fn deref_mut(&mut self) -> &mut Self::Target {
355 &mut self.snapshot
356 }
357}
358
359impl Deref for LocalMutableSnapshot {
360 type Target = LocalSnapshot;
361
362 fn deref(&self) -> &Self::Target {
363 &self.snapshot
364 }
365}
366
367impl DerefMut for LocalMutableSnapshot {
368 fn deref_mut(&mut self) -> &mut Self::Target {
369 &mut self.snapshot
370 }
371}
372
373enum ScanState {
374 Started,
375 Updated {
376 snapshot: LocalSnapshot,
377 changes: HashMap<(Arc<Path>, ProjectEntryId), PathChange>,
378 barrier: Option<barrier::Sender>,
379 scanning: bool,
380 },
381}
382
383struct ShareState {
384 project_id: u64,
385 snapshots_tx: watch::Sender<LocalSnapshot>,
386 resume_updates: watch::Sender<()>,
387 _maintain_remote_snapshot: Task<Option<()>>,
388}
389
390pub enum Event {
391 UpdatedEntries(HashMap<(Arc<Path>, ProjectEntryId), PathChange>),
392 UpdatedGitRepositories(HashMap<Arc<Path>, LocalRepositoryEntry>),
393}
394
395impl Entity for Worktree {
396 type Event = Event;
397}
398
399impl Worktree {
400 pub async fn local(
401 client: Arc<Client>,
402 path: impl Into<Arc<Path>>,
403 visible: bool,
404 fs: Arc<dyn Fs>,
405 next_entry_id: Arc<AtomicUsize>,
406 cx: &mut AsyncAppContext,
407 ) -> Result<ModelHandle<Self>> {
408 // After determining whether the root entry is a file or a directory, populate the
409 // snapshot's "root name", which will be used for the purpose of fuzzy matching.
410 let abs_path = path.into();
411 let metadata = fs
412 .metadata(&abs_path)
413 .await
414 .context("failed to stat worktree path")?;
415
416 Ok(cx.add_model(move |cx: &mut ModelContext<Worktree>| {
417 let root_name = abs_path
418 .file_name()
419 .map_or(String::new(), |f| f.to_string_lossy().to_string());
420
421 let mut snapshot = LocalSnapshot {
422 ignores_by_parent_abs_path: Default::default(),
423 git_repositories: Default::default(),
424 snapshot: Snapshot {
425 id: WorktreeId::from_usize(cx.model_id()),
426 abs_path: abs_path.clone(),
427 root_name: root_name.clone(),
428 root_char_bag: root_name.chars().map(|c| c.to_ascii_lowercase()).collect(),
429 entries_by_path: Default::default(),
430 entries_by_id: Default::default(),
431 repository_entries: Default::default(),
432 scan_id: 1,
433 completed_scan_id: 0,
434 },
435 };
436
437 if let Some(metadata) = metadata {
438 snapshot.insert_entry(
439 Entry::new(
440 Arc::from(Path::new("")),
441 &metadata,
442 &next_entry_id,
443 snapshot.root_char_bag,
444 ),
445 fs.as_ref(),
446 );
447 }
448
449 let (path_changes_tx, path_changes_rx) = channel::unbounded();
450 let (scan_states_tx, mut scan_states_rx) = mpsc::unbounded();
451
452 cx.spawn_weak(|this, mut cx| async move {
453 while let Some((state, this)) = scan_states_rx.next().await.zip(this.upgrade(&cx)) {
454 this.update(&mut cx, |this, cx| {
455 let this = this.as_local_mut().unwrap();
456 match state {
457 ScanState::Started => {
458 *this.is_scanning.0.borrow_mut() = true;
459 }
460 ScanState::Updated {
461 snapshot,
462 changes,
463 barrier,
464 scanning,
465 } => {
466 *this.is_scanning.0.borrow_mut() = scanning;
467 this.set_snapshot(snapshot, cx);
468 cx.emit(Event::UpdatedEntries(changes));
469 drop(barrier);
470 }
471 }
472 cx.notify();
473 });
474 }
475 })
476 .detach();
477
478 let background_scanner_task = cx.background().spawn({
479 let fs = fs.clone();
480 let snapshot = snapshot.clone();
481 let background = cx.background().clone();
482 async move {
483 let events = fs.watch(&abs_path, Duration::from_millis(100)).await;
484 BackgroundScanner::new(
485 snapshot,
486 next_entry_id,
487 fs,
488 scan_states_tx,
489 background,
490 path_changes_rx,
491 )
492 .run(events)
493 .await;
494 }
495 });
496
497 Worktree::Local(LocalWorktree {
498 snapshot,
499 is_scanning: watch::channel_with(true),
500 share: None,
501 path_changes_tx,
502 _background_scanner_task: background_scanner_task,
503 diagnostics: Default::default(),
504 diagnostic_summaries: Default::default(),
505 client,
506 fs,
507 visible,
508 })
509 }))
510 }
511
512 pub fn remote(
513 project_remote_id: u64,
514 replica_id: ReplicaId,
515 worktree: proto::WorktreeMetadata,
516 client: Arc<Client>,
517 cx: &mut AppContext,
518 ) -> ModelHandle<Self> {
519 cx.add_model(|cx: &mut ModelContext<Self>| {
520 let snapshot = Snapshot {
521 id: WorktreeId(worktree.id as usize),
522 abs_path: Arc::from(PathBuf::from(worktree.abs_path)),
523 root_name: worktree.root_name.clone(),
524 root_char_bag: worktree
525 .root_name
526 .chars()
527 .map(|c| c.to_ascii_lowercase())
528 .collect(),
529 entries_by_path: Default::default(),
530 entries_by_id: Default::default(),
531 repository_entries: Default::default(),
532 scan_id: 1,
533 completed_scan_id: 0,
534 };
535
536 let (updates_tx, mut updates_rx) = mpsc::unbounded();
537 let background_snapshot = Arc::new(Mutex::new(snapshot.clone()));
538 let (mut snapshot_updated_tx, mut snapshot_updated_rx) = watch::channel();
539
540 cx.background()
541 .spawn({
542 let background_snapshot = background_snapshot.clone();
543 async move {
544 while let Some(update) = updates_rx.next().await {
545 if let Err(error) =
546 background_snapshot.lock().apply_remote_update(update)
547 {
548 log::error!("error applying worktree update: {}", error);
549 }
550 snapshot_updated_tx.send(()).await.ok();
551 }
552 }
553 })
554 .detach();
555
556 cx.spawn_weak(|this, mut cx| async move {
557 while (snapshot_updated_rx.recv().await).is_some() {
558 if let Some(this) = this.upgrade(&cx) {
559 this.update(&mut cx, |this, cx| {
560 let this = this.as_remote_mut().unwrap();
561 this.snapshot = this.background_snapshot.lock().clone();
562 cx.emit(Event::UpdatedEntries(Default::default()));
563 cx.notify();
564 while let Some((scan_id, _)) = this.snapshot_subscriptions.front() {
565 if this.observed_snapshot(*scan_id) {
566 let (_, tx) = this.snapshot_subscriptions.pop_front().unwrap();
567 let _ = tx.send(());
568 } else {
569 break;
570 }
571 }
572 });
573 } else {
574 break;
575 }
576 }
577 })
578 .detach();
579
580 Worktree::Remote(RemoteWorktree {
581 project_id: project_remote_id,
582 replica_id,
583 snapshot: snapshot.clone(),
584 background_snapshot,
585 updates_tx: Some(updates_tx),
586 snapshot_subscriptions: Default::default(),
587 client: client.clone(),
588 diagnostic_summaries: Default::default(),
589 visible: worktree.visible,
590 disconnected: false,
591 })
592 })
593 }
594
595 pub fn as_local(&self) -> Option<&LocalWorktree> {
596 if let Worktree::Local(worktree) = self {
597 Some(worktree)
598 } else {
599 None
600 }
601 }
602
603 pub fn as_remote(&self) -> Option<&RemoteWorktree> {
604 if let Worktree::Remote(worktree) = self {
605 Some(worktree)
606 } else {
607 None
608 }
609 }
610
611 pub fn as_local_mut(&mut self) -> Option<&mut LocalWorktree> {
612 if let Worktree::Local(worktree) = self {
613 Some(worktree)
614 } else {
615 None
616 }
617 }
618
619 pub fn as_remote_mut(&mut self) -> Option<&mut RemoteWorktree> {
620 if let Worktree::Remote(worktree) = self {
621 Some(worktree)
622 } else {
623 None
624 }
625 }
626
627 pub fn is_local(&self) -> bool {
628 matches!(self, Worktree::Local(_))
629 }
630
631 pub fn is_remote(&self) -> bool {
632 !self.is_local()
633 }
634
635 pub fn snapshot(&self) -> Snapshot {
636 match self {
637 Worktree::Local(worktree) => worktree.snapshot().snapshot,
638 Worktree::Remote(worktree) => worktree.snapshot(),
639 }
640 }
641
642 pub fn scan_id(&self) -> usize {
643 match self {
644 Worktree::Local(worktree) => worktree.snapshot.scan_id,
645 Worktree::Remote(worktree) => worktree.snapshot.scan_id,
646 }
647 }
648
649 pub fn completed_scan_id(&self) -> usize {
650 match self {
651 Worktree::Local(worktree) => worktree.snapshot.completed_scan_id,
652 Worktree::Remote(worktree) => worktree.snapshot.completed_scan_id,
653 }
654 }
655
656 pub fn is_visible(&self) -> bool {
657 match self {
658 Worktree::Local(worktree) => worktree.visible,
659 Worktree::Remote(worktree) => worktree.visible,
660 }
661 }
662
663 pub fn replica_id(&self) -> ReplicaId {
664 match self {
665 Worktree::Local(_) => 0,
666 Worktree::Remote(worktree) => worktree.replica_id,
667 }
668 }
669
670 pub fn diagnostic_summaries(
671 &self,
672 ) -> impl Iterator<Item = (Arc<Path>, LanguageServerId, DiagnosticSummary)> + '_ {
673 match self {
674 Worktree::Local(worktree) => &worktree.diagnostic_summaries,
675 Worktree::Remote(worktree) => &worktree.diagnostic_summaries,
676 }
677 .iter()
678 .flat_map(|(path, summaries)| {
679 summaries
680 .iter()
681 .map(move |(&server_id, &summary)| (path.clone(), server_id, summary))
682 })
683 }
684
685 pub fn abs_path(&self) -> Arc<Path> {
686 match self {
687 Worktree::Local(worktree) => worktree.abs_path.clone(),
688 Worktree::Remote(worktree) => worktree.abs_path.clone(),
689 }
690 }
691}
692
693impl LocalWorktree {
694 pub fn contains_abs_path(&self, path: &Path) -> bool {
695 path.starts_with(&self.abs_path)
696 }
697
698 fn absolutize(&self, path: &Path) -> PathBuf {
699 if path.file_name().is_some() {
700 self.abs_path.join(path)
701 } else {
702 self.abs_path.to_path_buf()
703 }
704 }
705
706 pub(crate) fn load_buffer(
707 &mut self,
708 id: u64,
709 path: &Path,
710 cx: &mut ModelContext<Worktree>,
711 ) -> Task<Result<ModelHandle<Buffer>>> {
712 let path = Arc::from(path);
713 cx.spawn(move |this, mut cx| async move {
714 let (file, contents, diff_base) = this
715 .update(&mut cx, |t, cx| t.as_local().unwrap().load(&path, cx))
716 .await?;
717 let text_buffer = cx
718 .background()
719 .spawn(async move { text::Buffer::new(0, id, contents) })
720 .await;
721 Ok(cx.add_model(|cx| {
722 let mut buffer = Buffer::build(text_buffer, diff_base, Some(Arc::new(file)));
723 buffer.git_diff_recalc(cx);
724 buffer
725 }))
726 })
727 }
728
729 pub fn diagnostics_for_path(
730 &self,
731 path: &Path,
732 ) -> Vec<(
733 LanguageServerId,
734 Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
735 )> {
736 self.diagnostics.get(path).cloned().unwrap_or_default()
737 }
738
739 pub fn update_diagnostics(
740 &mut self,
741 server_id: LanguageServerId,
742 worktree_path: Arc<Path>,
743 diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
744 _: &mut ModelContext<Worktree>,
745 ) -> Result<bool> {
746 let summaries_by_server_id = self
747 .diagnostic_summaries
748 .entry(worktree_path.clone())
749 .or_default();
750
751 let old_summary = summaries_by_server_id
752 .remove(&server_id)
753 .unwrap_or_default();
754
755 let new_summary = DiagnosticSummary::new(&diagnostics);
756 if new_summary.is_empty() {
757 if let Some(diagnostics_by_server_id) = self.diagnostics.get_mut(&worktree_path) {
758 if let Ok(ix) = diagnostics_by_server_id.binary_search_by_key(&server_id, |e| e.0) {
759 diagnostics_by_server_id.remove(ix);
760 }
761 if diagnostics_by_server_id.is_empty() {
762 self.diagnostics.remove(&worktree_path);
763 }
764 }
765 } else {
766 summaries_by_server_id.insert(server_id, new_summary);
767 let diagnostics_by_server_id =
768 self.diagnostics.entry(worktree_path.clone()).or_default();
769 match diagnostics_by_server_id.binary_search_by_key(&server_id, |e| e.0) {
770 Ok(ix) => {
771 diagnostics_by_server_id[ix] = (server_id, diagnostics);
772 }
773 Err(ix) => {
774 diagnostics_by_server_id.insert(ix, (server_id, diagnostics));
775 }
776 }
777 }
778
779 if !old_summary.is_empty() || !new_summary.is_empty() {
780 if let Some(share) = self.share.as_ref() {
781 self.client
782 .send(proto::UpdateDiagnosticSummary {
783 project_id: share.project_id,
784 worktree_id: self.id().to_proto(),
785 summary: Some(proto::DiagnosticSummary {
786 path: worktree_path.to_string_lossy().to_string(),
787 language_server_id: server_id.0 as u64,
788 error_count: new_summary.error_count as u32,
789 warning_count: new_summary.warning_count as u32,
790 }),
791 })
792 .log_err();
793 }
794 }
795
796 Ok(!old_summary.is_empty() || !new_summary.is_empty())
797 }
798
799 fn set_snapshot(&mut self, new_snapshot: LocalSnapshot, cx: &mut ModelContext<Worktree>) {
800 let updated_repos =
801 self.changed_repos(&self.git_repositories, &new_snapshot.git_repositories);
802 self.snapshot = new_snapshot;
803
804 if let Some(share) = self.share.as_mut() {
805 *share.snapshots_tx.borrow_mut() = self.snapshot.clone();
806 }
807
808 if !updated_repos.is_empty() {
809 cx.emit(Event::UpdatedGitRepositories(updated_repos));
810 }
811 }
812
813 fn changed_repos(
814 &self,
815 old_repos: &TreeMap<ProjectEntryId, LocalRepositoryEntry>,
816 new_repos: &TreeMap<ProjectEntryId, LocalRepositoryEntry>,
817 ) -> HashMap<Arc<Path>, LocalRepositoryEntry> {
818 let mut diff = HashMap::default();
819 let mut old_repos = old_repos.iter().peekable();
820 let mut new_repos = new_repos.iter().peekable();
821 loop {
822 match (old_repos.peek(), new_repos.peek()) {
823 (Some((old_entry_id, old_repo)), Some((new_entry_id, new_repo))) => {
824 match Ord::cmp(old_entry_id, new_entry_id) {
825 Ordering::Less => {
826 if let Some(entry) = self.entry_for_id(**old_entry_id) {
827 diff.insert(entry.path.clone(), (*old_repo).clone());
828 }
829 old_repos.next();
830 }
831 Ordering::Equal => {
832 if old_repo.scan_id != new_repo.scan_id {
833 if let Some(entry) = self.entry_for_id(**new_entry_id) {
834 diff.insert(entry.path.clone(), (*new_repo).clone());
835 }
836 }
837
838 old_repos.next();
839 new_repos.next();
840 }
841 Ordering::Greater => {
842 if let Some(entry) = self.entry_for_id(**new_entry_id) {
843 diff.insert(entry.path.clone(), (*new_repo).clone());
844 }
845 new_repos.next();
846 }
847 }
848 }
849 (Some((old_entry_id, old_repo)), None) => {
850 if let Some(entry) = self.entry_for_id(**old_entry_id) {
851 diff.insert(entry.path.clone(), (*old_repo).clone());
852 }
853 old_repos.next();
854 }
855 (None, Some((new_entry_id, new_repo))) => {
856 if let Some(entry) = self.entry_for_id(**new_entry_id) {
857 diff.insert(entry.path.clone(), (*new_repo).clone());
858 }
859 new_repos.next();
860 }
861 (None, None) => break,
862 }
863 }
864 diff
865 }
866
867 pub fn scan_complete(&self) -> impl Future<Output = ()> {
868 let mut is_scanning_rx = self.is_scanning.1.clone();
869 async move {
870 let mut is_scanning = is_scanning_rx.borrow().clone();
871 while is_scanning {
872 if let Some(value) = is_scanning_rx.recv().await {
873 is_scanning = value;
874 } else {
875 break;
876 }
877 }
878 }
879 }
880
881 pub fn snapshot(&self) -> LocalSnapshot {
882 self.snapshot.clone()
883 }
884
885 pub fn metadata_proto(&self) -> proto::WorktreeMetadata {
886 proto::WorktreeMetadata {
887 id: self.id().to_proto(),
888 root_name: self.root_name().to_string(),
889 visible: self.visible,
890 abs_path: self.abs_path().as_os_str().to_string_lossy().into(),
891 }
892 }
893
894 fn load(
895 &self,
896 path: &Path,
897 cx: &mut ModelContext<Worktree>,
898 ) -> Task<Result<(File, String, Option<String>)>> {
899 let handle = cx.handle();
900 let path = Arc::from(path);
901 let abs_path = self.absolutize(&path);
902 let fs = self.fs.clone();
903 let snapshot = self.snapshot();
904
905 let mut index_task = None;
906
907 if let Some(repo) = snapshot.repository_for_path(&path) {
908 let repo_path = repo.work_directory.relativize(self, &path).unwrap();
909 if let Some(repo) = self.git_repositories.get(&*repo.work_directory) {
910 let repo = repo.repo_ptr.to_owned();
911 index_task = Some(
912 cx.background()
913 .spawn(async move { repo.lock().load_index_text(&repo_path) }),
914 );
915 }
916 }
917
918 cx.spawn(|this, mut cx| async move {
919 let text = fs.load(&abs_path).await?;
920
921 let diff_base = if let Some(index_task) = index_task {
922 index_task.await
923 } else {
924 None
925 };
926
927 // Eagerly populate the snapshot with an updated entry for the loaded file
928 let entry = this
929 .update(&mut cx, |this, cx| {
930 this.as_local().unwrap().refresh_entry(path, None, cx)
931 })
932 .await?;
933
934 Ok((
935 File {
936 entry_id: entry.id,
937 worktree: handle,
938 path: entry.path,
939 mtime: entry.mtime,
940 is_local: true,
941 is_deleted: false,
942 },
943 text,
944 diff_base,
945 ))
946 })
947 }
948
949 pub fn save_buffer(
950 &self,
951 buffer_handle: ModelHandle<Buffer>,
952 path: Arc<Path>,
953 has_changed_file: bool,
954 cx: &mut ModelContext<Worktree>,
955 ) -> Task<Result<(clock::Global, RopeFingerprint, SystemTime)>> {
956 let handle = cx.handle();
957 let buffer = buffer_handle.read(cx);
958
959 let rpc = self.client.clone();
960 let buffer_id = buffer.remote_id();
961 let project_id = self.share.as_ref().map(|share| share.project_id);
962
963 let text = buffer.as_rope().clone();
964 let fingerprint = text.fingerprint();
965 let version = buffer.version();
966 let save = self.write_file(path, text, buffer.line_ending(), cx);
967
968 cx.as_mut().spawn(|mut cx| async move {
969 let entry = save.await?;
970
971 if has_changed_file {
972 let new_file = Arc::new(File {
973 entry_id: entry.id,
974 worktree: handle,
975 path: entry.path,
976 mtime: entry.mtime,
977 is_local: true,
978 is_deleted: false,
979 });
980
981 if let Some(project_id) = project_id {
982 rpc.send(proto::UpdateBufferFile {
983 project_id,
984 buffer_id,
985 file: Some(new_file.to_proto()),
986 })
987 .log_err();
988 }
989
990 buffer_handle.update(&mut cx, |buffer, cx| {
991 if has_changed_file {
992 buffer.file_updated(new_file, cx).detach();
993 }
994 });
995 }
996
997 if let Some(project_id) = project_id {
998 rpc.send(proto::BufferSaved {
999 project_id,
1000 buffer_id,
1001 version: serialize_version(&version),
1002 mtime: Some(entry.mtime.into()),
1003 fingerprint: serialize_fingerprint(fingerprint),
1004 })?;
1005 }
1006
1007 buffer_handle.update(&mut cx, |buffer, cx| {
1008 buffer.did_save(version.clone(), fingerprint, entry.mtime, cx);
1009 });
1010
1011 Ok((version, fingerprint, entry.mtime))
1012 })
1013 }
1014
1015 pub fn create_entry(
1016 &self,
1017 path: impl Into<Arc<Path>>,
1018 is_dir: bool,
1019 cx: &mut ModelContext<Worktree>,
1020 ) -> Task<Result<Entry>> {
1021 let path = path.into();
1022 let abs_path = self.absolutize(&path);
1023 let fs = self.fs.clone();
1024 let write = cx.background().spawn(async move {
1025 if is_dir {
1026 fs.create_dir(&abs_path).await
1027 } else {
1028 fs.save(&abs_path, &Default::default(), Default::default())
1029 .await
1030 }
1031 });
1032
1033 cx.spawn(|this, mut cx| async move {
1034 write.await?;
1035 this.update(&mut cx, |this, cx| {
1036 this.as_local_mut().unwrap().refresh_entry(path, None, cx)
1037 })
1038 .await
1039 })
1040 }
1041
1042 pub fn write_file(
1043 &self,
1044 path: impl Into<Arc<Path>>,
1045 text: Rope,
1046 line_ending: LineEnding,
1047 cx: &mut ModelContext<Worktree>,
1048 ) -> Task<Result<Entry>> {
1049 let path = path.into();
1050 let abs_path = self.absolutize(&path);
1051 let fs = self.fs.clone();
1052 let write = cx
1053 .background()
1054 .spawn(async move { fs.save(&abs_path, &text, line_ending).await });
1055
1056 cx.spawn(|this, mut cx| async move {
1057 write.await?;
1058 this.update(&mut cx, |this, cx| {
1059 this.as_local_mut().unwrap().refresh_entry(path, None, cx)
1060 })
1061 .await
1062 })
1063 }
1064
1065 pub fn delete_entry(
1066 &self,
1067 entry_id: ProjectEntryId,
1068 cx: &mut ModelContext<Worktree>,
1069 ) -> Option<Task<Result<()>>> {
1070 let entry = self.entry_for_id(entry_id)?.clone();
1071 let abs_path = self.abs_path.clone();
1072 let fs = self.fs.clone();
1073
1074 let delete = cx.background().spawn(async move {
1075 let mut abs_path = fs.canonicalize(&abs_path).await?;
1076 if entry.path.file_name().is_some() {
1077 abs_path = abs_path.join(&entry.path);
1078 }
1079 if entry.is_file() {
1080 fs.remove_file(&abs_path, Default::default()).await?;
1081 } else {
1082 fs.remove_dir(
1083 &abs_path,
1084 RemoveOptions {
1085 recursive: true,
1086 ignore_if_not_exists: false,
1087 },
1088 )
1089 .await?;
1090 }
1091 anyhow::Ok(abs_path)
1092 });
1093
1094 Some(cx.spawn(|this, mut cx| async move {
1095 let abs_path = delete.await?;
1096 let (tx, mut rx) = barrier::channel();
1097 this.update(&mut cx, |this, _| {
1098 this.as_local_mut()
1099 .unwrap()
1100 .path_changes_tx
1101 .try_send((vec![abs_path], tx))
1102 })?;
1103 rx.recv().await;
1104 Ok(())
1105 }))
1106 }
1107
1108 pub fn rename_entry(
1109 &self,
1110 entry_id: ProjectEntryId,
1111 new_path: impl Into<Arc<Path>>,
1112 cx: &mut ModelContext<Worktree>,
1113 ) -> Option<Task<Result<Entry>>> {
1114 let old_path = self.entry_for_id(entry_id)?.path.clone();
1115 let new_path = new_path.into();
1116 let abs_old_path = self.absolutize(&old_path);
1117 let abs_new_path = self.absolutize(&new_path);
1118 let fs = self.fs.clone();
1119 let rename = cx.background().spawn(async move {
1120 fs.rename(&abs_old_path, &abs_new_path, Default::default())
1121 .await
1122 });
1123
1124 Some(cx.spawn(|this, mut cx| async move {
1125 rename.await?;
1126 this.update(&mut cx, |this, cx| {
1127 this.as_local_mut()
1128 .unwrap()
1129 .refresh_entry(new_path.clone(), Some(old_path), cx)
1130 })
1131 .await
1132 }))
1133 }
1134
1135 pub fn copy_entry(
1136 &self,
1137 entry_id: ProjectEntryId,
1138 new_path: impl Into<Arc<Path>>,
1139 cx: &mut ModelContext<Worktree>,
1140 ) -> Option<Task<Result<Entry>>> {
1141 let old_path = self.entry_for_id(entry_id)?.path.clone();
1142 let new_path = new_path.into();
1143 let abs_old_path = self.absolutize(&old_path);
1144 let abs_new_path = self.absolutize(&new_path);
1145 let fs = self.fs.clone();
1146 let copy = cx.background().spawn(async move {
1147 copy_recursive(
1148 fs.as_ref(),
1149 &abs_old_path,
1150 &abs_new_path,
1151 Default::default(),
1152 )
1153 .await
1154 });
1155
1156 Some(cx.spawn(|this, mut cx| async move {
1157 copy.await?;
1158 this.update(&mut cx, |this, cx| {
1159 this.as_local_mut()
1160 .unwrap()
1161 .refresh_entry(new_path.clone(), None, cx)
1162 })
1163 .await
1164 }))
1165 }
1166
1167 fn refresh_entry(
1168 &self,
1169 path: Arc<Path>,
1170 old_path: Option<Arc<Path>>,
1171 cx: &mut ModelContext<Worktree>,
1172 ) -> Task<Result<Entry>> {
1173 let fs = self.fs.clone();
1174 let abs_root_path = self.abs_path.clone();
1175 let path_changes_tx = self.path_changes_tx.clone();
1176 cx.spawn_weak(move |this, mut cx| async move {
1177 let abs_path = fs.canonicalize(&abs_root_path).await?;
1178 let mut paths = Vec::with_capacity(2);
1179 paths.push(if path.file_name().is_some() {
1180 abs_path.join(&path)
1181 } else {
1182 abs_path.clone()
1183 });
1184 if let Some(old_path) = old_path {
1185 paths.push(if old_path.file_name().is_some() {
1186 abs_path.join(&old_path)
1187 } else {
1188 abs_path.clone()
1189 });
1190 }
1191
1192 let (tx, mut rx) = barrier::channel();
1193 path_changes_tx.try_send((paths, tx))?;
1194 rx.recv().await;
1195 this.upgrade(&cx)
1196 .ok_or_else(|| anyhow!("worktree was dropped"))?
1197 .update(&mut cx, |this, _| {
1198 this.entry_for_path(path)
1199 .cloned()
1200 .ok_or_else(|| anyhow!("failed to read path after update"))
1201 })
1202 })
1203 }
1204
1205 pub fn share(&mut self, project_id: u64, cx: &mut ModelContext<Worktree>) -> Task<Result<()>> {
1206 let (share_tx, share_rx) = oneshot::channel();
1207
1208 if let Some(share) = self.share.as_mut() {
1209 let _ = share_tx.send(());
1210 *share.resume_updates.borrow_mut() = ();
1211 } else {
1212 let (snapshots_tx, mut snapshots_rx) = watch::channel_with(self.snapshot());
1213 let (resume_updates_tx, mut resume_updates_rx) = watch::channel();
1214 let worktree_id = cx.model_id() as u64;
1215
1216 for (path, summaries) in &self.diagnostic_summaries {
1217 for (&server_id, summary) in summaries {
1218 if let Err(e) = self.client.send(proto::UpdateDiagnosticSummary {
1219 project_id,
1220 worktree_id,
1221 summary: Some(summary.to_proto(server_id, &path)),
1222 }) {
1223 return Task::ready(Err(e));
1224 }
1225 }
1226 }
1227
1228 let _maintain_remote_snapshot = cx.background().spawn({
1229 let client = self.client.clone();
1230 async move {
1231 let mut share_tx = Some(share_tx);
1232 let mut prev_snapshot = LocalSnapshot {
1233 ignores_by_parent_abs_path: Default::default(),
1234 git_repositories: Default::default(),
1235 snapshot: Snapshot {
1236 id: WorktreeId(worktree_id as usize),
1237 abs_path: Path::new("").into(),
1238 root_name: Default::default(),
1239 root_char_bag: Default::default(),
1240 entries_by_path: Default::default(),
1241 entries_by_id: Default::default(),
1242 repository_entries: Default::default(),
1243 scan_id: 0,
1244 completed_scan_id: 0,
1245 },
1246 };
1247 while let Some(snapshot) = snapshots_rx.recv().await {
1248 #[cfg(any(test, feature = "test-support"))]
1249 const MAX_CHUNK_SIZE: usize = 2;
1250 #[cfg(not(any(test, feature = "test-support")))]
1251 const MAX_CHUNK_SIZE: usize = 256;
1252
1253 let update =
1254 snapshot.build_update(&prev_snapshot, project_id, worktree_id, true);
1255 for update in proto::split_worktree_update(update, MAX_CHUNK_SIZE) {
1256 let _ = resume_updates_rx.try_recv();
1257 while let Err(error) = client.request(update.clone()).await {
1258 log::error!("failed to send worktree update: {}", error);
1259 log::info!("waiting to resume updates");
1260 if resume_updates_rx.next().await.is_none() {
1261 return Ok(());
1262 }
1263 }
1264 }
1265
1266 if let Some(share_tx) = share_tx.take() {
1267 let _ = share_tx.send(());
1268 }
1269
1270 prev_snapshot = snapshot;
1271 }
1272
1273 Ok::<_, anyhow::Error>(())
1274 }
1275 .log_err()
1276 });
1277
1278 self.share = Some(ShareState {
1279 project_id,
1280 snapshots_tx,
1281 resume_updates: resume_updates_tx,
1282 _maintain_remote_snapshot,
1283 });
1284 }
1285
1286 cx.foreground()
1287 .spawn(async move { share_rx.await.map_err(|_| anyhow!("share ended")) })
1288 }
1289
1290 pub fn unshare(&mut self) {
1291 self.share.take();
1292 }
1293
1294 pub fn is_shared(&self) -> bool {
1295 self.share.is_some()
1296 }
1297}
1298
1299impl RemoteWorktree {
1300 fn snapshot(&self) -> Snapshot {
1301 self.snapshot.clone()
1302 }
1303
1304 pub fn disconnected_from_host(&mut self) {
1305 self.updates_tx.take();
1306 self.snapshot_subscriptions.clear();
1307 self.disconnected = true;
1308 }
1309
1310 pub fn save_buffer(
1311 &self,
1312 buffer_handle: ModelHandle<Buffer>,
1313 cx: &mut ModelContext<Worktree>,
1314 ) -> Task<Result<(clock::Global, RopeFingerprint, SystemTime)>> {
1315 let buffer = buffer_handle.read(cx);
1316 let buffer_id = buffer.remote_id();
1317 let version = buffer.version();
1318 let rpc = self.client.clone();
1319 let project_id = self.project_id;
1320 cx.as_mut().spawn(|mut cx| async move {
1321 let response = rpc
1322 .request(proto::SaveBuffer {
1323 project_id,
1324 buffer_id,
1325 version: serialize_version(&version),
1326 })
1327 .await?;
1328 let version = deserialize_version(&response.version);
1329 let fingerprint = deserialize_fingerprint(&response.fingerprint)?;
1330 let mtime = response
1331 .mtime
1332 .ok_or_else(|| anyhow!("missing mtime"))?
1333 .into();
1334
1335 buffer_handle.update(&mut cx, |buffer, cx| {
1336 buffer.did_save(version.clone(), fingerprint, mtime, cx);
1337 });
1338
1339 Ok((version, fingerprint, mtime))
1340 })
1341 }
1342
1343 pub fn update_from_remote(&mut self, update: proto::UpdateWorktree) {
1344 if let Some(updates_tx) = &self.updates_tx {
1345 updates_tx
1346 .unbounded_send(update)
1347 .expect("consumer runs to completion");
1348 }
1349 }
1350
1351 fn observed_snapshot(&self, scan_id: usize) -> bool {
1352 self.completed_scan_id >= scan_id
1353 }
1354
1355 fn wait_for_snapshot(&mut self, scan_id: usize) -> impl Future<Output = Result<()>> {
1356 let (tx, rx) = oneshot::channel();
1357 if self.observed_snapshot(scan_id) {
1358 let _ = tx.send(());
1359 } else if self.disconnected {
1360 drop(tx);
1361 } else {
1362 match self
1363 .snapshot_subscriptions
1364 .binary_search_by_key(&scan_id, |probe| probe.0)
1365 {
1366 Ok(ix) | Err(ix) => self.snapshot_subscriptions.insert(ix, (scan_id, tx)),
1367 }
1368 }
1369
1370 async move {
1371 rx.await?;
1372 Ok(())
1373 }
1374 }
1375
1376 pub fn update_diagnostic_summary(
1377 &mut self,
1378 path: Arc<Path>,
1379 summary: &proto::DiagnosticSummary,
1380 ) {
1381 let server_id = LanguageServerId(summary.language_server_id as usize);
1382 let summary = DiagnosticSummary {
1383 error_count: summary.error_count as usize,
1384 warning_count: summary.warning_count as usize,
1385 };
1386
1387 if summary.is_empty() {
1388 if let Some(summaries) = self.diagnostic_summaries.get_mut(&path) {
1389 summaries.remove(&server_id);
1390 if summaries.is_empty() {
1391 self.diagnostic_summaries.remove(&path);
1392 }
1393 }
1394 } else {
1395 self.diagnostic_summaries
1396 .entry(path)
1397 .or_default()
1398 .insert(server_id, summary);
1399 }
1400 }
1401
1402 pub fn insert_entry(
1403 &mut self,
1404 entry: proto::Entry,
1405 scan_id: usize,
1406 cx: &mut ModelContext<Worktree>,
1407 ) -> Task<Result<Entry>> {
1408 let wait_for_snapshot = self.wait_for_snapshot(scan_id);
1409 cx.spawn(|this, mut cx| async move {
1410 wait_for_snapshot.await?;
1411 this.update(&mut cx, |worktree, _| {
1412 let worktree = worktree.as_remote_mut().unwrap();
1413 let mut snapshot = worktree.background_snapshot.lock();
1414 let entry = snapshot.insert_entry(entry);
1415 worktree.snapshot = snapshot.clone();
1416 entry
1417 })
1418 })
1419 }
1420
1421 pub(crate) fn delete_entry(
1422 &mut self,
1423 id: ProjectEntryId,
1424 scan_id: usize,
1425 cx: &mut ModelContext<Worktree>,
1426 ) -> Task<Result<()>> {
1427 let wait_for_snapshot = self.wait_for_snapshot(scan_id);
1428 cx.spawn(|this, mut cx| async move {
1429 wait_for_snapshot.await?;
1430 this.update(&mut cx, |worktree, _| {
1431 let worktree = worktree.as_remote_mut().unwrap();
1432 let mut snapshot = worktree.background_snapshot.lock();
1433 snapshot.delete_entry(id);
1434 worktree.snapshot = snapshot.clone();
1435 });
1436 Ok(())
1437 })
1438 }
1439}
1440
1441impl Snapshot {
1442 pub fn id(&self) -> WorktreeId {
1443 self.id
1444 }
1445
1446 pub fn abs_path(&self) -> &Arc<Path> {
1447 &self.abs_path
1448 }
1449
1450 pub fn contains_entry(&self, entry_id: ProjectEntryId) -> bool {
1451 self.entries_by_id.get(&entry_id, &()).is_some()
1452 }
1453
1454 pub(crate) fn insert_entry(&mut self, entry: proto::Entry) -> Result<Entry> {
1455 let entry = Entry::try_from((&self.root_char_bag, entry))?;
1456 let old_entry = self.entries_by_id.insert_or_replace(
1457 PathEntry {
1458 id: entry.id,
1459 path: entry.path.clone(),
1460 is_ignored: entry.is_ignored,
1461 scan_id: 0,
1462 },
1463 &(),
1464 );
1465 if let Some(old_entry) = old_entry {
1466 self.entries_by_path.remove(&PathKey(old_entry.path), &());
1467 }
1468 self.entries_by_path.insert_or_replace(entry.clone(), &());
1469 Ok(entry)
1470 }
1471
1472 fn delete_entry(&mut self, entry_id: ProjectEntryId) -> Option<Arc<Path>> {
1473 let removed_entry = self.entries_by_id.remove(&entry_id, &())?;
1474 self.entries_by_path = {
1475 let mut cursor = self.entries_by_path.cursor();
1476 let mut new_entries_by_path =
1477 cursor.slice(&TraversalTarget::Path(&removed_entry.path), Bias::Left, &());
1478 while let Some(entry) = cursor.item() {
1479 if entry.path.starts_with(&removed_entry.path) {
1480 self.entries_by_id.remove(&entry.id, &());
1481 cursor.next(&());
1482 } else {
1483 break;
1484 }
1485 }
1486 new_entries_by_path.push_tree(cursor.suffix(&()), &());
1487 new_entries_by_path
1488 };
1489
1490 Some(removed_entry.path)
1491 }
1492
1493 pub(crate) fn apply_remote_update(&mut self, mut update: proto::UpdateWorktree) -> Result<()> {
1494 let mut entries_by_path_edits = Vec::new();
1495 let mut entries_by_id_edits = Vec::new();
1496 for entry_id in update.removed_entries {
1497 if let Some(entry) = self.entry_for_id(ProjectEntryId::from_proto(entry_id)) {
1498 entries_by_path_edits.push(Edit::Remove(PathKey(entry.path.clone())));
1499 entries_by_id_edits.push(Edit::Remove(entry.id));
1500 }
1501 }
1502
1503 for entry in update.updated_entries {
1504 let entry = Entry::try_from((&self.root_char_bag, entry))?;
1505 if let Some(PathEntry { path, .. }) = self.entries_by_id.get(&entry.id, &()) {
1506 entries_by_path_edits.push(Edit::Remove(PathKey(path.clone())));
1507 }
1508 entries_by_id_edits.push(Edit::Insert(PathEntry {
1509 id: entry.id,
1510 path: entry.path.clone(),
1511 is_ignored: entry.is_ignored,
1512 scan_id: 0,
1513 }));
1514 entries_by_path_edits.push(Edit::Insert(entry));
1515 }
1516
1517 self.entries_by_path.edit(entries_by_path_edits, &());
1518 self.entries_by_id.edit(entries_by_id_edits, &());
1519
1520 update.removed_repositories.sort_unstable();
1521 self.repository_entries.retain(|_, entry| {
1522 if let Ok(_) = update
1523 .removed_repositories
1524 .binary_search(&entry.work_directory.to_proto())
1525 {
1526 false
1527 } else {
1528 true
1529 }
1530 });
1531
1532 for repository in update.updated_repositories {
1533 let work_directory_entry: WorkDirectoryEntry =
1534 ProjectEntryId::from_proto(repository.work_directory_id).into();
1535
1536 if let Some(entry) = self.entry_for_id(*work_directory_entry) {
1537 let mut statuses = TreeMap::default();
1538 for status_entry in repository.updated_statuses {
1539 let Some(git_file_status) = read_git_status(status_entry.status) else {
1540 continue;
1541 };
1542
1543 let repo_path = RepoPath::new(status_entry.repo_path.into());
1544 statuses.insert(repo_path, git_file_status);
1545 }
1546
1547 let work_directory = RepositoryWorkDirectory(entry.path.clone());
1548 if self.repository_entries.get(&work_directory).is_some() {
1549 self.repository_entries.update(&work_directory, |repo| {
1550 repo.branch = repository.branch.map(Into::into);
1551 repo.statuses.insert_tree(statuses);
1552
1553 for repo_path in repository.removed_repo_paths {
1554 let repo_path = RepoPath::new(repo_path.into());
1555 repo.statuses.remove(&repo_path);
1556 }
1557 });
1558 } else {
1559 self.repository_entries.insert(
1560 work_directory,
1561 RepositoryEntry {
1562 work_directory: work_directory_entry,
1563 branch: repository.branch.map(Into::into),
1564 statuses,
1565 },
1566 )
1567 }
1568 } else {
1569 log::error!("no work directory entry for repository {:?}", repository)
1570 }
1571 }
1572
1573 self.scan_id = update.scan_id as usize;
1574 if update.is_last_update {
1575 self.completed_scan_id = update.scan_id as usize;
1576 }
1577
1578 Ok(())
1579 }
1580
1581 pub fn file_count(&self) -> usize {
1582 self.entries_by_path.summary().file_count
1583 }
1584
1585 pub fn visible_file_count(&self) -> usize {
1586 self.entries_by_path.summary().visible_file_count
1587 }
1588
1589 fn traverse_from_offset(
1590 &self,
1591 include_dirs: bool,
1592 include_ignored: bool,
1593 start_offset: usize,
1594 ) -> Traversal {
1595 let mut cursor = self.entries_by_path.cursor();
1596 cursor.seek(
1597 &TraversalTarget::Count {
1598 count: start_offset,
1599 include_dirs,
1600 include_ignored,
1601 },
1602 Bias::Right,
1603 &(),
1604 );
1605 Traversal {
1606 cursor,
1607 include_dirs,
1608 include_ignored,
1609 }
1610 }
1611
1612 fn traverse_from_path(
1613 &self,
1614 include_dirs: bool,
1615 include_ignored: bool,
1616 path: &Path,
1617 ) -> Traversal {
1618 let mut cursor = self.entries_by_path.cursor();
1619 cursor.seek(&TraversalTarget::Path(path), Bias::Left, &());
1620 Traversal {
1621 cursor,
1622 include_dirs,
1623 include_ignored,
1624 }
1625 }
1626
1627 pub fn files(&self, include_ignored: bool, start: usize) -> Traversal {
1628 self.traverse_from_offset(false, include_ignored, start)
1629 }
1630
1631 pub fn entries(&self, include_ignored: bool) -> Traversal {
1632 self.traverse_from_offset(true, include_ignored, 0)
1633 }
1634
1635 pub fn repositories(&self) -> impl Iterator<Item = (&Arc<Path>, &RepositoryEntry)> {
1636 self.repository_entries
1637 .iter()
1638 .map(|(path, entry)| (&path.0, entry))
1639 }
1640
1641 /// Get the repository whose work directory contains the given path.
1642 pub fn repository_for_path(&self, path: &Path) -> Option<RepositoryEntry> {
1643 let mut max_len = 0;
1644 let mut current_candidate = None;
1645 for (work_directory, repo) in (&self.repository_entries).iter() {
1646 if path.starts_with(&work_directory.0) {
1647 if work_directory.0.as_os_str().len() >= max_len {
1648 current_candidate = Some(repo);
1649 max_len = work_directory.0.as_os_str().len();
1650 } else {
1651 break;
1652 }
1653 }
1654 }
1655
1656 current_candidate.map(|entry| entry.to_owned())
1657 }
1658
1659 /// Given an ordered iterator of entries, returns an iterator of those entries,
1660 /// along with their containing git repository.
1661 pub fn entries_with_repositories<'a>(
1662 &'a self,
1663 entries: impl 'a + Iterator<Item = &'a Entry>,
1664 ) -> impl 'a + Iterator<Item = (&'a Entry, Option<&'a RepositoryEntry>)> {
1665 let mut containing_repos = Vec::<(&Arc<Path>, &RepositoryEntry)>::new();
1666 let mut repositories = self.repositories().peekable();
1667 entries.map(move |entry| {
1668 while let Some((repo_path, _)) = containing_repos.last() {
1669 if !entry.path.starts_with(repo_path) {
1670 containing_repos.pop();
1671 } else {
1672 break;
1673 }
1674 }
1675 while let Some((repo_path, _)) = repositories.peek() {
1676 if entry.path.starts_with(repo_path) {
1677 containing_repos.push(repositories.next().unwrap());
1678 } else {
1679 break;
1680 }
1681 }
1682 let repo = containing_repos.last().map(|(_, repo)| *repo);
1683 (entry, repo)
1684 })
1685 }
1686
1687 pub fn paths(&self) -> impl Iterator<Item = &Arc<Path>> {
1688 let empty_path = Path::new("");
1689 self.entries_by_path
1690 .cursor::<()>()
1691 .filter(move |entry| entry.path.as_ref() != empty_path)
1692 .map(|entry| &entry.path)
1693 }
1694
1695 fn child_entries<'a>(&'a self, parent_path: &'a Path) -> ChildEntriesIter<'a> {
1696 let mut cursor = self.entries_by_path.cursor();
1697 cursor.seek(&TraversalTarget::Path(parent_path), Bias::Right, &());
1698 let traversal = Traversal {
1699 cursor,
1700 include_dirs: true,
1701 include_ignored: true,
1702 };
1703 ChildEntriesIter {
1704 traversal,
1705 parent_path,
1706 }
1707 }
1708
1709 fn descendent_entries<'a>(
1710 &'a self,
1711 include_dirs: bool,
1712 include_ignored: bool,
1713 parent_path: &'a Path,
1714 ) -> DescendentEntriesIter<'a> {
1715 let mut cursor = self.entries_by_path.cursor();
1716 cursor.seek(&TraversalTarget::Path(parent_path), Bias::Left, &());
1717 let mut traversal = Traversal {
1718 cursor,
1719 include_dirs,
1720 include_ignored,
1721 };
1722
1723 if traversal.end_offset() == traversal.start_offset() {
1724 traversal.advance();
1725 }
1726
1727 DescendentEntriesIter {
1728 traversal,
1729 parent_path,
1730 }
1731 }
1732
1733 pub fn root_entry(&self) -> Option<&Entry> {
1734 self.entry_for_path("")
1735 }
1736
1737 pub fn root_name(&self) -> &str {
1738 &self.root_name
1739 }
1740
1741 pub fn root_git_entry(&self) -> Option<RepositoryEntry> {
1742 self.repository_entries
1743 .get(&RepositoryWorkDirectory(Path::new("").into()))
1744 .map(|entry| entry.to_owned())
1745 }
1746
1747 pub fn git_entries(&self) -> impl Iterator<Item = &RepositoryEntry> {
1748 self.repository_entries.values()
1749 }
1750
1751 pub fn scan_id(&self) -> usize {
1752 self.scan_id
1753 }
1754
1755 pub fn entry_for_path(&self, path: impl AsRef<Path>) -> Option<&Entry> {
1756 let path = path.as_ref();
1757 self.traverse_from_path(true, true, path)
1758 .entry()
1759 .and_then(|entry| {
1760 if entry.path.as_ref() == path {
1761 Some(entry)
1762 } else {
1763 None
1764 }
1765 })
1766 }
1767
1768 pub fn entry_for_id(&self, id: ProjectEntryId) -> Option<&Entry> {
1769 let entry = self.entries_by_id.get(&id, &())?;
1770 self.entry_for_path(&entry.path)
1771 }
1772
1773 pub fn inode_for_path(&self, path: impl AsRef<Path>) -> Option<u64> {
1774 self.entry_for_path(path.as_ref()).map(|e| e.inode)
1775 }
1776}
1777
1778impl LocalSnapshot {
1779 pub(crate) fn get_local_repo(&self, repo: &RepositoryEntry) -> Option<&LocalRepositoryEntry> {
1780 self.git_repositories.get(&repo.work_directory.0)
1781 }
1782
1783 pub(crate) fn repo_for_metadata(
1784 &self,
1785 path: &Path,
1786 ) -> Option<(&ProjectEntryId, &LocalRepositoryEntry)> {
1787 self.git_repositories
1788 .iter()
1789 .find(|(_, repo)| repo.in_dot_git(path))
1790 }
1791
1792 #[cfg(test)]
1793 pub(crate) fn build_initial_update(&self, project_id: u64) -> proto::UpdateWorktree {
1794 let root_name = self.root_name.clone();
1795 proto::UpdateWorktree {
1796 project_id,
1797 worktree_id: self.id().to_proto(),
1798 abs_path: self.abs_path().to_string_lossy().into(),
1799 root_name,
1800 updated_entries: self.entries_by_path.iter().map(Into::into).collect(),
1801 removed_entries: Default::default(),
1802 scan_id: self.scan_id as u64,
1803 is_last_update: true,
1804 updated_repositories: self.repository_entries.values().map(Into::into).collect(),
1805 removed_repositories: Default::default(),
1806 }
1807 }
1808
1809 pub(crate) fn build_update(
1810 &self,
1811 other: &Self,
1812 project_id: u64,
1813 worktree_id: u64,
1814 include_ignored: bool,
1815 ) -> proto::UpdateWorktree {
1816 let mut updated_entries = Vec::new();
1817 let mut removed_entries = Vec::new();
1818 let mut self_entries = self
1819 .entries_by_id
1820 .cursor::<()>()
1821 .filter(|e| include_ignored || !e.is_ignored)
1822 .peekable();
1823 let mut other_entries = other
1824 .entries_by_id
1825 .cursor::<()>()
1826 .filter(|e| include_ignored || !e.is_ignored)
1827 .peekable();
1828 loop {
1829 match (self_entries.peek(), other_entries.peek()) {
1830 (Some(self_entry), Some(other_entry)) => {
1831 match Ord::cmp(&self_entry.id, &other_entry.id) {
1832 Ordering::Less => {
1833 let entry = self.entry_for_id(self_entry.id).unwrap().into();
1834 updated_entries.push(entry);
1835 self_entries.next();
1836 }
1837 Ordering::Equal => {
1838 if self_entry.scan_id != other_entry.scan_id {
1839 let entry = self.entry_for_id(self_entry.id).unwrap().into();
1840 updated_entries.push(entry);
1841 }
1842
1843 self_entries.next();
1844 other_entries.next();
1845 }
1846 Ordering::Greater => {
1847 removed_entries.push(other_entry.id.to_proto());
1848 other_entries.next();
1849 }
1850 }
1851 }
1852 (Some(self_entry), None) => {
1853 let entry = self.entry_for_id(self_entry.id).unwrap().into();
1854 updated_entries.push(entry);
1855 self_entries.next();
1856 }
1857 (None, Some(other_entry)) => {
1858 removed_entries.push(other_entry.id.to_proto());
1859 other_entries.next();
1860 }
1861 (None, None) => break,
1862 }
1863 }
1864
1865 let mut updated_repositories: Vec<proto::RepositoryEntry> = Vec::new();
1866 let mut removed_repositories = Vec::new();
1867 let mut self_repos = self.snapshot.repository_entries.iter().peekable();
1868 let mut other_repos = other.snapshot.repository_entries.iter().peekable();
1869 loop {
1870 match (self_repos.peek(), other_repos.peek()) {
1871 (Some((self_work_dir, self_repo)), Some((other_work_dir, other_repo))) => {
1872 match Ord::cmp(self_work_dir, other_work_dir) {
1873 Ordering::Less => {
1874 updated_repositories.push((*self_repo).into());
1875 self_repos.next();
1876 }
1877 Ordering::Equal => {
1878 if self_repo != other_repo {
1879 updated_repositories.push(self_repo.build_update(other_repo));
1880 }
1881
1882 self_repos.next();
1883 other_repos.next();
1884 }
1885 Ordering::Greater => {
1886 removed_repositories.push(other_repo.work_directory.to_proto());
1887 other_repos.next();
1888 }
1889 }
1890 }
1891 (Some((_, self_repo)), None) => {
1892 updated_repositories.push((*self_repo).into());
1893 self_repos.next();
1894 }
1895 (None, Some((_, other_repo))) => {
1896 removed_repositories.push(other_repo.work_directory.to_proto());
1897 other_repos.next();
1898 }
1899 (None, None) => break,
1900 }
1901 }
1902
1903 proto::UpdateWorktree {
1904 project_id,
1905 worktree_id,
1906 abs_path: self.abs_path().to_string_lossy().into(),
1907 root_name: self.root_name().to_string(),
1908 updated_entries,
1909 removed_entries,
1910 scan_id: self.scan_id as u64,
1911 is_last_update: self.completed_scan_id == self.scan_id,
1912 updated_repositories,
1913 removed_repositories,
1914 }
1915 }
1916
1917 fn insert_entry(&mut self, mut entry: Entry, fs: &dyn Fs) -> Entry {
1918 if entry.is_file() && entry.path.file_name() == Some(&GITIGNORE) {
1919 let abs_path = self.abs_path.join(&entry.path);
1920 match smol::block_on(build_gitignore(&abs_path, fs)) {
1921 Ok(ignore) => {
1922 self.ignores_by_parent_abs_path
1923 .insert(abs_path.parent().unwrap().into(), (Arc::new(ignore), true));
1924 }
1925 Err(error) => {
1926 log::error!(
1927 "error loading .gitignore file {:?} - {:?}",
1928 &entry.path,
1929 error
1930 );
1931 }
1932 }
1933 }
1934
1935 if entry.kind == EntryKind::PendingDir {
1936 if let Some(existing_entry) =
1937 self.entries_by_path.get(&PathKey(entry.path.clone()), &())
1938 {
1939 entry.kind = existing_entry.kind;
1940 }
1941 }
1942
1943 let scan_id = self.scan_id;
1944 let removed = self.entries_by_path.insert_or_replace(entry.clone(), &());
1945 if let Some(removed) = removed {
1946 if removed.id != entry.id {
1947 self.entries_by_id.remove(&removed.id, &());
1948 }
1949 }
1950 self.entries_by_id.insert_or_replace(
1951 PathEntry {
1952 id: entry.id,
1953 path: entry.path.clone(),
1954 is_ignored: entry.is_ignored,
1955 scan_id,
1956 },
1957 &(),
1958 );
1959
1960 entry
1961 }
1962
1963 fn build_repo(&mut self, parent_path: Arc<Path>, fs: &dyn Fs) -> Option<()> {
1964 let abs_path = self.abs_path.join(&parent_path);
1965 let work_dir: Arc<Path> = parent_path.parent().unwrap().into();
1966
1967 // Guard against repositories inside the repository metadata
1968 if work_dir
1969 .components()
1970 .find(|component| component.as_os_str() == *DOT_GIT)
1971 .is_some()
1972 {
1973 return None;
1974 };
1975
1976 let work_dir_id = self
1977 .entry_for_path(work_dir.clone())
1978 .map(|entry| entry.id)?;
1979
1980 if self.git_repositories.get(&work_dir_id).is_none() {
1981 let repo = fs.open_repo(abs_path.as_path())?;
1982 let work_directory = RepositoryWorkDirectory(work_dir.clone());
1983 let scan_id = self.scan_id;
1984
1985 let repo_lock = repo.lock();
1986
1987 self.repository_entries.insert(
1988 work_directory,
1989 RepositoryEntry {
1990 work_directory: work_dir_id.into(),
1991 branch: repo_lock.branch_name().map(Into::into),
1992 statuses: repo_lock.statuses().unwrap_or_default(),
1993 },
1994 );
1995 drop(repo_lock);
1996
1997 self.git_repositories.insert(
1998 work_dir_id,
1999 LocalRepositoryEntry {
2000 scan_id,
2001 full_scan_id: scan_id,
2002 repo_ptr: repo,
2003 git_dir_path: parent_path.clone(),
2004 },
2005 )
2006 }
2007
2008 Some(())
2009 }
2010
2011 fn ancestor_inodes_for_path(&self, path: &Path) -> TreeSet<u64> {
2012 let mut inodes = TreeSet::default();
2013 for ancestor in path.ancestors().skip(1) {
2014 if let Some(entry) = self.entry_for_path(ancestor) {
2015 inodes.insert(entry.inode);
2016 }
2017 }
2018 inodes
2019 }
2020
2021 fn ignore_stack_for_abs_path(&self, abs_path: &Path, is_dir: bool) -> Arc<IgnoreStack> {
2022 let mut new_ignores = Vec::new();
2023 for ancestor in abs_path.ancestors().skip(1) {
2024 if let Some((ignore, _)) = self.ignores_by_parent_abs_path.get(ancestor) {
2025 new_ignores.push((ancestor, Some(ignore.clone())));
2026 } else {
2027 new_ignores.push((ancestor, None));
2028 }
2029 }
2030
2031 let mut ignore_stack = IgnoreStack::none();
2032 for (parent_abs_path, ignore) in new_ignores.into_iter().rev() {
2033 if ignore_stack.is_abs_path_ignored(parent_abs_path, true) {
2034 ignore_stack = IgnoreStack::all();
2035 break;
2036 } else if let Some(ignore) = ignore {
2037 ignore_stack = ignore_stack.append(parent_abs_path.into(), ignore);
2038 }
2039 }
2040
2041 if ignore_stack.is_abs_path_ignored(abs_path, is_dir) {
2042 ignore_stack = IgnoreStack::all();
2043 }
2044
2045 ignore_stack
2046 }
2047}
2048
2049impl LocalMutableSnapshot {
2050 fn reuse_entry_id(&mut self, entry: &mut Entry) {
2051 if let Some(removed_entry_id) = self.removed_entry_ids.remove(&entry.inode) {
2052 entry.id = removed_entry_id;
2053 } else if let Some(existing_entry) = self.entry_for_path(&entry.path) {
2054 entry.id = existing_entry.id;
2055 }
2056 }
2057
2058 fn insert_entry(&mut self, mut entry: Entry, fs: &dyn Fs) -> Entry {
2059 self.reuse_entry_id(&mut entry);
2060 self.snapshot.insert_entry(entry, fs)
2061 }
2062
2063 fn populate_dir(
2064 &mut self,
2065 parent_path: Arc<Path>,
2066 entries: impl IntoIterator<Item = Entry>,
2067 ignore: Option<Arc<Gitignore>>,
2068 fs: &dyn Fs,
2069 ) {
2070 let mut parent_entry = if let Some(parent_entry) =
2071 self.entries_by_path.get(&PathKey(parent_path.clone()), &())
2072 {
2073 parent_entry.clone()
2074 } else {
2075 log::warn!(
2076 "populating a directory {:?} that has been removed",
2077 parent_path
2078 );
2079 return;
2080 };
2081
2082 match parent_entry.kind {
2083 EntryKind::PendingDir => {
2084 parent_entry.kind = EntryKind::Dir;
2085 }
2086 EntryKind::Dir => {}
2087 _ => return,
2088 }
2089
2090 if let Some(ignore) = ignore {
2091 let abs_parent_path = self.abs_path.join(&parent_path).into();
2092 self.ignores_by_parent_abs_path
2093 .insert(abs_parent_path, (ignore, false));
2094 }
2095
2096 if parent_path.file_name() == Some(&DOT_GIT) {
2097 self.build_repo(parent_path, fs);
2098 }
2099
2100 let mut entries_by_path_edits = vec![Edit::Insert(parent_entry)];
2101 let mut entries_by_id_edits = Vec::new();
2102
2103 for mut entry in entries {
2104 self.reuse_entry_id(&mut entry);
2105 entries_by_id_edits.push(Edit::Insert(PathEntry {
2106 id: entry.id,
2107 path: entry.path.clone(),
2108 is_ignored: entry.is_ignored,
2109 scan_id: self.scan_id,
2110 }));
2111 entries_by_path_edits.push(Edit::Insert(entry));
2112 }
2113
2114 self.entries_by_path.edit(entries_by_path_edits, &());
2115 self.entries_by_id.edit(entries_by_id_edits, &());
2116 }
2117
2118 fn remove_path(&mut self, path: &Path) {
2119 let mut new_entries;
2120 let removed_entries;
2121 {
2122 let mut cursor = self.entries_by_path.cursor::<TraversalProgress>();
2123 new_entries = cursor.slice(&TraversalTarget::Path(path), Bias::Left, &());
2124 removed_entries = cursor.slice(&TraversalTarget::PathSuccessor(path), Bias::Left, &());
2125 new_entries.push_tree(cursor.suffix(&()), &());
2126 }
2127 self.entries_by_path = new_entries;
2128
2129 let mut entries_by_id_edits = Vec::new();
2130 for entry in removed_entries.cursor::<()>() {
2131 let removed_entry_id = self
2132 .removed_entry_ids
2133 .entry(entry.inode)
2134 .or_insert(entry.id);
2135 *removed_entry_id = cmp::max(*removed_entry_id, entry.id);
2136 entries_by_id_edits.push(Edit::Remove(entry.id));
2137 }
2138 self.entries_by_id.edit(entries_by_id_edits, &());
2139
2140 if path.file_name() == Some(&GITIGNORE) {
2141 let abs_parent_path = self.abs_path.join(path.parent().unwrap());
2142 if let Some((_, needs_update)) = self
2143 .ignores_by_parent_abs_path
2144 .get_mut(abs_parent_path.as_path())
2145 {
2146 *needs_update = true;
2147 }
2148 }
2149 }
2150}
2151
2152async fn build_gitignore(abs_path: &Path, fs: &dyn Fs) -> Result<Gitignore> {
2153 let contents = fs.load(abs_path).await?;
2154 let parent = abs_path.parent().unwrap_or_else(|| Path::new("/"));
2155 let mut builder = GitignoreBuilder::new(parent);
2156 for line in contents.lines() {
2157 builder.add_line(Some(abs_path.into()), line)?;
2158 }
2159 Ok(builder.build()?)
2160}
2161
2162impl WorktreeId {
2163 pub fn from_usize(handle_id: usize) -> Self {
2164 Self(handle_id)
2165 }
2166
2167 pub(crate) fn from_proto(id: u64) -> Self {
2168 Self(id as usize)
2169 }
2170
2171 pub fn to_proto(&self) -> u64 {
2172 self.0 as u64
2173 }
2174
2175 pub fn to_usize(&self) -> usize {
2176 self.0
2177 }
2178}
2179
2180impl fmt::Display for WorktreeId {
2181 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2182 self.0.fmt(f)
2183 }
2184}
2185
2186impl Deref for Worktree {
2187 type Target = Snapshot;
2188
2189 fn deref(&self) -> &Self::Target {
2190 match self {
2191 Worktree::Local(worktree) => &worktree.snapshot,
2192 Worktree::Remote(worktree) => &worktree.snapshot,
2193 }
2194 }
2195}
2196
2197impl Deref for LocalWorktree {
2198 type Target = LocalSnapshot;
2199
2200 fn deref(&self) -> &Self::Target {
2201 &self.snapshot
2202 }
2203}
2204
2205impl Deref for RemoteWorktree {
2206 type Target = Snapshot;
2207
2208 fn deref(&self) -> &Self::Target {
2209 &self.snapshot
2210 }
2211}
2212
2213impl fmt::Debug for LocalWorktree {
2214 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2215 self.snapshot.fmt(f)
2216 }
2217}
2218
2219impl fmt::Debug for Snapshot {
2220 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2221 struct EntriesById<'a>(&'a SumTree<PathEntry>);
2222 struct EntriesByPath<'a>(&'a SumTree<Entry>);
2223
2224 impl<'a> fmt::Debug for EntriesByPath<'a> {
2225 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2226 f.debug_map()
2227 .entries(self.0.iter().map(|entry| (&entry.path, entry.id)))
2228 .finish()
2229 }
2230 }
2231
2232 impl<'a> fmt::Debug for EntriesById<'a> {
2233 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2234 f.debug_list().entries(self.0.iter()).finish()
2235 }
2236 }
2237
2238 f.debug_struct("Snapshot")
2239 .field("id", &self.id)
2240 .field("root_name", &self.root_name)
2241 .field("entries_by_path", &EntriesByPath(&self.entries_by_path))
2242 .field("entries_by_id", &EntriesById(&self.entries_by_id))
2243 .finish()
2244 }
2245}
2246
2247#[derive(Clone, PartialEq)]
2248pub struct File {
2249 pub worktree: ModelHandle<Worktree>,
2250 pub path: Arc<Path>,
2251 pub mtime: SystemTime,
2252 pub(crate) entry_id: ProjectEntryId,
2253 pub(crate) is_local: bool,
2254 pub(crate) is_deleted: bool,
2255}
2256
2257impl language::File for File {
2258 fn as_local(&self) -> Option<&dyn language::LocalFile> {
2259 if self.is_local {
2260 Some(self)
2261 } else {
2262 None
2263 }
2264 }
2265
2266 fn mtime(&self) -> SystemTime {
2267 self.mtime
2268 }
2269
2270 fn path(&self) -> &Arc<Path> {
2271 &self.path
2272 }
2273
2274 fn full_path(&self, cx: &AppContext) -> PathBuf {
2275 let mut full_path = PathBuf::new();
2276 let worktree = self.worktree.read(cx);
2277
2278 if worktree.is_visible() {
2279 full_path.push(worktree.root_name());
2280 } else {
2281 let path = worktree.abs_path();
2282
2283 if worktree.is_local() && path.starts_with(HOME.as_path()) {
2284 full_path.push("~");
2285 full_path.push(path.strip_prefix(HOME.as_path()).unwrap());
2286 } else {
2287 full_path.push(path)
2288 }
2289 }
2290
2291 if self.path.components().next().is_some() {
2292 full_path.push(&self.path);
2293 }
2294
2295 full_path
2296 }
2297
2298 /// Returns the last component of this handle's absolute path. If this handle refers to the root
2299 /// of its worktree, then this method will return the name of the worktree itself.
2300 fn file_name<'a>(&'a self, cx: &'a AppContext) -> &'a OsStr {
2301 self.path
2302 .file_name()
2303 .unwrap_or_else(|| OsStr::new(&self.worktree.read(cx).root_name))
2304 }
2305
2306 fn is_deleted(&self) -> bool {
2307 self.is_deleted
2308 }
2309
2310 fn as_any(&self) -> &dyn Any {
2311 self
2312 }
2313
2314 fn to_proto(&self) -> rpc::proto::File {
2315 rpc::proto::File {
2316 worktree_id: self.worktree.id() as u64,
2317 entry_id: self.entry_id.to_proto(),
2318 path: self.path.to_string_lossy().into(),
2319 mtime: Some(self.mtime.into()),
2320 is_deleted: self.is_deleted,
2321 }
2322 }
2323}
2324
2325impl language::LocalFile for File {
2326 fn abs_path(&self, cx: &AppContext) -> PathBuf {
2327 self.worktree
2328 .read(cx)
2329 .as_local()
2330 .unwrap()
2331 .abs_path
2332 .join(&self.path)
2333 }
2334
2335 fn load(&self, cx: &AppContext) -> Task<Result<String>> {
2336 let worktree = self.worktree.read(cx).as_local().unwrap();
2337 let abs_path = worktree.absolutize(&self.path);
2338 let fs = worktree.fs.clone();
2339 cx.background()
2340 .spawn(async move { fs.load(&abs_path).await })
2341 }
2342
2343 fn buffer_reloaded(
2344 &self,
2345 buffer_id: u64,
2346 version: &clock::Global,
2347 fingerprint: RopeFingerprint,
2348 line_ending: LineEnding,
2349 mtime: SystemTime,
2350 cx: &mut AppContext,
2351 ) {
2352 let worktree = self.worktree.read(cx).as_local().unwrap();
2353 if let Some(project_id) = worktree.share.as_ref().map(|share| share.project_id) {
2354 worktree
2355 .client
2356 .send(proto::BufferReloaded {
2357 project_id,
2358 buffer_id,
2359 version: serialize_version(version),
2360 mtime: Some(mtime.into()),
2361 fingerprint: serialize_fingerprint(fingerprint),
2362 line_ending: serialize_line_ending(line_ending) as i32,
2363 })
2364 .log_err();
2365 }
2366 }
2367}
2368
2369impl File {
2370 pub fn from_proto(
2371 proto: rpc::proto::File,
2372 worktree: ModelHandle<Worktree>,
2373 cx: &AppContext,
2374 ) -> Result<Self> {
2375 let worktree_id = worktree
2376 .read(cx)
2377 .as_remote()
2378 .ok_or_else(|| anyhow!("not remote"))?
2379 .id();
2380
2381 if worktree_id.to_proto() != proto.worktree_id {
2382 return Err(anyhow!("worktree id does not match file"));
2383 }
2384
2385 Ok(Self {
2386 worktree,
2387 path: Path::new(&proto.path).into(),
2388 mtime: proto.mtime.ok_or_else(|| anyhow!("no timestamp"))?.into(),
2389 entry_id: ProjectEntryId::from_proto(proto.entry_id),
2390 is_local: false,
2391 is_deleted: proto.is_deleted,
2392 })
2393 }
2394
2395 pub fn from_dyn(file: Option<&Arc<dyn language::File>>) -> Option<&Self> {
2396 file.and_then(|f| f.as_any().downcast_ref())
2397 }
2398
2399 pub fn worktree_id(&self, cx: &AppContext) -> WorktreeId {
2400 self.worktree.read(cx).id()
2401 }
2402
2403 pub fn project_entry_id(&self, _: &AppContext) -> Option<ProjectEntryId> {
2404 if self.is_deleted {
2405 None
2406 } else {
2407 Some(self.entry_id)
2408 }
2409 }
2410}
2411
2412#[derive(Clone, Debug, PartialEq, Eq)]
2413pub struct Entry {
2414 pub id: ProjectEntryId,
2415 pub kind: EntryKind,
2416 pub path: Arc<Path>,
2417 pub inode: u64,
2418 pub mtime: SystemTime,
2419 pub is_symlink: bool,
2420 pub is_ignored: bool,
2421}
2422
2423#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2424pub enum EntryKind {
2425 PendingDir,
2426 Dir,
2427 File(CharBag),
2428}
2429
2430#[derive(Clone, Copy, Debug)]
2431pub enum PathChange {
2432 Added,
2433 Removed,
2434 Updated,
2435 AddedOrUpdated,
2436}
2437
2438impl Entry {
2439 fn new(
2440 path: Arc<Path>,
2441 metadata: &fs::Metadata,
2442 next_entry_id: &AtomicUsize,
2443 root_char_bag: CharBag,
2444 ) -> Self {
2445 Self {
2446 id: ProjectEntryId::new(next_entry_id),
2447 kind: if metadata.is_dir {
2448 EntryKind::PendingDir
2449 } else {
2450 EntryKind::File(char_bag_for_path(root_char_bag, &path))
2451 },
2452 path,
2453 inode: metadata.inode,
2454 mtime: metadata.mtime,
2455 is_symlink: metadata.is_symlink,
2456 is_ignored: false,
2457 }
2458 }
2459
2460 pub fn is_dir(&self) -> bool {
2461 matches!(self.kind, EntryKind::Dir | EntryKind::PendingDir)
2462 }
2463
2464 pub fn is_file(&self) -> bool {
2465 matches!(self.kind, EntryKind::File(_))
2466 }
2467}
2468
2469impl sum_tree::Item for Entry {
2470 type Summary = EntrySummary;
2471
2472 fn summary(&self) -> Self::Summary {
2473 let visible_count = if self.is_ignored { 0 } else { 1 };
2474 let file_count;
2475 let visible_file_count;
2476 if self.is_file() {
2477 file_count = 1;
2478 visible_file_count = visible_count;
2479 } else {
2480 file_count = 0;
2481 visible_file_count = 0;
2482 }
2483
2484 EntrySummary {
2485 max_path: self.path.clone(),
2486 count: 1,
2487 visible_count,
2488 file_count,
2489 visible_file_count,
2490 }
2491 }
2492}
2493
2494impl sum_tree::KeyedItem for Entry {
2495 type Key = PathKey;
2496
2497 fn key(&self) -> Self::Key {
2498 PathKey(self.path.clone())
2499 }
2500}
2501
2502#[derive(Clone, Debug)]
2503pub struct EntrySummary {
2504 max_path: Arc<Path>,
2505 count: usize,
2506 visible_count: usize,
2507 file_count: usize,
2508 visible_file_count: usize,
2509}
2510
2511impl Default for EntrySummary {
2512 fn default() -> Self {
2513 Self {
2514 max_path: Arc::from(Path::new("")),
2515 count: 0,
2516 visible_count: 0,
2517 file_count: 0,
2518 visible_file_count: 0,
2519 }
2520 }
2521}
2522
2523impl sum_tree::Summary for EntrySummary {
2524 type Context = ();
2525
2526 fn add_summary(&mut self, rhs: &Self, _: &()) {
2527 self.max_path = rhs.max_path.clone();
2528 self.count += rhs.count;
2529 self.visible_count += rhs.visible_count;
2530 self.file_count += rhs.file_count;
2531 self.visible_file_count += rhs.visible_file_count;
2532 }
2533}
2534
2535#[derive(Clone, Debug)]
2536struct PathEntry {
2537 id: ProjectEntryId,
2538 path: Arc<Path>,
2539 is_ignored: bool,
2540 scan_id: usize,
2541}
2542
2543impl sum_tree::Item for PathEntry {
2544 type Summary = PathEntrySummary;
2545
2546 fn summary(&self) -> Self::Summary {
2547 PathEntrySummary { max_id: self.id }
2548 }
2549}
2550
2551impl sum_tree::KeyedItem for PathEntry {
2552 type Key = ProjectEntryId;
2553
2554 fn key(&self) -> Self::Key {
2555 self.id
2556 }
2557}
2558
2559#[derive(Clone, Debug, Default)]
2560struct PathEntrySummary {
2561 max_id: ProjectEntryId,
2562}
2563
2564impl sum_tree::Summary for PathEntrySummary {
2565 type Context = ();
2566
2567 fn add_summary(&mut self, summary: &Self, _: &Self::Context) {
2568 self.max_id = summary.max_id;
2569 }
2570}
2571
2572impl<'a> sum_tree::Dimension<'a, PathEntrySummary> for ProjectEntryId {
2573 fn add_summary(&mut self, summary: &'a PathEntrySummary, _: &()) {
2574 *self = summary.max_id;
2575 }
2576}
2577
2578#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
2579pub struct PathKey(Arc<Path>);
2580
2581impl Default for PathKey {
2582 fn default() -> Self {
2583 Self(Path::new("").into())
2584 }
2585}
2586
2587impl<'a> sum_tree::Dimension<'a, EntrySummary> for PathKey {
2588 fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
2589 self.0 = summary.max_path.clone();
2590 }
2591}
2592
2593struct BackgroundScanner {
2594 snapshot: Mutex<LocalMutableSnapshot>,
2595 fs: Arc<dyn Fs>,
2596 status_updates_tx: UnboundedSender<ScanState>,
2597 executor: Arc<executor::Background>,
2598 refresh_requests_rx: channel::Receiver<(Vec<PathBuf>, barrier::Sender)>,
2599 prev_state: Mutex<BackgroundScannerState>,
2600 next_entry_id: Arc<AtomicUsize>,
2601 finished_initial_scan: bool,
2602}
2603
2604struct BackgroundScannerState {
2605 snapshot: Snapshot,
2606 event_paths: Vec<Arc<Path>>,
2607}
2608
2609impl BackgroundScanner {
2610 fn new(
2611 snapshot: LocalSnapshot,
2612 next_entry_id: Arc<AtomicUsize>,
2613 fs: Arc<dyn Fs>,
2614 status_updates_tx: UnboundedSender<ScanState>,
2615 executor: Arc<executor::Background>,
2616 refresh_requests_rx: channel::Receiver<(Vec<PathBuf>, barrier::Sender)>,
2617 ) -> Self {
2618 Self {
2619 fs,
2620 status_updates_tx,
2621 executor,
2622 refresh_requests_rx,
2623 next_entry_id,
2624 prev_state: Mutex::new(BackgroundScannerState {
2625 snapshot: snapshot.snapshot.clone(),
2626 event_paths: Default::default(),
2627 }),
2628 snapshot: Mutex::new(LocalMutableSnapshot {
2629 snapshot,
2630 removed_entry_ids: Default::default(),
2631 }),
2632 finished_initial_scan: false,
2633 }
2634 }
2635
2636 async fn run(
2637 &mut self,
2638 mut events_rx: Pin<Box<dyn Send + Stream<Item = Vec<fsevent::Event>>>>,
2639 ) {
2640 use futures::FutureExt as _;
2641
2642 let (root_abs_path, root_inode) = {
2643 let snapshot = self.snapshot.lock();
2644 (
2645 snapshot.abs_path.clone(),
2646 snapshot.root_entry().map(|e| e.inode),
2647 )
2648 };
2649
2650 // Populate ignores above the root.
2651 let ignore_stack;
2652 for ancestor in root_abs_path.ancestors().skip(1) {
2653 if let Ok(ignore) = build_gitignore(&ancestor.join(&*GITIGNORE), self.fs.as_ref()).await
2654 {
2655 self.snapshot
2656 .lock()
2657 .ignores_by_parent_abs_path
2658 .insert(ancestor.into(), (ignore.into(), false));
2659 }
2660 }
2661 {
2662 let mut snapshot = self.snapshot.lock();
2663 snapshot.scan_id += 1;
2664 ignore_stack = snapshot.ignore_stack_for_abs_path(&root_abs_path, true);
2665 if ignore_stack.is_all() {
2666 if let Some(mut root_entry) = snapshot.root_entry().cloned() {
2667 root_entry.is_ignored = true;
2668 snapshot.insert_entry(root_entry, self.fs.as_ref());
2669 }
2670 }
2671 };
2672
2673 // Perform an initial scan of the directory.
2674 let (scan_job_tx, scan_job_rx) = channel::unbounded();
2675 smol::block_on(scan_job_tx.send(ScanJob {
2676 abs_path: root_abs_path,
2677 path: Arc::from(Path::new("")),
2678 ignore_stack,
2679 ancestor_inodes: TreeSet::from_ordered_entries(root_inode),
2680 scan_queue: scan_job_tx.clone(),
2681 }))
2682 .unwrap();
2683 drop(scan_job_tx);
2684 self.scan_dirs(true, scan_job_rx).await;
2685 {
2686 let mut snapshot = self.snapshot.lock();
2687 snapshot.completed_scan_id = snapshot.scan_id;
2688 }
2689 self.send_status_update(false, None);
2690
2691 // Process any any FS events that occurred while performing the initial scan.
2692 // For these events, update events cannot be as precise, because we didn't
2693 // have the previous state loaded yet.
2694 if let Poll::Ready(Some(events)) = futures::poll!(events_rx.next()) {
2695 let mut paths = events.into_iter().map(|e| e.path).collect::<Vec<_>>();
2696 while let Poll::Ready(Some(more_events)) = futures::poll!(events_rx.next()) {
2697 paths.extend(more_events.into_iter().map(|e| e.path));
2698 }
2699 self.process_events(paths).await;
2700 }
2701
2702 self.finished_initial_scan = true;
2703
2704 // Continue processing events until the worktree is dropped.
2705 loop {
2706 select_biased! {
2707 // Process any path refresh requests from the worktree. Prioritize
2708 // these before handling changes reported by the filesystem.
2709 request = self.refresh_requests_rx.recv().fuse() => {
2710 let Ok((paths, barrier)) = request else { break };
2711 if !self.process_refresh_request(paths.clone(), barrier).await {
2712 return;
2713 }
2714 }
2715
2716 events = events_rx.next().fuse() => {
2717 let Some(events) = events else { break };
2718 let mut paths = events.into_iter().map(|e| e.path).collect::<Vec<_>>();
2719 while let Poll::Ready(Some(more_events)) = futures::poll!(events_rx.next()) {
2720 paths.extend(more_events.into_iter().map(|e| e.path));
2721 }
2722 self.process_events(paths.clone()).await;
2723 }
2724 }
2725 }
2726 }
2727
2728 async fn process_refresh_request(&self, paths: Vec<PathBuf>, barrier: barrier::Sender) -> bool {
2729 if let Some(mut paths) = self.reload_entries_for_paths(paths, None).await {
2730 paths.sort_unstable();
2731 util::extend_sorted(
2732 &mut self.prev_state.lock().event_paths,
2733 paths,
2734 usize::MAX,
2735 Ord::cmp,
2736 );
2737 }
2738 self.send_status_update(false, Some(barrier))
2739 }
2740
2741 async fn process_events(&mut self, paths: Vec<PathBuf>) {
2742 let (scan_job_tx, scan_job_rx) = channel::unbounded();
2743 let paths = self
2744 .reload_entries_for_paths(paths, Some(scan_job_tx.clone()))
2745 .await;
2746 if let Some(paths) = &paths {
2747 util::extend_sorted(
2748 &mut self.prev_state.lock().event_paths,
2749 paths.iter().cloned(),
2750 usize::MAX,
2751 Ord::cmp,
2752 );
2753 }
2754 drop(scan_job_tx);
2755 self.scan_dirs(false, scan_job_rx).await;
2756
2757 self.update_ignore_statuses().await;
2758
2759 let mut snapshot = self.snapshot.lock();
2760
2761 if let Some(paths) = paths {
2762 for path in paths {
2763 self.reload_repo_for_file_path(&path, &mut *snapshot, self.fs.as_ref());
2764 }
2765 }
2766
2767 let mut git_repositories = mem::take(&mut snapshot.git_repositories);
2768 git_repositories.retain(|work_directory_id, _| {
2769 snapshot
2770 .entry_for_id(*work_directory_id)
2771 .map_or(false, |entry| {
2772 snapshot.entry_for_path(entry.path.join(*DOT_GIT)).is_some()
2773 })
2774 });
2775 snapshot.git_repositories = git_repositories;
2776
2777 let mut git_repository_entries = mem::take(&mut snapshot.snapshot.repository_entries);
2778 git_repository_entries.retain(|_, entry| {
2779 snapshot
2780 .git_repositories
2781 .get(&entry.work_directory.0)
2782 .is_some()
2783 });
2784 snapshot.snapshot.repository_entries = git_repository_entries;
2785 snapshot.completed_scan_id = snapshot.scan_id;
2786 drop(snapshot);
2787
2788 self.send_status_update(false, None);
2789 self.prev_state.lock().event_paths.clear();
2790 }
2791
2792 async fn scan_dirs(
2793 &self,
2794 enable_progress_updates: bool,
2795 scan_jobs_rx: channel::Receiver<ScanJob>,
2796 ) {
2797 use futures::FutureExt as _;
2798
2799 if self
2800 .status_updates_tx
2801 .unbounded_send(ScanState::Started)
2802 .is_err()
2803 {
2804 return;
2805 }
2806
2807 let progress_update_count = AtomicUsize::new(0);
2808 self.executor
2809 .scoped(|scope| {
2810 for _ in 0..self.executor.num_cpus() {
2811 scope.spawn(async {
2812 let mut last_progress_update_count = 0;
2813 let progress_update_timer = self.progress_timer(enable_progress_updates).fuse();
2814 futures::pin_mut!(progress_update_timer);
2815
2816 loop {
2817 select_biased! {
2818 // Process any path refresh requests before moving on to process
2819 // the scan queue, so that user operations are prioritized.
2820 request = self.refresh_requests_rx.recv().fuse() => {
2821 let Ok((paths, barrier)) = request else { break };
2822 if !self.process_refresh_request(paths, barrier).await {
2823 return;
2824 }
2825 }
2826
2827 // Send periodic progress updates to the worktree. Use an atomic counter
2828 // to ensure that only one of the workers sends a progress update after
2829 // the update interval elapses.
2830 _ = progress_update_timer => {
2831 match progress_update_count.compare_exchange(
2832 last_progress_update_count,
2833 last_progress_update_count + 1,
2834 SeqCst,
2835 SeqCst
2836 ) {
2837 Ok(_) => {
2838 last_progress_update_count += 1;
2839 self.send_status_update(true, None);
2840 }
2841 Err(count) => {
2842 last_progress_update_count = count;
2843 }
2844 }
2845 progress_update_timer.set(self.progress_timer(enable_progress_updates).fuse());
2846 }
2847
2848 // Recursively load directories from the file system.
2849 job = scan_jobs_rx.recv().fuse() => {
2850 let Ok(job) = job else { break };
2851 if let Err(err) = self.scan_dir(&job).await {
2852 if job.path.as_ref() != Path::new("") {
2853 log::error!("error scanning directory {:?}: {}", job.abs_path, err);
2854 }
2855 }
2856 }
2857 }
2858 }
2859 })
2860 }
2861 })
2862 .await;
2863 }
2864
2865 fn send_status_update(&self, scanning: bool, barrier: Option<barrier::Sender>) -> bool {
2866 let mut prev_state = self.prev_state.lock();
2867 let new_snapshot = self.snapshot.lock().clone();
2868 let old_snapshot = mem::replace(&mut prev_state.snapshot, new_snapshot.snapshot.clone());
2869
2870 let changes = self.build_change_set(
2871 &old_snapshot,
2872 &new_snapshot.snapshot,
2873 &prev_state.event_paths,
2874 );
2875
2876 self.status_updates_tx
2877 .unbounded_send(ScanState::Updated {
2878 snapshot: new_snapshot,
2879 changes,
2880 scanning,
2881 barrier,
2882 })
2883 .is_ok()
2884 }
2885
2886 async fn scan_dir(&self, job: &ScanJob) -> Result<()> {
2887 let mut new_entries: Vec<Entry> = Vec::new();
2888 let mut new_jobs: Vec<Option<ScanJob>> = Vec::new();
2889 let mut ignore_stack = job.ignore_stack.clone();
2890 let mut new_ignore = None;
2891 let (root_abs_path, root_char_bag, next_entry_id) = {
2892 let snapshot = self.snapshot.lock();
2893 (
2894 snapshot.abs_path().clone(),
2895 snapshot.root_char_bag,
2896 self.next_entry_id.clone(),
2897 )
2898 };
2899 let mut child_paths = self.fs.read_dir(&job.abs_path).await?;
2900 while let Some(child_abs_path) = child_paths.next().await {
2901 let child_abs_path: Arc<Path> = match child_abs_path {
2902 Ok(child_abs_path) => child_abs_path.into(),
2903 Err(error) => {
2904 log::error!("error processing entry {:?}", error);
2905 continue;
2906 }
2907 };
2908
2909 let child_name = child_abs_path.file_name().unwrap();
2910 let child_path: Arc<Path> = job.path.join(child_name).into();
2911 let child_metadata = match self.fs.metadata(&child_abs_path).await {
2912 Ok(Some(metadata)) => metadata,
2913 Ok(None) => continue,
2914 Err(err) => {
2915 log::error!("error processing {:?}: {:?}", child_abs_path, err);
2916 continue;
2917 }
2918 };
2919
2920 // If we find a .gitignore, add it to the stack of ignores used to determine which paths are ignored
2921 if child_name == *GITIGNORE {
2922 match build_gitignore(&child_abs_path, self.fs.as_ref()).await {
2923 Ok(ignore) => {
2924 let ignore = Arc::new(ignore);
2925 ignore_stack = ignore_stack.append(job.abs_path.clone(), ignore.clone());
2926 new_ignore = Some(ignore);
2927 }
2928 Err(error) => {
2929 log::error!(
2930 "error loading .gitignore file {:?} - {:?}",
2931 child_name,
2932 error
2933 );
2934 }
2935 }
2936
2937 // Update ignore status of any child entries we've already processed to reflect the
2938 // ignore file in the current directory. Because `.gitignore` starts with a `.`,
2939 // there should rarely be too numerous. Update the ignore stack associated with any
2940 // new jobs as well.
2941 let mut new_jobs = new_jobs.iter_mut();
2942 for entry in &mut new_entries {
2943 let entry_abs_path = root_abs_path.join(&entry.path);
2944 entry.is_ignored =
2945 ignore_stack.is_abs_path_ignored(&entry_abs_path, entry.is_dir());
2946
2947 if entry.is_dir() {
2948 if let Some(job) = new_jobs.next().expect("Missing scan job for entry") {
2949 job.ignore_stack = if entry.is_ignored {
2950 IgnoreStack::all()
2951 } else {
2952 ignore_stack.clone()
2953 };
2954 }
2955 }
2956 }
2957 }
2958
2959 let mut child_entry = Entry::new(
2960 child_path.clone(),
2961 &child_metadata,
2962 &next_entry_id,
2963 root_char_bag,
2964 );
2965
2966 if child_entry.is_dir() {
2967 let is_ignored = ignore_stack.is_abs_path_ignored(&child_abs_path, true);
2968 child_entry.is_ignored = is_ignored;
2969
2970 // Avoid recursing until crash in the case of a recursive symlink
2971 if !job.ancestor_inodes.contains(&child_entry.inode) {
2972 let mut ancestor_inodes = job.ancestor_inodes.clone();
2973 ancestor_inodes.insert(child_entry.inode);
2974
2975 new_jobs.push(Some(ScanJob {
2976 abs_path: child_abs_path,
2977 path: child_path,
2978 ignore_stack: if is_ignored {
2979 IgnoreStack::all()
2980 } else {
2981 ignore_stack.clone()
2982 },
2983 ancestor_inodes,
2984 scan_queue: job.scan_queue.clone(),
2985 }));
2986 } else {
2987 new_jobs.push(None);
2988 }
2989 } else {
2990 child_entry.is_ignored = ignore_stack.is_abs_path_ignored(&child_abs_path, false);
2991 }
2992
2993 new_entries.push(child_entry);
2994 }
2995
2996 self.snapshot.lock().populate_dir(
2997 job.path.clone(),
2998 new_entries,
2999 new_ignore,
3000 self.fs.as_ref(),
3001 );
3002
3003 for new_job in new_jobs {
3004 if let Some(new_job) = new_job {
3005 job.scan_queue.send(new_job).await.unwrap();
3006 }
3007 }
3008
3009 Ok(())
3010 }
3011
3012 async fn reload_entries_for_paths(
3013 &self,
3014 mut abs_paths: Vec<PathBuf>,
3015 scan_queue_tx: Option<Sender<ScanJob>>,
3016 ) -> Option<Vec<Arc<Path>>> {
3017 let doing_recursive_update = scan_queue_tx.is_some();
3018
3019 abs_paths.sort_unstable();
3020 abs_paths.dedup_by(|a, b| a.starts_with(&b));
3021
3022 let root_abs_path = self.snapshot.lock().abs_path.clone();
3023 let root_canonical_path = self.fs.canonicalize(&root_abs_path).await.log_err()?;
3024 let metadata = futures::future::join_all(
3025 abs_paths
3026 .iter()
3027 .map(|abs_path| self.fs.metadata(&abs_path))
3028 .collect::<Vec<_>>(),
3029 )
3030 .await;
3031
3032 let mut snapshot = self.snapshot.lock();
3033 let is_idle = snapshot.completed_scan_id == snapshot.scan_id;
3034 snapshot.scan_id += 1;
3035 if is_idle && !doing_recursive_update {
3036 snapshot.completed_scan_id = snapshot.scan_id;
3037 }
3038
3039 // Remove any entries for paths that no longer exist or are being recursively
3040 // refreshed. Do this before adding any new entries, so that renames can be
3041 // detected regardless of the order of the paths.
3042 let mut event_paths = Vec::<Arc<Path>>::with_capacity(abs_paths.len());
3043 for (abs_path, metadata) in abs_paths.iter().zip(metadata.iter()) {
3044 if let Ok(path) = abs_path.strip_prefix(&root_canonical_path) {
3045 if matches!(metadata, Ok(None)) || doing_recursive_update {
3046 snapshot.remove_path(path);
3047 }
3048 event_paths.push(path.into());
3049 } else {
3050 log::error!(
3051 "unexpected event {:?} for root path {:?}",
3052 abs_path,
3053 root_canonical_path
3054 );
3055 }
3056 }
3057
3058 for (path, metadata) in event_paths.iter().cloned().zip(metadata.into_iter()) {
3059 let abs_path: Arc<Path> = root_abs_path.join(&path).into();
3060
3061 match metadata {
3062 Ok(Some(metadata)) => {
3063 let ignore_stack =
3064 snapshot.ignore_stack_for_abs_path(&abs_path, metadata.is_dir);
3065 let mut fs_entry = Entry::new(
3066 path.clone(),
3067 &metadata,
3068 self.next_entry_id.as_ref(),
3069 snapshot.root_char_bag,
3070 );
3071 fs_entry.is_ignored = ignore_stack.is_all();
3072 snapshot.insert_entry(fs_entry, self.fs.as_ref());
3073
3074 if let Some(scan_queue_tx) = &scan_queue_tx {
3075 let mut ancestor_inodes = snapshot.ancestor_inodes_for_path(&path);
3076 if metadata.is_dir && !ancestor_inodes.contains(&metadata.inode) {
3077 ancestor_inodes.insert(metadata.inode);
3078 smol::block_on(scan_queue_tx.send(ScanJob {
3079 abs_path,
3080 path,
3081 ignore_stack,
3082 ancestor_inodes,
3083 scan_queue: scan_queue_tx.clone(),
3084 }))
3085 .unwrap();
3086 }
3087 }
3088 }
3089 Ok(None) => {
3090 self.remove_repo_path(&path, &mut snapshot);
3091 }
3092 Err(err) => {
3093 // TODO - create a special 'error' entry in the entries tree to mark this
3094 log::error!("error reading file on event {:?}", err);
3095 }
3096 }
3097 }
3098
3099 Some(event_paths)
3100 }
3101
3102 fn remove_repo_path(&self, path: &Path, snapshot: &mut LocalSnapshot) -> Option<()> {
3103 if !path
3104 .components()
3105 .any(|component| component.as_os_str() == *DOT_GIT)
3106 {
3107 let scan_id = snapshot.scan_id;
3108 let repo = snapshot.repository_for_path(&path)?;
3109
3110 let repo_path = repo.work_directory.relativize(&snapshot, &path)?;
3111
3112 let work_dir = repo.work_directory(snapshot)?;
3113 let work_dir_id = repo.work_directory;
3114
3115 snapshot
3116 .git_repositories
3117 .update(&work_dir_id, |entry| entry.scan_id = scan_id);
3118
3119 snapshot.repository_entries.update(&work_dir, |entry| {
3120 entry
3121 .statuses
3122 .remove_range(&repo_path, &RepoPathDescendants(&repo_path))
3123 });
3124 }
3125
3126 Some(())
3127 }
3128
3129 fn reload_repo_for_file_path(
3130 &self,
3131 path: &Path,
3132 snapshot: &mut LocalSnapshot,
3133 fs: &dyn Fs,
3134 ) -> Option<()> {
3135 let scan_id = snapshot.scan_id;
3136
3137 if path
3138 .components()
3139 .any(|component| component.as_os_str() == *DOT_GIT)
3140 {
3141 let (entry_id, repo_ptr) = {
3142 let Some((entry_id, repo)) = snapshot.repo_for_metadata(&path) else {
3143 let dot_git_dir = path.ancestors()
3144 .skip_while(|ancestor| ancestor.file_name() != Some(&*DOT_GIT))
3145 .next()?;
3146
3147 snapshot.build_repo(dot_git_dir.into(), fs);
3148 return None;
3149 };
3150 if repo.full_scan_id == scan_id {
3151 return None;
3152 }
3153 (*entry_id, repo.repo_ptr.to_owned())
3154 };
3155
3156 let work_dir = snapshot
3157 .entry_for_id(entry_id)
3158 .map(|entry| RepositoryWorkDirectory(entry.path.clone()))?;
3159
3160 let repo = repo_ptr.lock();
3161 repo.reload_index();
3162 let branch = repo.branch_name();
3163 let statuses = repo.statuses().unwrap_or_default();
3164
3165 snapshot.git_repositories.update(&entry_id, |entry| {
3166 entry.scan_id = scan_id;
3167 entry.full_scan_id = scan_id;
3168 });
3169
3170 snapshot.repository_entries.update(&work_dir, |entry| {
3171 entry.branch = branch.map(Into::into);
3172 entry.statuses = statuses;
3173 });
3174 } else {
3175 if snapshot
3176 .entry_for_path(&path)
3177 .map(|entry| entry.is_ignored)
3178 .unwrap_or(false)
3179 {
3180 self.remove_repo_path(&path, snapshot);
3181 return None;
3182 }
3183
3184 let repo = snapshot.repository_for_path(&path)?;
3185
3186 let work_dir = repo.work_directory(snapshot)?;
3187 let work_dir_id = repo.work_directory.clone();
3188
3189 snapshot
3190 .git_repositories
3191 .update(&work_dir_id, |entry| entry.scan_id = scan_id);
3192
3193 let local_repo = snapshot.get_local_repo(&repo)?.to_owned();
3194
3195 // Short circuit if we've already scanned everything
3196 if local_repo.full_scan_id == scan_id {
3197 return None;
3198 }
3199
3200 let mut repository = snapshot.repository_entries.remove(&work_dir)?;
3201
3202 for entry in snapshot.descendent_entries(false, false, path) {
3203 let Some(repo_path) = repo.work_directory.relativize(snapshot, &entry.path) else {
3204 continue;
3205 };
3206
3207 let status = local_repo.repo_ptr.lock().status(&repo_path);
3208 if let Some(status) = status {
3209 repository.statuses.insert(repo_path.clone(), status);
3210 } else {
3211 repository.statuses.remove(&repo_path);
3212 }
3213 }
3214
3215 snapshot.repository_entries.insert(work_dir, repository)
3216 }
3217
3218 Some(())
3219 }
3220
3221 async fn update_ignore_statuses(&self) {
3222 use futures::FutureExt as _;
3223
3224 let mut snapshot = self.snapshot.lock().clone();
3225 let mut ignores_to_update = Vec::new();
3226 let mut ignores_to_delete = Vec::new();
3227 let abs_path = snapshot.abs_path.clone();
3228 for (parent_abs_path, (_, needs_update)) in &mut snapshot.ignores_by_parent_abs_path {
3229 if let Ok(parent_path) = parent_abs_path.strip_prefix(&abs_path) {
3230 if *needs_update {
3231 *needs_update = false;
3232 if snapshot.snapshot.entry_for_path(parent_path).is_some() {
3233 ignores_to_update.push(parent_abs_path.clone());
3234 }
3235 }
3236
3237 let ignore_path = parent_path.join(&*GITIGNORE);
3238 if snapshot.snapshot.entry_for_path(ignore_path).is_none() {
3239 ignores_to_delete.push(parent_abs_path.clone());
3240 }
3241 }
3242 }
3243
3244 for parent_abs_path in ignores_to_delete {
3245 snapshot.ignores_by_parent_abs_path.remove(&parent_abs_path);
3246 self.snapshot
3247 .lock()
3248 .ignores_by_parent_abs_path
3249 .remove(&parent_abs_path);
3250 }
3251
3252 let (ignore_queue_tx, ignore_queue_rx) = channel::unbounded();
3253 ignores_to_update.sort_unstable();
3254 let mut ignores_to_update = ignores_to_update.into_iter().peekable();
3255 while let Some(parent_abs_path) = ignores_to_update.next() {
3256 while ignores_to_update
3257 .peek()
3258 .map_or(false, |p| p.starts_with(&parent_abs_path))
3259 {
3260 ignores_to_update.next().unwrap();
3261 }
3262
3263 let ignore_stack = snapshot.ignore_stack_for_abs_path(&parent_abs_path, true);
3264 smol::block_on(ignore_queue_tx.send(UpdateIgnoreStatusJob {
3265 abs_path: parent_abs_path,
3266 ignore_stack,
3267 ignore_queue: ignore_queue_tx.clone(),
3268 }))
3269 .unwrap();
3270 }
3271 drop(ignore_queue_tx);
3272
3273 self.executor
3274 .scoped(|scope| {
3275 for _ in 0..self.executor.num_cpus() {
3276 scope.spawn(async {
3277 loop {
3278 select_biased! {
3279 // Process any path refresh requests before moving on to process
3280 // the queue of ignore statuses.
3281 request = self.refresh_requests_rx.recv().fuse() => {
3282 let Ok((paths, barrier)) = request else { break };
3283 if !self.process_refresh_request(paths, barrier).await {
3284 return;
3285 }
3286 }
3287
3288 // Recursively process directories whose ignores have changed.
3289 job = ignore_queue_rx.recv().fuse() => {
3290 let Ok(job) = job else { break };
3291 self.update_ignore_status(job, &snapshot).await;
3292 }
3293 }
3294 }
3295 });
3296 }
3297 })
3298 .await;
3299 }
3300
3301 async fn update_ignore_status(&self, job: UpdateIgnoreStatusJob, snapshot: &LocalSnapshot) {
3302 let mut ignore_stack = job.ignore_stack;
3303 if let Some((ignore, _)) = snapshot.ignores_by_parent_abs_path.get(&job.abs_path) {
3304 ignore_stack = ignore_stack.append(job.abs_path.clone(), ignore.clone());
3305 }
3306
3307 let mut entries_by_id_edits = Vec::new();
3308 let mut entries_by_path_edits = Vec::new();
3309 let path = job.abs_path.strip_prefix(&snapshot.abs_path).unwrap();
3310 for mut entry in snapshot.child_entries(path).cloned() {
3311 let was_ignored = entry.is_ignored;
3312 let abs_path = snapshot.abs_path().join(&entry.path);
3313 entry.is_ignored = ignore_stack.is_abs_path_ignored(&abs_path, entry.is_dir());
3314 if entry.is_dir() {
3315 let child_ignore_stack = if entry.is_ignored {
3316 IgnoreStack::all()
3317 } else {
3318 ignore_stack.clone()
3319 };
3320 job.ignore_queue
3321 .send(UpdateIgnoreStatusJob {
3322 abs_path: abs_path.into(),
3323 ignore_stack: child_ignore_stack,
3324 ignore_queue: job.ignore_queue.clone(),
3325 })
3326 .await
3327 .unwrap();
3328 }
3329
3330 if entry.is_ignored != was_ignored {
3331 let mut path_entry = snapshot.entries_by_id.get(&entry.id, &()).unwrap().clone();
3332 path_entry.scan_id = snapshot.scan_id;
3333 path_entry.is_ignored = entry.is_ignored;
3334 entries_by_id_edits.push(Edit::Insert(path_entry));
3335 entries_by_path_edits.push(Edit::Insert(entry));
3336 }
3337 }
3338
3339 let mut snapshot = self.snapshot.lock();
3340 snapshot.entries_by_path.edit(entries_by_path_edits, &());
3341 snapshot.entries_by_id.edit(entries_by_id_edits, &());
3342 }
3343
3344 fn build_change_set(
3345 &self,
3346 old_snapshot: &Snapshot,
3347 new_snapshot: &Snapshot,
3348 event_paths: &[Arc<Path>],
3349 ) -> HashMap<(Arc<Path>, ProjectEntryId), PathChange> {
3350 use PathChange::{Added, AddedOrUpdated, Removed, Updated};
3351
3352 let mut changes = HashMap::default();
3353 let mut old_paths = old_snapshot.entries_by_path.cursor::<PathKey>();
3354 let mut new_paths = new_snapshot.entries_by_path.cursor::<PathKey>();
3355 let received_before_initialized = !self.finished_initial_scan;
3356
3357 for path in event_paths {
3358 let path = PathKey(path.clone());
3359 old_paths.seek(&path, Bias::Left, &());
3360 new_paths.seek(&path, Bias::Left, &());
3361
3362 loop {
3363 match (old_paths.item(), new_paths.item()) {
3364 (Some(old_entry), Some(new_entry)) => {
3365 if old_entry.path > path.0
3366 && new_entry.path > path.0
3367 && !old_entry.path.starts_with(&path.0)
3368 && !new_entry.path.starts_with(&path.0)
3369 {
3370 break;
3371 }
3372
3373 match Ord::cmp(&old_entry.path, &new_entry.path) {
3374 Ordering::Less => {
3375 changes.insert((old_entry.path.clone(), old_entry.id), Removed);
3376 old_paths.next(&());
3377 }
3378 Ordering::Equal => {
3379 if received_before_initialized {
3380 // If the worktree was not fully initialized when this event was generated,
3381 // we can't know whether this entry was added during the scan or whether
3382 // it was merely updated.
3383 changes.insert(
3384 (new_entry.path.clone(), new_entry.id),
3385 AddedOrUpdated,
3386 );
3387 } else if old_entry.mtime != new_entry.mtime {
3388 changes.insert((new_entry.path.clone(), new_entry.id), Updated);
3389 }
3390 old_paths.next(&());
3391 new_paths.next(&());
3392 }
3393 Ordering::Greater => {
3394 changes.insert((new_entry.path.clone(), new_entry.id), Added);
3395 new_paths.next(&());
3396 }
3397 }
3398 }
3399 (Some(old_entry), None) => {
3400 changes.insert((old_entry.path.clone(), old_entry.id), Removed);
3401 old_paths.next(&());
3402 }
3403 (None, Some(new_entry)) => {
3404 changes.insert((new_entry.path.clone(), new_entry.id), Added);
3405 new_paths.next(&());
3406 }
3407 (None, None) => break,
3408 }
3409 }
3410 }
3411
3412 changes
3413 }
3414
3415 async fn progress_timer(&self, running: bool) {
3416 if !running {
3417 return futures::future::pending().await;
3418 }
3419
3420 #[cfg(any(test, feature = "test-support"))]
3421 if self.fs.is_fake() {
3422 return self.executor.simulate_random_delay().await;
3423 }
3424
3425 smol::Timer::after(Duration::from_millis(100)).await;
3426 }
3427}
3428
3429fn char_bag_for_path(root_char_bag: CharBag, path: &Path) -> CharBag {
3430 let mut result = root_char_bag;
3431 result.extend(
3432 path.to_string_lossy()
3433 .chars()
3434 .map(|c| c.to_ascii_lowercase()),
3435 );
3436 result
3437}
3438
3439struct ScanJob {
3440 abs_path: Arc<Path>,
3441 path: Arc<Path>,
3442 ignore_stack: Arc<IgnoreStack>,
3443 scan_queue: Sender<ScanJob>,
3444 ancestor_inodes: TreeSet<u64>,
3445}
3446
3447struct UpdateIgnoreStatusJob {
3448 abs_path: Arc<Path>,
3449 ignore_stack: Arc<IgnoreStack>,
3450 ignore_queue: Sender<UpdateIgnoreStatusJob>,
3451}
3452
3453pub trait WorktreeHandle {
3454 #[cfg(any(test, feature = "test-support"))]
3455 fn flush_fs_events<'a>(
3456 &self,
3457 cx: &'a gpui::TestAppContext,
3458 ) -> futures::future::LocalBoxFuture<'a, ()>;
3459}
3460
3461impl WorktreeHandle for ModelHandle<Worktree> {
3462 // When the worktree's FS event stream sometimes delivers "redundant" events for FS changes that
3463 // occurred before the worktree was constructed. These events can cause the worktree to perfrom
3464 // extra directory scans, and emit extra scan-state notifications.
3465 //
3466 // This function mutates the worktree's directory and waits for those mutations to be picked up,
3467 // to ensure that all redundant FS events have already been processed.
3468 #[cfg(any(test, feature = "test-support"))]
3469 fn flush_fs_events<'a>(
3470 &self,
3471 cx: &'a gpui::TestAppContext,
3472 ) -> futures::future::LocalBoxFuture<'a, ()> {
3473 use smol::future::FutureExt;
3474
3475 let filename = "fs-event-sentinel";
3476 let tree = self.clone();
3477 let (fs, root_path) = self.read_with(cx, |tree, _| {
3478 let tree = tree.as_local().unwrap();
3479 (tree.fs.clone(), tree.abs_path().clone())
3480 });
3481
3482 async move {
3483 fs.create_file(&root_path.join(filename), Default::default())
3484 .await
3485 .unwrap();
3486 tree.condition(cx, |tree, _| tree.entry_for_path(filename).is_some())
3487 .await;
3488
3489 fs.remove_file(&root_path.join(filename), Default::default())
3490 .await
3491 .unwrap();
3492 tree.condition(cx, |tree, _| tree.entry_for_path(filename).is_none())
3493 .await;
3494
3495 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3496 .await;
3497 }
3498 .boxed_local()
3499 }
3500}
3501
3502#[derive(Clone, Debug)]
3503struct TraversalProgress<'a> {
3504 max_path: &'a Path,
3505 count: usize,
3506 visible_count: usize,
3507 file_count: usize,
3508 visible_file_count: usize,
3509}
3510
3511impl<'a> TraversalProgress<'a> {
3512 fn count(&self, include_dirs: bool, include_ignored: bool) -> usize {
3513 match (include_ignored, include_dirs) {
3514 (true, true) => self.count,
3515 (true, false) => self.file_count,
3516 (false, true) => self.visible_count,
3517 (false, false) => self.visible_file_count,
3518 }
3519 }
3520}
3521
3522impl<'a> sum_tree::Dimension<'a, EntrySummary> for TraversalProgress<'a> {
3523 fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
3524 self.max_path = summary.max_path.as_ref();
3525 self.count += summary.count;
3526 self.visible_count += summary.visible_count;
3527 self.file_count += summary.file_count;
3528 self.visible_file_count += summary.visible_file_count;
3529 }
3530}
3531
3532impl<'a> Default for TraversalProgress<'a> {
3533 fn default() -> Self {
3534 Self {
3535 max_path: Path::new(""),
3536 count: 0,
3537 visible_count: 0,
3538 file_count: 0,
3539 visible_file_count: 0,
3540 }
3541 }
3542}
3543
3544pub struct Traversal<'a> {
3545 cursor: sum_tree::Cursor<'a, Entry, TraversalProgress<'a>>,
3546 include_ignored: bool,
3547 include_dirs: bool,
3548}
3549
3550impl<'a> Traversal<'a> {
3551 pub fn advance(&mut self) -> bool {
3552 self.cursor.seek_forward(
3553 &TraversalTarget::Count {
3554 count: self.end_offset() + 1,
3555 include_dirs: self.include_dirs,
3556 include_ignored: self.include_ignored,
3557 },
3558 Bias::Left,
3559 &(),
3560 )
3561 }
3562
3563 pub fn advance_to_sibling(&mut self) -> bool {
3564 while let Some(entry) = self.cursor.item() {
3565 self.cursor.seek_forward(
3566 &TraversalTarget::PathSuccessor(&entry.path),
3567 Bias::Left,
3568 &(),
3569 );
3570 if let Some(entry) = self.cursor.item() {
3571 if (self.include_dirs || !entry.is_dir())
3572 && (self.include_ignored || !entry.is_ignored)
3573 {
3574 return true;
3575 }
3576 }
3577 }
3578 false
3579 }
3580
3581 pub fn entry(&self) -> Option<&'a Entry> {
3582 self.cursor.item()
3583 }
3584
3585 pub fn start_offset(&self) -> usize {
3586 self.cursor
3587 .start()
3588 .count(self.include_dirs, self.include_ignored)
3589 }
3590
3591 pub fn end_offset(&self) -> usize {
3592 self.cursor
3593 .end(&())
3594 .count(self.include_dirs, self.include_ignored)
3595 }
3596}
3597
3598impl<'a> Iterator for Traversal<'a> {
3599 type Item = &'a Entry;
3600
3601 fn next(&mut self) -> Option<Self::Item> {
3602 if let Some(item) = self.entry() {
3603 self.advance();
3604 Some(item)
3605 } else {
3606 None
3607 }
3608 }
3609}
3610
3611#[derive(Debug)]
3612enum TraversalTarget<'a> {
3613 Path(&'a Path),
3614 PathSuccessor(&'a Path),
3615 Count {
3616 count: usize,
3617 include_ignored: bool,
3618 include_dirs: bool,
3619 },
3620}
3621
3622impl<'a, 'b> SeekTarget<'a, EntrySummary, TraversalProgress<'a>> for TraversalTarget<'b> {
3623 fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: &()) -> Ordering {
3624 match self {
3625 TraversalTarget::Path(path) => path.cmp(&cursor_location.max_path),
3626 TraversalTarget::PathSuccessor(path) => {
3627 if !cursor_location.max_path.starts_with(path) {
3628 Ordering::Equal
3629 } else {
3630 Ordering::Greater
3631 }
3632 }
3633 TraversalTarget::Count {
3634 count,
3635 include_dirs,
3636 include_ignored,
3637 } => Ord::cmp(
3638 count,
3639 &cursor_location.count(*include_dirs, *include_ignored),
3640 ),
3641 }
3642 }
3643}
3644
3645struct ChildEntriesIter<'a> {
3646 parent_path: &'a Path,
3647 traversal: Traversal<'a>,
3648}
3649
3650impl<'a> Iterator for ChildEntriesIter<'a> {
3651 type Item = &'a Entry;
3652
3653 fn next(&mut self) -> Option<Self::Item> {
3654 if let Some(item) = self.traversal.entry() {
3655 if item.path.starts_with(&self.parent_path) {
3656 self.traversal.advance_to_sibling();
3657 return Some(item);
3658 }
3659 }
3660 None
3661 }
3662}
3663
3664struct DescendentEntriesIter<'a> {
3665 parent_path: &'a Path,
3666 traversal: Traversal<'a>,
3667}
3668
3669impl<'a> Iterator for DescendentEntriesIter<'a> {
3670 type Item = &'a Entry;
3671
3672 fn next(&mut self) -> Option<Self::Item> {
3673 if let Some(item) = self.traversal.entry() {
3674 if item.path.starts_with(&self.parent_path) {
3675 self.traversal.advance();
3676 return Some(item);
3677 }
3678 }
3679 None
3680 }
3681}
3682
3683impl<'a> From<&'a Entry> for proto::Entry {
3684 fn from(entry: &'a Entry) -> Self {
3685 Self {
3686 id: entry.id.to_proto(),
3687 is_dir: entry.is_dir(),
3688 path: entry.path.to_string_lossy().into(),
3689 inode: entry.inode,
3690 mtime: Some(entry.mtime.into()),
3691 is_symlink: entry.is_symlink,
3692 is_ignored: entry.is_ignored,
3693 }
3694 }
3695}
3696
3697impl<'a> TryFrom<(&'a CharBag, proto::Entry)> for Entry {
3698 type Error = anyhow::Error;
3699
3700 fn try_from((root_char_bag, entry): (&'a CharBag, proto::Entry)) -> Result<Self> {
3701 if let Some(mtime) = entry.mtime {
3702 let kind = if entry.is_dir {
3703 EntryKind::Dir
3704 } else {
3705 let mut char_bag = *root_char_bag;
3706 char_bag.extend(entry.path.chars().map(|c| c.to_ascii_lowercase()));
3707 EntryKind::File(char_bag)
3708 };
3709 let path: Arc<Path> = PathBuf::from(entry.path).into();
3710 Ok(Entry {
3711 id: ProjectEntryId::from_proto(entry.id),
3712 kind,
3713 path,
3714 inode: entry.inode,
3715 mtime: mtime.into(),
3716 is_symlink: entry.is_symlink,
3717 is_ignored: entry.is_ignored,
3718 })
3719 } else {
3720 Err(anyhow!(
3721 "missing mtime in remote worktree entry {:?}",
3722 entry.path
3723 ))
3724 }
3725 }
3726}
3727
3728#[cfg(test)]
3729mod tests {
3730 use super::*;
3731 use fs::{FakeFs, RealFs};
3732 use gpui::{executor::Deterministic, TestAppContext};
3733 use pretty_assertions::assert_eq;
3734 use rand::prelude::*;
3735 use serde_json::json;
3736 use std::{env, fmt::Write};
3737 use util::{http::FakeHttpClient, test::temp_tree};
3738
3739 #[gpui::test]
3740 async fn test_traversal(cx: &mut TestAppContext) {
3741 let fs = FakeFs::new(cx.background());
3742 fs.insert_tree(
3743 "/root",
3744 json!({
3745 ".gitignore": "a/b\n",
3746 "a": {
3747 "b": "",
3748 "c": "",
3749 }
3750 }),
3751 )
3752 .await;
3753
3754 let http_client = FakeHttpClient::with_404_response();
3755 let client = cx.read(|cx| Client::new(http_client, cx));
3756
3757 let tree = Worktree::local(
3758 client,
3759 Path::new("/root"),
3760 true,
3761 fs,
3762 Default::default(),
3763 &mut cx.to_async(),
3764 )
3765 .await
3766 .unwrap();
3767 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3768 .await;
3769
3770 tree.read_with(cx, |tree, _| {
3771 assert_eq!(
3772 tree.entries(false)
3773 .map(|entry| entry.path.as_ref())
3774 .collect::<Vec<_>>(),
3775 vec![
3776 Path::new(""),
3777 Path::new(".gitignore"),
3778 Path::new("a"),
3779 Path::new("a/c"),
3780 ]
3781 );
3782 assert_eq!(
3783 tree.entries(true)
3784 .map(|entry| entry.path.as_ref())
3785 .collect::<Vec<_>>(),
3786 vec![
3787 Path::new(""),
3788 Path::new(".gitignore"),
3789 Path::new("a"),
3790 Path::new("a/b"),
3791 Path::new("a/c"),
3792 ]
3793 );
3794 })
3795 }
3796
3797 #[gpui::test]
3798 async fn test_descendent_entries(cx: &mut TestAppContext) {
3799 let fs = FakeFs::new(cx.background());
3800 fs.insert_tree(
3801 "/root",
3802 json!({
3803 "a": "",
3804 "b": {
3805 "c": {
3806 "d": ""
3807 },
3808 "e": {}
3809 },
3810 "f": "",
3811 "g": {
3812 "h": {}
3813 },
3814 "i": {
3815 "j": {
3816 "k": ""
3817 },
3818 "l": {
3819
3820 }
3821 },
3822 ".gitignore": "i/j\n",
3823 }),
3824 )
3825 .await;
3826
3827 let http_client = FakeHttpClient::with_404_response();
3828 let client = cx.read(|cx| Client::new(http_client, cx));
3829
3830 let tree = Worktree::local(
3831 client,
3832 Path::new("/root"),
3833 true,
3834 fs,
3835 Default::default(),
3836 &mut cx.to_async(),
3837 )
3838 .await
3839 .unwrap();
3840 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3841 .await;
3842
3843 tree.read_with(cx, |tree, _| {
3844 assert_eq!(
3845 tree.descendent_entries(false, false, Path::new("b"))
3846 .map(|entry| entry.path.as_ref())
3847 .collect::<Vec<_>>(),
3848 vec![Path::new("b/c/d"),]
3849 );
3850 assert_eq!(
3851 tree.descendent_entries(true, false, Path::new("b"))
3852 .map(|entry| entry.path.as_ref())
3853 .collect::<Vec<_>>(),
3854 vec![
3855 Path::new("b"),
3856 Path::new("b/c"),
3857 Path::new("b/c/d"),
3858 Path::new("b/e"),
3859 ]
3860 );
3861
3862 assert_eq!(
3863 tree.descendent_entries(false, false, Path::new("g"))
3864 .map(|entry| entry.path.as_ref())
3865 .collect::<Vec<_>>(),
3866 Vec::<PathBuf>::new()
3867 );
3868 assert_eq!(
3869 tree.descendent_entries(true, false, Path::new("g"))
3870 .map(|entry| entry.path.as_ref())
3871 .collect::<Vec<_>>(),
3872 vec![Path::new("g"), Path::new("g/h"),]
3873 );
3874
3875 assert_eq!(
3876 tree.descendent_entries(false, false, Path::new("i"))
3877 .map(|entry| entry.path.as_ref())
3878 .collect::<Vec<_>>(),
3879 Vec::<PathBuf>::new()
3880 );
3881 assert_eq!(
3882 tree.descendent_entries(false, true, Path::new("i"))
3883 .map(|entry| entry.path.as_ref())
3884 .collect::<Vec<_>>(),
3885 vec![Path::new("i/j/k")]
3886 );
3887 assert_eq!(
3888 tree.descendent_entries(true, false, Path::new("i"))
3889 .map(|entry| entry.path.as_ref())
3890 .collect::<Vec<_>>(),
3891 vec![Path::new("i"), Path::new("i/l"),]
3892 );
3893 })
3894 }
3895
3896 #[gpui::test(iterations = 10)]
3897 async fn test_circular_symlinks(executor: Arc<Deterministic>, cx: &mut TestAppContext) {
3898 let fs = FakeFs::new(cx.background());
3899 fs.insert_tree(
3900 "/root",
3901 json!({
3902 "lib": {
3903 "a": {
3904 "a.txt": ""
3905 },
3906 "b": {
3907 "b.txt": ""
3908 }
3909 }
3910 }),
3911 )
3912 .await;
3913 fs.insert_symlink("/root/lib/a/lib", "..".into()).await;
3914 fs.insert_symlink("/root/lib/b/lib", "..".into()).await;
3915
3916 let client = cx.read(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
3917 let tree = Worktree::local(
3918 client,
3919 Path::new("/root"),
3920 true,
3921 fs.clone(),
3922 Default::default(),
3923 &mut cx.to_async(),
3924 )
3925 .await
3926 .unwrap();
3927
3928 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3929 .await;
3930
3931 tree.read_with(cx, |tree, _| {
3932 assert_eq!(
3933 tree.entries(false)
3934 .map(|entry| entry.path.as_ref())
3935 .collect::<Vec<_>>(),
3936 vec![
3937 Path::new(""),
3938 Path::new("lib"),
3939 Path::new("lib/a"),
3940 Path::new("lib/a/a.txt"),
3941 Path::new("lib/a/lib"),
3942 Path::new("lib/b"),
3943 Path::new("lib/b/b.txt"),
3944 Path::new("lib/b/lib"),
3945 ]
3946 );
3947 });
3948
3949 fs.rename(
3950 Path::new("/root/lib/a/lib"),
3951 Path::new("/root/lib/a/lib-2"),
3952 Default::default(),
3953 )
3954 .await
3955 .unwrap();
3956 executor.run_until_parked();
3957 tree.read_with(cx, |tree, _| {
3958 assert_eq!(
3959 tree.entries(false)
3960 .map(|entry| entry.path.as_ref())
3961 .collect::<Vec<_>>(),
3962 vec![
3963 Path::new(""),
3964 Path::new("lib"),
3965 Path::new("lib/a"),
3966 Path::new("lib/a/a.txt"),
3967 Path::new("lib/a/lib-2"),
3968 Path::new("lib/b"),
3969 Path::new("lib/b/b.txt"),
3970 Path::new("lib/b/lib"),
3971 ]
3972 );
3973 });
3974 }
3975
3976 #[gpui::test]
3977 async fn test_rescan_with_gitignore(cx: &mut TestAppContext) {
3978 let parent_dir = temp_tree(json!({
3979 ".gitignore": "ancestor-ignored-file1\nancestor-ignored-file2\n",
3980 "tree": {
3981 ".git": {},
3982 ".gitignore": "ignored-dir\n",
3983 "tracked-dir": {
3984 "tracked-file1": "",
3985 "ancestor-ignored-file1": "",
3986 },
3987 "ignored-dir": {
3988 "ignored-file1": ""
3989 }
3990 }
3991 }));
3992 let dir = parent_dir.path().join("tree");
3993
3994 let client = cx.read(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
3995
3996 let tree = Worktree::local(
3997 client,
3998 dir.as_path(),
3999 true,
4000 Arc::new(RealFs),
4001 Default::default(),
4002 &mut cx.to_async(),
4003 )
4004 .await
4005 .unwrap();
4006 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
4007 .await;
4008 tree.flush_fs_events(cx).await;
4009 cx.read(|cx| {
4010 let tree = tree.read(cx);
4011 assert!(
4012 !tree
4013 .entry_for_path("tracked-dir/tracked-file1")
4014 .unwrap()
4015 .is_ignored
4016 );
4017 assert!(
4018 tree.entry_for_path("tracked-dir/ancestor-ignored-file1")
4019 .unwrap()
4020 .is_ignored
4021 );
4022 assert!(
4023 tree.entry_for_path("ignored-dir/ignored-file1")
4024 .unwrap()
4025 .is_ignored
4026 );
4027 });
4028
4029 std::fs::write(dir.join("tracked-dir/tracked-file2"), "").unwrap();
4030 std::fs::write(dir.join("tracked-dir/ancestor-ignored-file2"), "").unwrap();
4031 std::fs::write(dir.join("ignored-dir/ignored-file2"), "").unwrap();
4032 tree.flush_fs_events(cx).await;
4033 cx.read(|cx| {
4034 let tree = tree.read(cx);
4035 assert!(
4036 !tree
4037 .entry_for_path("tracked-dir/tracked-file2")
4038 .unwrap()
4039 .is_ignored
4040 );
4041 assert!(
4042 tree.entry_for_path("tracked-dir/ancestor-ignored-file2")
4043 .unwrap()
4044 .is_ignored
4045 );
4046 assert!(
4047 tree.entry_for_path("ignored-dir/ignored-file2")
4048 .unwrap()
4049 .is_ignored
4050 );
4051 assert!(tree.entry_for_path(".git").unwrap().is_ignored);
4052 });
4053 }
4054
4055 #[gpui::test]
4056 async fn test_git_repository_for_path(cx: &mut TestAppContext) {
4057 let root = temp_tree(json!({
4058 "c.txt": "",
4059 "dir1": {
4060 ".git": {},
4061 "deps": {
4062 "dep1": {
4063 ".git": {},
4064 "src": {
4065 "a.txt": ""
4066 }
4067 }
4068 },
4069 "src": {
4070 "b.txt": ""
4071 }
4072 },
4073 }));
4074
4075 let http_client = FakeHttpClient::with_404_response();
4076 let client = cx.read(|cx| Client::new(http_client, cx));
4077 let tree = Worktree::local(
4078 client,
4079 root.path(),
4080 true,
4081 Arc::new(RealFs),
4082 Default::default(),
4083 &mut cx.to_async(),
4084 )
4085 .await
4086 .unwrap();
4087
4088 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
4089 .await;
4090 tree.flush_fs_events(cx).await;
4091
4092 tree.read_with(cx, |tree, _cx| {
4093 let tree = tree.as_local().unwrap();
4094
4095 assert!(tree.repository_for_path("c.txt".as_ref()).is_none());
4096
4097 let entry = tree.repository_for_path("dir1/src/b.txt".as_ref()).unwrap();
4098 assert_eq!(
4099 entry
4100 .work_directory(tree)
4101 .map(|directory| directory.as_ref().to_owned()),
4102 Some(Path::new("dir1").to_owned())
4103 );
4104
4105 let entry = tree
4106 .repository_for_path("dir1/deps/dep1/src/a.txt".as_ref())
4107 .unwrap();
4108 assert_eq!(
4109 entry
4110 .work_directory(tree)
4111 .map(|directory| directory.as_ref().to_owned()),
4112 Some(Path::new("dir1/deps/dep1").to_owned())
4113 );
4114
4115 let entries = tree.files(false, 0);
4116
4117 let paths_with_repos = tree
4118 .entries_with_repositories(entries)
4119 .map(|(entry, repo)| {
4120 (
4121 entry.path.as_ref(),
4122 repo.and_then(|repo| {
4123 repo.work_directory(&tree)
4124 .map(|work_directory| work_directory.0.to_path_buf())
4125 }),
4126 )
4127 })
4128 .collect::<Vec<_>>();
4129
4130 assert_eq!(
4131 paths_with_repos,
4132 &[
4133 (Path::new("c.txt"), None),
4134 (
4135 Path::new("dir1/deps/dep1/src/a.txt"),
4136 Some(Path::new("dir1/deps/dep1").into())
4137 ),
4138 (Path::new("dir1/src/b.txt"), Some(Path::new("dir1").into())),
4139 ]
4140 );
4141 });
4142
4143 let repo_update_events = Arc::new(Mutex::new(vec![]));
4144 tree.update(cx, |_, cx| {
4145 let repo_update_events = repo_update_events.clone();
4146 cx.subscribe(&tree, move |_, _, event, _| {
4147 if let Event::UpdatedGitRepositories(update) = event {
4148 repo_update_events.lock().push(update.clone());
4149 }
4150 })
4151 .detach();
4152 });
4153
4154 std::fs::write(root.path().join("dir1/.git/random_new_file"), "hello").unwrap();
4155 tree.flush_fs_events(cx).await;
4156
4157 assert_eq!(
4158 repo_update_events.lock()[0]
4159 .keys()
4160 .cloned()
4161 .collect::<Vec<Arc<Path>>>(),
4162 vec![Path::new("dir1").into()]
4163 );
4164
4165 std::fs::remove_dir_all(root.path().join("dir1/.git")).unwrap();
4166 tree.flush_fs_events(cx).await;
4167
4168 tree.read_with(cx, |tree, _cx| {
4169 let tree = tree.as_local().unwrap();
4170
4171 assert!(tree
4172 .repository_for_path("dir1/src/b.txt".as_ref())
4173 .is_none());
4174 });
4175 }
4176
4177 #[gpui::test]
4178 async fn test_git_status(cx: &mut TestAppContext) {
4179 #[track_caller]
4180 fn git_init(path: &Path) -> git2::Repository {
4181 git2::Repository::init(path).expect("Failed to initialize git repository")
4182 }
4183
4184 #[track_caller]
4185 fn git_add(path: &Path, repo: &git2::Repository) {
4186 let mut index = repo.index().expect("Failed to get index");
4187 index.add_path(path).expect("Failed to add a.txt");
4188 index.write().expect("Failed to write index");
4189 }
4190
4191 #[track_caller]
4192 fn git_remove_index(path: &Path, repo: &git2::Repository) {
4193 let mut index = repo.index().expect("Failed to get index");
4194 index.remove_path(path).expect("Failed to add a.txt");
4195 index.write().expect("Failed to write index");
4196 }
4197
4198 #[track_caller]
4199 fn git_commit(msg: &'static str, repo: &git2::Repository) {
4200 use git2::Signature;
4201
4202 let signature = Signature::now("test", "test@zed.dev").unwrap();
4203 let oid = repo.index().unwrap().write_tree().unwrap();
4204 let tree = repo.find_tree(oid).unwrap();
4205 if let Some(head) = repo.head().ok() {
4206 let parent_obj = head.peel(git2::ObjectType::Commit).unwrap();
4207
4208 let parent_commit = parent_obj.as_commit().unwrap();
4209
4210 repo.commit(
4211 Some("HEAD"),
4212 &signature,
4213 &signature,
4214 msg,
4215 &tree,
4216 &[parent_commit],
4217 )
4218 .expect("Failed to commit with parent");
4219 } else {
4220 repo.commit(Some("HEAD"), &signature, &signature, msg, &tree, &[])
4221 .expect("Failed to commit");
4222 }
4223 }
4224
4225 #[track_caller]
4226 fn git_stash(repo: &mut git2::Repository) {
4227 use git2::Signature;
4228
4229 let signature = Signature::now("test", "test@zed.dev").unwrap();
4230 repo.stash_save(&signature, "N/A", None)
4231 .expect("Failed to stash");
4232 }
4233
4234 #[track_caller]
4235 fn git_reset(offset: usize, repo: &git2::Repository) {
4236 let head = repo.head().expect("Couldn't get repo head");
4237 let object = head.peel(git2::ObjectType::Commit).unwrap();
4238 let commit = object.as_commit().unwrap();
4239 let new_head = commit
4240 .parents()
4241 .inspect(|parnet| {
4242 parnet.message();
4243 })
4244 .skip(offset)
4245 .next()
4246 .expect("Not enough history");
4247 repo.reset(&new_head.as_object(), git2::ResetType::Soft, None)
4248 .expect("Could not reset");
4249 }
4250
4251 #[allow(dead_code)]
4252 #[track_caller]
4253 fn git_status(repo: &git2::Repository) -> HashMap<String, git2::Status> {
4254 repo.statuses(None)
4255 .unwrap()
4256 .iter()
4257 .map(|status| (status.path().unwrap().to_string(), status.status()))
4258 .collect()
4259 }
4260
4261 const IGNORE_RULE: &'static str = "**/target";
4262
4263 let root = temp_tree(json!({
4264 "project": {
4265 "a.txt": "a",
4266 "b.txt": "bb",
4267 "c": {
4268 "d": {
4269 "e.txt": "eee"
4270 }
4271 },
4272 "f.txt": "ffff",
4273 "target": {
4274 "build_file": "???"
4275 },
4276 ".gitignore": IGNORE_RULE
4277 },
4278
4279 }));
4280
4281 let http_client = FakeHttpClient::with_404_response();
4282 let client = cx.read(|cx| Client::new(http_client, cx));
4283 let tree = Worktree::local(
4284 client,
4285 root.path(),
4286 true,
4287 Arc::new(RealFs),
4288 Default::default(),
4289 &mut cx.to_async(),
4290 )
4291 .await
4292 .unwrap();
4293
4294 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
4295 .await;
4296
4297 const A_TXT: &'static str = "a.txt";
4298 const B_TXT: &'static str = "b.txt";
4299 const E_TXT: &'static str = "c/d/e.txt";
4300 const F_TXT: &'static str = "f.txt";
4301 const DOTGITIGNORE: &'static str = ".gitignore";
4302 const BUILD_FILE: &'static str = "target/build_file";
4303
4304 let work_dir = root.path().join("project");
4305 let mut repo = git_init(work_dir.as_path());
4306 repo.add_ignore_rule(IGNORE_RULE).unwrap();
4307 git_add(Path::new(A_TXT), &repo);
4308 git_add(Path::new(E_TXT), &repo);
4309 git_add(Path::new(DOTGITIGNORE), &repo);
4310 git_commit("Initial commit", &repo);
4311
4312 std::fs::write(work_dir.join(A_TXT), "aa").unwrap();
4313
4314 tree.flush_fs_events(cx).await;
4315
4316 // Check that the right git state is observed on startup
4317 tree.read_with(cx, |tree, _cx| {
4318 let snapshot = tree.snapshot();
4319 assert_eq!(snapshot.repository_entries.iter().count(), 1);
4320 let (dir, repo) = snapshot.repository_entries.iter().next().unwrap();
4321 assert_eq!(dir.0.as_ref(), Path::new("project"));
4322
4323 assert_eq!(repo.statuses.iter().count(), 3);
4324 assert_eq!(
4325 repo.statuses.get(&Path::new(A_TXT).into()),
4326 Some(&GitFileStatus::Modified)
4327 );
4328 assert_eq!(
4329 repo.statuses.get(&Path::new(B_TXT).into()),
4330 Some(&GitFileStatus::Added)
4331 );
4332 assert_eq!(
4333 repo.statuses.get(&Path::new(F_TXT).into()),
4334 Some(&GitFileStatus::Added)
4335 );
4336 });
4337
4338 git_add(Path::new(A_TXT), &repo);
4339 git_add(Path::new(B_TXT), &repo);
4340 git_commit("Committing modified and added", &repo);
4341 tree.flush_fs_events(cx).await;
4342
4343 // Check that repo only changes are tracked
4344 tree.read_with(cx, |tree, _cx| {
4345 let snapshot = tree.snapshot();
4346 let (_, repo) = snapshot.repository_entries.iter().next().unwrap();
4347
4348 assert_eq!(repo.statuses.iter().count(), 1);
4349 assert_eq!(
4350 repo.statuses.get(&Path::new(F_TXT).into()),
4351 Some(&GitFileStatus::Added)
4352 );
4353 });
4354
4355 git_reset(0, &repo);
4356 git_remove_index(Path::new(B_TXT), &repo);
4357 git_stash(&mut repo);
4358 std::fs::write(work_dir.join(E_TXT), "eeee").unwrap();
4359 std::fs::write(work_dir.join(BUILD_FILE), "this should be ignored").unwrap();
4360 tree.flush_fs_events(cx).await;
4361
4362 // Check that more complex repo changes are tracked
4363 tree.read_with(cx, |tree, _cx| {
4364 let snapshot = tree.snapshot();
4365 let (_, repo) = snapshot.repository_entries.iter().next().unwrap();
4366
4367 assert_eq!(repo.statuses.iter().count(), 3);
4368 assert_eq!(repo.statuses.get(&Path::new(A_TXT).into()), None);
4369 assert_eq!(
4370 repo.statuses.get(&Path::new(B_TXT).into()),
4371 Some(&GitFileStatus::Added)
4372 );
4373 assert_eq!(
4374 repo.statuses.get(&Path::new(E_TXT).into()),
4375 Some(&GitFileStatus::Modified)
4376 );
4377 assert_eq!(
4378 repo.statuses.get(&Path::new(F_TXT).into()),
4379 Some(&GitFileStatus::Added)
4380 );
4381 });
4382
4383 std::fs::remove_file(work_dir.join(B_TXT)).unwrap();
4384 std::fs::remove_dir_all(work_dir.join("c")).unwrap();
4385 std::fs::write(
4386 work_dir.join(DOTGITIGNORE),
4387 [IGNORE_RULE, "f.txt"].join("\n"),
4388 )
4389 .unwrap();
4390
4391 git_add(Path::new(DOTGITIGNORE), &repo);
4392 git_commit("Committing modified git ignore", &repo);
4393
4394 tree.flush_fs_events(cx).await;
4395
4396 // Check that non-repo behavior is tracked
4397 tree.read_with(cx, |tree, _cx| {
4398 let snapshot = tree.snapshot();
4399 let (_, repo) = snapshot.repository_entries.iter().next().unwrap();
4400
4401 assert_eq!(repo.statuses.iter().count(), 0);
4402 });
4403
4404 let mut renamed_dir_name = "first_directory/second_directory";
4405 const RENAMED_FILE: &'static str = "rf.txt";
4406
4407 std::fs::create_dir_all(work_dir.join(renamed_dir_name)).unwrap();
4408 std::fs::write(
4409 work_dir.join(renamed_dir_name).join(RENAMED_FILE),
4410 "new-contents",
4411 )
4412 .unwrap();
4413
4414 tree.flush_fs_events(cx).await;
4415
4416 tree.read_with(cx, |tree, _cx| {
4417 let snapshot = tree.snapshot();
4418 let (_, repo) = snapshot.repository_entries.iter().next().unwrap();
4419
4420 assert_eq!(repo.statuses.iter().count(), 1);
4421 assert_eq!(
4422 repo.statuses
4423 .get(&Path::new(renamed_dir_name).join(RENAMED_FILE).into()),
4424 Some(&GitFileStatus::Added)
4425 );
4426 });
4427
4428 renamed_dir_name = "new_first_directory/second_directory";
4429
4430 std::fs::rename(
4431 work_dir.join("first_directory"),
4432 work_dir.join("new_first_directory"),
4433 )
4434 .unwrap();
4435
4436 tree.flush_fs_events(cx).await;
4437
4438 tree.read_with(cx, |tree, _cx| {
4439 let snapshot = tree.snapshot();
4440 let (_, repo) = snapshot.repository_entries.iter().next().unwrap();
4441
4442 assert_eq!(repo.statuses.iter().count(), 1);
4443 assert_eq!(
4444 repo.statuses
4445 .get(&Path::new(renamed_dir_name).join(RENAMED_FILE).into()),
4446 Some(&GitFileStatus::Added)
4447 );
4448 });
4449 }
4450
4451 #[gpui::test]
4452 async fn test_write_file(cx: &mut TestAppContext) {
4453 let dir = temp_tree(json!({
4454 ".git": {},
4455 ".gitignore": "ignored-dir\n",
4456 "tracked-dir": {},
4457 "ignored-dir": {}
4458 }));
4459
4460 let client = cx.read(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
4461
4462 let tree = Worktree::local(
4463 client,
4464 dir.path(),
4465 true,
4466 Arc::new(RealFs),
4467 Default::default(),
4468 &mut cx.to_async(),
4469 )
4470 .await
4471 .unwrap();
4472 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
4473 .await;
4474 tree.flush_fs_events(cx).await;
4475
4476 tree.update(cx, |tree, cx| {
4477 tree.as_local().unwrap().write_file(
4478 Path::new("tracked-dir/file.txt"),
4479 "hello".into(),
4480 Default::default(),
4481 cx,
4482 )
4483 })
4484 .await
4485 .unwrap();
4486 tree.update(cx, |tree, cx| {
4487 tree.as_local().unwrap().write_file(
4488 Path::new("ignored-dir/file.txt"),
4489 "world".into(),
4490 Default::default(),
4491 cx,
4492 )
4493 })
4494 .await
4495 .unwrap();
4496
4497 tree.read_with(cx, |tree, _| {
4498 let tracked = tree.entry_for_path("tracked-dir/file.txt").unwrap();
4499 let ignored = tree.entry_for_path("ignored-dir/file.txt").unwrap();
4500 assert!(!tracked.is_ignored);
4501 assert!(ignored.is_ignored);
4502 });
4503 }
4504
4505 #[gpui::test(iterations = 30)]
4506 async fn test_create_directory_during_initial_scan(cx: &mut TestAppContext) {
4507 let client = cx.read(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
4508
4509 let fs = FakeFs::new(cx.background());
4510 fs.insert_tree(
4511 "/root",
4512 json!({
4513 "b": {},
4514 "c": {},
4515 "d": {},
4516 }),
4517 )
4518 .await;
4519
4520 let tree = Worktree::local(
4521 client,
4522 "/root".as_ref(),
4523 true,
4524 fs,
4525 Default::default(),
4526 &mut cx.to_async(),
4527 )
4528 .await
4529 .unwrap();
4530
4531 let mut snapshot1 = tree.update(cx, |tree, _| tree.as_local().unwrap().snapshot());
4532
4533 let entry = tree
4534 .update(cx, |tree, cx| {
4535 tree.as_local_mut()
4536 .unwrap()
4537 .create_entry("a/e".as_ref(), true, cx)
4538 })
4539 .await
4540 .unwrap();
4541 assert!(entry.is_dir());
4542
4543 cx.foreground().run_until_parked();
4544 tree.read_with(cx, |tree, _| {
4545 assert_eq!(tree.entry_for_path("a/e").unwrap().kind, EntryKind::Dir);
4546 });
4547
4548 let snapshot2 = tree.update(cx, |tree, _| tree.as_local().unwrap().snapshot());
4549 let update = snapshot2.build_update(&snapshot1, 0, 0, true);
4550 snapshot1.apply_remote_update(update).unwrap();
4551 assert_eq!(snapshot1.to_vec(true), snapshot2.to_vec(true),);
4552 }
4553
4554 #[gpui::test(iterations = 100)]
4555 async fn test_random_worktree_operations_during_initial_scan(
4556 cx: &mut TestAppContext,
4557 mut rng: StdRng,
4558 ) {
4559 let operations = env::var("OPERATIONS")
4560 .map(|o| o.parse().unwrap())
4561 .unwrap_or(5);
4562 let initial_entries = env::var("INITIAL_ENTRIES")
4563 .map(|o| o.parse().unwrap())
4564 .unwrap_or(20);
4565
4566 let root_dir = Path::new("/test");
4567 let fs = FakeFs::new(cx.background()) as Arc<dyn Fs>;
4568 fs.as_fake().insert_tree(root_dir, json!({})).await;
4569 for _ in 0..initial_entries {
4570 randomly_mutate_fs(&fs, root_dir, 1.0, &mut rng).await;
4571 }
4572 log::info!("generated initial tree");
4573
4574 let client = cx.read(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
4575 let worktree = Worktree::local(
4576 client.clone(),
4577 root_dir,
4578 true,
4579 fs.clone(),
4580 Default::default(),
4581 &mut cx.to_async(),
4582 )
4583 .await
4584 .unwrap();
4585
4586 let mut snapshot = worktree.update(cx, |tree, _| tree.as_local().unwrap().snapshot());
4587
4588 for _ in 0..operations {
4589 worktree
4590 .update(cx, |worktree, cx| {
4591 randomly_mutate_worktree(worktree, &mut rng, cx)
4592 })
4593 .await
4594 .log_err();
4595 worktree.read_with(cx, |tree, _| {
4596 tree.as_local().unwrap().snapshot.check_invariants()
4597 });
4598
4599 if rng.gen_bool(0.6) {
4600 let new_snapshot =
4601 worktree.read_with(cx, |tree, _| tree.as_local().unwrap().snapshot());
4602 let update = new_snapshot.build_update(&snapshot, 0, 0, true);
4603 snapshot.apply_remote_update(update.clone()).unwrap();
4604 assert_eq!(
4605 snapshot.to_vec(true),
4606 new_snapshot.to_vec(true),
4607 "incorrect snapshot after update {:?}",
4608 update
4609 );
4610 }
4611 }
4612
4613 worktree
4614 .update(cx, |tree, _| tree.as_local_mut().unwrap().scan_complete())
4615 .await;
4616 worktree.read_with(cx, |tree, _| {
4617 tree.as_local().unwrap().snapshot.check_invariants()
4618 });
4619
4620 let new_snapshot = worktree.read_with(cx, |tree, _| tree.as_local().unwrap().snapshot());
4621 let update = new_snapshot.build_update(&snapshot, 0, 0, true);
4622 snapshot.apply_remote_update(update.clone()).unwrap();
4623 assert_eq!(
4624 snapshot.to_vec(true),
4625 new_snapshot.to_vec(true),
4626 "incorrect snapshot after update {:?}",
4627 update
4628 );
4629 }
4630
4631 #[gpui::test(iterations = 100)]
4632 async fn test_random_worktree_changes(cx: &mut TestAppContext, mut rng: StdRng) {
4633 let operations = env::var("OPERATIONS")
4634 .map(|o| o.parse().unwrap())
4635 .unwrap_or(40);
4636 let initial_entries = env::var("INITIAL_ENTRIES")
4637 .map(|o| o.parse().unwrap())
4638 .unwrap_or(20);
4639
4640 let root_dir = Path::new("/test");
4641 let fs = FakeFs::new(cx.background()) as Arc<dyn Fs>;
4642 fs.as_fake().insert_tree(root_dir, json!({})).await;
4643 for _ in 0..initial_entries {
4644 randomly_mutate_fs(&fs, root_dir, 1.0, &mut rng).await;
4645 }
4646 log::info!("generated initial tree");
4647
4648 let client = cx.read(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
4649 let worktree = Worktree::local(
4650 client.clone(),
4651 root_dir,
4652 true,
4653 fs.clone(),
4654 Default::default(),
4655 &mut cx.to_async(),
4656 )
4657 .await
4658 .unwrap();
4659
4660 worktree
4661 .update(cx, |tree, _| tree.as_local_mut().unwrap().scan_complete())
4662 .await;
4663
4664 // After the initial scan is complete, the `UpdatedEntries` event can
4665 // be used to follow along with all changes to the worktree's snapshot.
4666 worktree.update(cx, |tree, cx| {
4667 let mut paths = tree
4668 .as_local()
4669 .unwrap()
4670 .paths()
4671 .cloned()
4672 .collect::<Vec<_>>();
4673
4674 cx.subscribe(&worktree, move |tree, _, event, _| {
4675 if let Event::UpdatedEntries(changes) = event {
4676 for ((path, _), change_type) in changes.iter() {
4677 let path = path.clone();
4678 let ix = match paths.binary_search(&path) {
4679 Ok(ix) | Err(ix) => ix,
4680 };
4681 match change_type {
4682 PathChange::Added => {
4683 assert_ne!(paths.get(ix), Some(&path));
4684 paths.insert(ix, path);
4685 }
4686
4687 PathChange::Removed => {
4688 assert_eq!(paths.get(ix), Some(&path));
4689 paths.remove(ix);
4690 }
4691
4692 PathChange::Updated => {
4693 assert_eq!(paths.get(ix), Some(&path));
4694 }
4695
4696 PathChange::AddedOrUpdated => {
4697 if paths[ix] != path {
4698 paths.insert(ix, path);
4699 }
4700 }
4701 }
4702 }
4703
4704 let new_paths = tree.paths().cloned().collect::<Vec<_>>();
4705 assert_eq!(paths, new_paths, "incorrect changes: {:?}", changes);
4706 }
4707 })
4708 .detach();
4709 });
4710
4711 fs.as_fake().pause_events();
4712 let mut snapshots = Vec::new();
4713 let mut mutations_len = operations;
4714 while mutations_len > 1 {
4715 if rng.gen_bool(0.2) {
4716 worktree
4717 .update(cx, |worktree, cx| {
4718 randomly_mutate_worktree(worktree, &mut rng, cx)
4719 })
4720 .await
4721 .log_err();
4722 } else {
4723 randomly_mutate_fs(&fs, root_dir, 1.0, &mut rng).await;
4724 }
4725
4726 let buffered_event_count = fs.as_fake().buffered_event_count();
4727 if buffered_event_count > 0 && rng.gen_bool(0.3) {
4728 let len = rng.gen_range(0..=buffered_event_count);
4729 log::info!("flushing {} events", len);
4730 fs.as_fake().flush_events(len);
4731 } else {
4732 randomly_mutate_fs(&fs, root_dir, 0.6, &mut rng).await;
4733 mutations_len -= 1;
4734 }
4735
4736 cx.foreground().run_until_parked();
4737 if rng.gen_bool(0.2) {
4738 log::info!("storing snapshot {}", snapshots.len());
4739 let snapshot =
4740 worktree.read_with(cx, |tree, _| tree.as_local().unwrap().snapshot());
4741 snapshots.push(snapshot);
4742 }
4743 }
4744
4745 log::info!("quiescing");
4746 fs.as_fake().flush_events(usize::MAX);
4747 cx.foreground().run_until_parked();
4748 let snapshot = worktree.read_with(cx, |tree, _| tree.as_local().unwrap().snapshot());
4749 snapshot.check_invariants();
4750
4751 {
4752 let new_worktree = Worktree::local(
4753 client.clone(),
4754 root_dir,
4755 true,
4756 fs.clone(),
4757 Default::default(),
4758 &mut cx.to_async(),
4759 )
4760 .await
4761 .unwrap();
4762 new_worktree
4763 .update(cx, |tree, _| tree.as_local_mut().unwrap().scan_complete())
4764 .await;
4765 let new_snapshot =
4766 new_worktree.read_with(cx, |tree, _| tree.as_local().unwrap().snapshot());
4767 assert_eq!(snapshot.to_vec(true), new_snapshot.to_vec(true));
4768 }
4769
4770 for (i, mut prev_snapshot) in snapshots.into_iter().enumerate() {
4771 let include_ignored = rng.gen::<bool>();
4772 if !include_ignored {
4773 let mut entries_by_path_edits = Vec::new();
4774 let mut entries_by_id_edits = Vec::new();
4775 for entry in prev_snapshot
4776 .entries_by_id
4777 .cursor::<()>()
4778 .filter(|e| e.is_ignored)
4779 {
4780 entries_by_path_edits.push(Edit::Remove(PathKey(entry.path.clone())));
4781 entries_by_id_edits.push(Edit::Remove(entry.id));
4782 }
4783
4784 prev_snapshot
4785 .entries_by_path
4786 .edit(entries_by_path_edits, &());
4787 prev_snapshot.entries_by_id.edit(entries_by_id_edits, &());
4788 }
4789
4790 let update = snapshot.build_update(&prev_snapshot, 0, 0, include_ignored);
4791 prev_snapshot.apply_remote_update(update.clone()).unwrap();
4792 assert_eq!(
4793 prev_snapshot.to_vec(include_ignored),
4794 snapshot.to_vec(include_ignored),
4795 "wrong update for snapshot {i}. update: {:?}",
4796 update
4797 );
4798 }
4799 }
4800
4801 fn randomly_mutate_worktree(
4802 worktree: &mut Worktree,
4803 rng: &mut impl Rng,
4804 cx: &mut ModelContext<Worktree>,
4805 ) -> Task<Result<()>> {
4806 log::info!("mutating worktree");
4807 let worktree = worktree.as_local_mut().unwrap();
4808 let snapshot = worktree.snapshot();
4809 let entry = snapshot.entries(false).choose(rng).unwrap();
4810
4811 match rng.gen_range(0_u32..100) {
4812 0..=33 if entry.path.as_ref() != Path::new("") => {
4813 log::info!("deleting entry {:?} ({})", entry.path, entry.id.0);
4814 worktree.delete_entry(entry.id, cx).unwrap()
4815 }
4816 ..=66 if entry.path.as_ref() != Path::new("") => {
4817 let other_entry = snapshot.entries(false).choose(rng).unwrap();
4818 let new_parent_path = if other_entry.is_dir() {
4819 other_entry.path.clone()
4820 } else {
4821 other_entry.path.parent().unwrap().into()
4822 };
4823 let mut new_path = new_parent_path.join(gen_name(rng));
4824 if new_path.starts_with(&entry.path) {
4825 new_path = gen_name(rng).into();
4826 }
4827
4828 log::info!(
4829 "renaming entry {:?} ({}) to {:?}",
4830 entry.path,
4831 entry.id.0,
4832 new_path
4833 );
4834 let task = worktree.rename_entry(entry.id, new_path, cx).unwrap();
4835 cx.foreground().spawn(async move {
4836 task.await?;
4837 Ok(())
4838 })
4839 }
4840 _ => {
4841 let task = if entry.is_dir() {
4842 let child_path = entry.path.join(gen_name(rng));
4843 let is_dir = rng.gen_bool(0.3);
4844 log::info!(
4845 "creating {} at {:?}",
4846 if is_dir { "dir" } else { "file" },
4847 child_path,
4848 );
4849 worktree.create_entry(child_path, is_dir, cx)
4850 } else {
4851 log::info!("overwriting file {:?} ({})", entry.path, entry.id.0);
4852 worktree.write_file(entry.path.clone(), "".into(), Default::default(), cx)
4853 };
4854 cx.foreground().spawn(async move {
4855 task.await?;
4856 Ok(())
4857 })
4858 }
4859 }
4860 }
4861
4862 async fn randomly_mutate_fs(
4863 fs: &Arc<dyn Fs>,
4864 root_path: &Path,
4865 insertion_probability: f64,
4866 rng: &mut impl Rng,
4867 ) {
4868 log::info!("mutating fs");
4869 let mut files = Vec::new();
4870 let mut dirs = Vec::new();
4871 for path in fs.as_fake().paths() {
4872 if path.starts_with(root_path) {
4873 if fs.is_file(&path).await {
4874 files.push(path);
4875 } else {
4876 dirs.push(path);
4877 }
4878 }
4879 }
4880
4881 if (files.is_empty() && dirs.len() == 1) || rng.gen_bool(insertion_probability) {
4882 let path = dirs.choose(rng).unwrap();
4883 let new_path = path.join(gen_name(rng));
4884
4885 if rng.gen() {
4886 log::info!(
4887 "creating dir {:?}",
4888 new_path.strip_prefix(root_path).unwrap()
4889 );
4890 fs.create_dir(&new_path).await.unwrap();
4891 } else {
4892 log::info!(
4893 "creating file {:?}",
4894 new_path.strip_prefix(root_path).unwrap()
4895 );
4896 fs.create_file(&new_path, Default::default()).await.unwrap();
4897 }
4898 } else if rng.gen_bool(0.05) {
4899 let ignore_dir_path = dirs.choose(rng).unwrap();
4900 let ignore_path = ignore_dir_path.join(&*GITIGNORE);
4901
4902 let subdirs = dirs
4903 .iter()
4904 .filter(|d| d.starts_with(&ignore_dir_path))
4905 .cloned()
4906 .collect::<Vec<_>>();
4907 let subfiles = files
4908 .iter()
4909 .filter(|d| d.starts_with(&ignore_dir_path))
4910 .cloned()
4911 .collect::<Vec<_>>();
4912 let files_to_ignore = {
4913 let len = rng.gen_range(0..=subfiles.len());
4914 subfiles.choose_multiple(rng, len)
4915 };
4916 let dirs_to_ignore = {
4917 let len = rng.gen_range(0..subdirs.len());
4918 subdirs.choose_multiple(rng, len)
4919 };
4920
4921 let mut ignore_contents = String::new();
4922 for path_to_ignore in files_to_ignore.chain(dirs_to_ignore) {
4923 writeln!(
4924 ignore_contents,
4925 "{}",
4926 path_to_ignore
4927 .strip_prefix(&ignore_dir_path)
4928 .unwrap()
4929 .to_str()
4930 .unwrap()
4931 )
4932 .unwrap();
4933 }
4934 log::info!(
4935 "creating gitignore {:?} with contents:\n{}",
4936 ignore_path.strip_prefix(&root_path).unwrap(),
4937 ignore_contents
4938 );
4939 fs.save(
4940 &ignore_path,
4941 &ignore_contents.as_str().into(),
4942 Default::default(),
4943 )
4944 .await
4945 .unwrap();
4946 } else {
4947 let old_path = {
4948 let file_path = files.choose(rng);
4949 let dir_path = dirs[1..].choose(rng);
4950 file_path.into_iter().chain(dir_path).choose(rng).unwrap()
4951 };
4952
4953 let is_rename = rng.gen();
4954 if is_rename {
4955 let new_path_parent = dirs
4956 .iter()
4957 .filter(|d| !d.starts_with(old_path))
4958 .choose(rng)
4959 .unwrap();
4960
4961 let overwrite_existing_dir =
4962 !old_path.starts_with(&new_path_parent) && rng.gen_bool(0.3);
4963 let new_path = if overwrite_existing_dir {
4964 fs.remove_dir(
4965 &new_path_parent,
4966 RemoveOptions {
4967 recursive: true,
4968 ignore_if_not_exists: true,
4969 },
4970 )
4971 .await
4972 .unwrap();
4973 new_path_parent.to_path_buf()
4974 } else {
4975 new_path_parent.join(gen_name(rng))
4976 };
4977
4978 log::info!(
4979 "renaming {:?} to {}{:?}",
4980 old_path.strip_prefix(&root_path).unwrap(),
4981 if overwrite_existing_dir {
4982 "overwrite "
4983 } else {
4984 ""
4985 },
4986 new_path.strip_prefix(&root_path).unwrap()
4987 );
4988 fs.rename(
4989 &old_path,
4990 &new_path,
4991 fs::RenameOptions {
4992 overwrite: true,
4993 ignore_if_exists: true,
4994 },
4995 )
4996 .await
4997 .unwrap();
4998 } else if fs.is_file(&old_path).await {
4999 log::info!(
5000 "deleting file {:?}",
5001 old_path.strip_prefix(&root_path).unwrap()
5002 );
5003 fs.remove_file(old_path, Default::default()).await.unwrap();
5004 } else {
5005 log::info!(
5006 "deleting dir {:?}",
5007 old_path.strip_prefix(&root_path).unwrap()
5008 );
5009 fs.remove_dir(
5010 &old_path,
5011 RemoveOptions {
5012 recursive: true,
5013 ignore_if_not_exists: true,
5014 },
5015 )
5016 .await
5017 .unwrap();
5018 }
5019 }
5020 }
5021
5022 fn gen_name(rng: &mut impl Rng) -> String {
5023 (0..6)
5024 .map(|_| rng.sample(rand::distributions::Alphanumeric))
5025 .map(char::from)
5026 .collect()
5027 }
5028
5029 impl LocalSnapshot {
5030 fn check_invariants(&self) {
5031 assert_eq!(
5032 self.entries_by_path
5033 .cursor::<()>()
5034 .map(|e| (&e.path, e.id))
5035 .collect::<Vec<_>>(),
5036 self.entries_by_id
5037 .cursor::<()>()
5038 .map(|e| (&e.path, e.id))
5039 .collect::<collections::BTreeSet<_>>()
5040 .into_iter()
5041 .collect::<Vec<_>>(),
5042 "entries_by_path and entries_by_id are inconsistent"
5043 );
5044
5045 let mut files = self.files(true, 0);
5046 let mut visible_files = self.files(false, 0);
5047 for entry in self.entries_by_path.cursor::<()>() {
5048 if entry.is_file() {
5049 assert_eq!(files.next().unwrap().inode, entry.inode);
5050 if !entry.is_ignored {
5051 assert_eq!(visible_files.next().unwrap().inode, entry.inode);
5052 }
5053 }
5054 }
5055
5056 assert!(files.next().is_none());
5057 assert!(visible_files.next().is_none());
5058
5059 let mut bfs_paths = Vec::new();
5060 let mut stack = vec![Path::new("")];
5061 while let Some(path) = stack.pop() {
5062 bfs_paths.push(path);
5063 let ix = stack.len();
5064 for child_entry in self.child_entries(path) {
5065 stack.insert(ix, &child_entry.path);
5066 }
5067 }
5068
5069 let dfs_paths_via_iter = self
5070 .entries_by_path
5071 .cursor::<()>()
5072 .map(|e| e.path.as_ref())
5073 .collect::<Vec<_>>();
5074 assert_eq!(bfs_paths, dfs_paths_via_iter);
5075
5076 let dfs_paths_via_traversal = self
5077 .entries(true)
5078 .map(|e| e.path.as_ref())
5079 .collect::<Vec<_>>();
5080 assert_eq!(dfs_paths_via_traversal, dfs_paths_via_iter);
5081
5082 for ignore_parent_abs_path in self.ignores_by_parent_abs_path.keys() {
5083 let ignore_parent_path =
5084 ignore_parent_abs_path.strip_prefix(&self.abs_path).unwrap();
5085 assert!(self.entry_for_path(&ignore_parent_path).is_some());
5086 assert!(self
5087 .entry_for_path(ignore_parent_path.join(&*GITIGNORE))
5088 .is_some());
5089 }
5090 }
5091
5092 fn to_vec(&self, include_ignored: bool) -> Vec<(&Path, u64, bool)> {
5093 let mut paths = Vec::new();
5094 for entry in self.entries_by_path.cursor::<()>() {
5095 if include_ignored || !entry.is_ignored {
5096 paths.push((entry.path.as_ref(), entry.inode, entry.is_ignored));
5097 }
5098 }
5099 paths.sort_by(|a, b| a.0.cmp(b.0));
5100 paths
5101 }
5102 }
5103}