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