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