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