fake_git_repo.rs

  1use crate::{FakeFs, FakeFsEntry, Fs};
  2use anyhow::{Context as _, Result, bail};
  3use collections::{HashMap, HashSet};
  4use futures::future::{self, BoxFuture, join_all};
  5use git::{
  6    Oid,
  7    blame::Blame,
  8    repository::{
  9        AskPassDelegate, Branch, CommitDetails, CommitOptions, FetchOptions, GitRepository,
 10        GitRepositoryCheckpoint, PushOptions, Remote, RepoPath, ResetMode, Worktree,
 11    },
 12    status::{
 13        DiffTreeType, FileStatus, GitStatus, StatusCode, TrackedStatus, TreeDiff, TreeDiffStatus,
 14        UnmergedStatus,
 15    },
 16};
 17use gpui::{AsyncApp, BackgroundExecutor, SharedString, Task, TaskLabel};
 18use ignore::gitignore::GitignoreBuilder;
 19use parking_lot::Mutex;
 20use rope::Rope;
 21use smol::future::FutureExt as _;
 22use std::{
 23    path::PathBuf,
 24    sync::{Arc, LazyLock},
 25};
 26use util::{paths::PathStyle, rel_path::RelPath};
 27
 28pub static LOAD_INDEX_TEXT_TASK: LazyLock<TaskLabel> = LazyLock::new(TaskLabel::new);
 29pub static LOAD_HEAD_TEXT_TASK: LazyLock<TaskLabel> = LazyLock::new(TaskLabel::new);
 30
 31#[derive(Clone)]
 32pub struct FakeGitRepository {
 33    pub(crate) fs: Arc<FakeFs>,
 34    pub(crate) checkpoints: Arc<Mutex<HashMap<Oid, FakeFsEntry>>>,
 35    pub(crate) executor: BackgroundExecutor,
 36    pub(crate) dot_git_path: PathBuf,
 37    pub(crate) repository_dir_path: PathBuf,
 38    pub(crate) common_dir_path: PathBuf,
 39}
 40
 41#[derive(Debug, Clone)]
 42pub struct FakeGitRepositoryState {
 43    pub event_emitter: smol::channel::Sender<PathBuf>,
 44    pub unmerged_paths: HashMap<RepoPath, UnmergedStatus>,
 45    pub head_contents: HashMap<RepoPath, String>,
 46    pub index_contents: HashMap<RepoPath, String>,
 47    // everything in commit contents is in oids
 48    pub merge_base_contents: HashMap<RepoPath, Oid>,
 49    pub oids: HashMap<Oid, String>,
 50    pub blames: HashMap<RepoPath, Blame>,
 51    pub current_branch_name: Option<String>,
 52    pub branches: HashSet<String>,
 53    pub simulated_index_write_error_message: Option<String>,
 54    pub refs: HashMap<String, String>,
 55}
 56
 57impl FakeGitRepositoryState {
 58    pub fn new(event_emitter: smol::channel::Sender<PathBuf>) -> Self {
 59        FakeGitRepositoryState {
 60            event_emitter,
 61            head_contents: Default::default(),
 62            index_contents: Default::default(),
 63            unmerged_paths: Default::default(),
 64            blames: Default::default(),
 65            current_branch_name: Default::default(),
 66            branches: Default::default(),
 67            simulated_index_write_error_message: Default::default(),
 68            refs: HashMap::from_iter([("HEAD".into(), "abc".into())]),
 69            merge_base_contents: Default::default(),
 70            oids: Default::default(),
 71        }
 72    }
 73}
 74
 75impl FakeGitRepository {
 76    fn with_state_async<F, T>(&self, write: bool, f: F) -> BoxFuture<'static, Result<T>>
 77    where
 78        F: 'static + Send + FnOnce(&mut FakeGitRepositoryState) -> Result<T>,
 79        T: Send,
 80    {
 81        let fs = self.fs.clone();
 82        let executor = self.executor.clone();
 83        let dot_git_path = self.dot_git_path.clone();
 84        async move {
 85            executor.simulate_random_delay().await;
 86            fs.with_git_state(&dot_git_path, write, f)?
 87        }
 88        .boxed()
 89    }
 90}
 91
 92impl GitRepository for FakeGitRepository {
 93    fn reload_index(&self) {}
 94
 95    fn load_index_text(&self, path: RepoPath) -> BoxFuture<'_, Option<String>> {
 96        let fut = self.with_state_async(false, move |state| {
 97            state
 98                .index_contents
 99                .get(&path)
100                .context("not present in index")
101                .cloned()
102        });
103        self.executor
104            .spawn_labeled(*LOAD_INDEX_TEXT_TASK, async move { fut.await.ok() })
105            .boxed()
106    }
107
108    fn load_committed_text(&self, path: RepoPath) -> BoxFuture<'_, Option<String>> {
109        let fut = self.with_state_async(false, move |state| {
110            state
111                .head_contents
112                .get(&path)
113                .context("not present in HEAD")
114                .cloned()
115        });
116        self.executor
117            .spawn_labeled(*LOAD_HEAD_TEXT_TASK, async move { fut.await.ok() })
118            .boxed()
119    }
120
121    fn load_blob_content(&self, oid: git::Oid) -> BoxFuture<'_, Result<String>> {
122        self.with_state_async(false, move |state| {
123            state.oids.get(&oid).cloned().context("oid does not exist")
124        })
125        .boxed()
126    }
127
128    fn load_commit(
129        &self,
130        _commit: String,
131        _cx: AsyncApp,
132    ) -> BoxFuture<'_, Result<git::repository::CommitDiff>> {
133        unimplemented!()
134    }
135
136    fn set_index_text(
137        &self,
138        path: RepoPath,
139        content: Option<String>,
140        _env: Arc<HashMap<String, String>>,
141    ) -> BoxFuture<'_, anyhow::Result<()>> {
142        self.with_state_async(true, move |state| {
143            if let Some(message) = &state.simulated_index_write_error_message {
144                anyhow::bail!("{message}");
145            } else if let Some(content) = content {
146                state.index_contents.insert(path, content);
147            } else {
148                state.index_contents.remove(&path);
149            }
150            Ok(())
151        })
152    }
153
154    fn remote_url(&self, _name: &str) -> Option<String> {
155        None
156    }
157
158    fn diff_tree(&self, _request: DiffTreeType) -> BoxFuture<'_, Result<TreeDiff>> {
159        let mut entries = HashMap::default();
160        self.with_state_async(false, |state| {
161            for (path, content) in &state.head_contents {
162                let status = if let Some((oid, original)) = state
163                    .merge_base_contents
164                    .get(path)
165                    .map(|oid| (oid, &state.oids[oid]))
166                {
167                    if original == content {
168                        continue;
169                    }
170                    TreeDiffStatus::Modified { old: *oid }
171                } else {
172                    TreeDiffStatus::Added
173                };
174                entries.insert(path.clone(), status);
175            }
176            for (path, oid) in &state.merge_base_contents {
177                if !entries.contains_key(path) {
178                    entries.insert(path.clone(), TreeDiffStatus::Deleted { old: *oid });
179                }
180            }
181            Ok(TreeDiff { entries })
182        })
183        .boxed()
184    }
185
186    fn revparse_batch(&self, revs: Vec<String>) -> BoxFuture<'_, Result<Vec<Option<String>>>> {
187        self.with_state_async(false, |state| {
188            Ok(revs
189                .into_iter()
190                .map(|rev| state.refs.get(&rev).cloned())
191                .collect())
192        })
193    }
194
195    fn show(&self, commit: String) -> BoxFuture<'_, Result<CommitDetails>> {
196        async {
197            Ok(CommitDetails {
198                sha: commit.into(),
199                ..Default::default()
200            })
201        }
202        .boxed()
203    }
204
205    fn reset(
206        &self,
207        _commit: String,
208        _mode: ResetMode,
209        _env: Arc<HashMap<String, String>>,
210    ) -> BoxFuture<'_, Result<()>> {
211        unimplemented!()
212    }
213
214    fn checkout_files(
215        &self,
216        _commit: String,
217        _paths: Vec<RepoPath>,
218        _env: Arc<HashMap<String, String>>,
219    ) -> BoxFuture<'_, Result<()>> {
220        unimplemented!()
221    }
222
223    fn path(&self) -> PathBuf {
224        self.repository_dir_path.clone()
225    }
226
227    fn main_repository_path(&self) -> PathBuf {
228        self.common_dir_path.clone()
229    }
230
231    fn merge_message(&self) -> BoxFuture<'_, Option<String>> {
232        async move { None }.boxed()
233    }
234
235    fn status(&self, path_prefixes: &[RepoPath]) -> Task<Result<GitStatus>> {
236        let workdir_path = self.dot_git_path.parent().unwrap();
237
238        // Load gitignores
239        let ignores = workdir_path
240            .ancestors()
241            .filter_map(|dir| {
242                let ignore_path = dir.join(".gitignore");
243                let content = self.fs.read_file_sync(ignore_path).ok()?;
244                let content = String::from_utf8(content).ok()?;
245                let mut builder = GitignoreBuilder::new(dir);
246                for line in content.lines() {
247                    builder.add_line(Some(dir.into()), line).ok()?;
248                }
249                builder.build().ok()
250            })
251            .collect::<Vec<_>>();
252
253        // Load working copy files.
254        let git_files: HashMap<RepoPath, (String, bool)> = self
255            .fs
256            .files()
257            .iter()
258            .filter_map(|path| {
259                // TODO better simulate git status output in the case of submodules and worktrees
260                let repo_path = path.strip_prefix(workdir_path).ok()?;
261                let mut is_ignored = repo_path.starts_with(".git");
262                for ignore in &ignores {
263                    match ignore.matched_path_or_any_parents(path, false) {
264                        ignore::Match::None => {}
265                        ignore::Match::Ignore(_) => is_ignored = true,
266                        ignore::Match::Whitelist(_) => break,
267                    }
268                }
269                let content = self
270                    .fs
271                    .read_file_sync(path)
272                    .ok()
273                    .map(|content| String::from_utf8(content).unwrap())?;
274                let repo_path = RelPath::new(repo_path, PathStyle::local()).ok()?;
275                Some((repo_path.into(), (content, is_ignored)))
276            })
277            .collect();
278
279        let result = self.fs.with_git_state(&self.dot_git_path, false, |state| {
280            let mut entries = Vec::new();
281            let paths = state
282                .head_contents
283                .keys()
284                .chain(state.index_contents.keys())
285                .chain(git_files.keys())
286                .collect::<HashSet<_>>();
287            for path in paths {
288                if !path_prefixes.iter().any(|prefix| path.starts_with(prefix)) {
289                    continue;
290                }
291
292                let head = state.head_contents.get(path);
293                let index = state.index_contents.get(path);
294                let unmerged = state.unmerged_paths.get(path);
295                let fs = git_files.get(path);
296                let status = match (unmerged, head, index, fs) {
297                    (Some(unmerged), _, _, _) => FileStatus::Unmerged(*unmerged),
298                    (_, Some(head), Some(index), Some((fs, _))) => {
299                        FileStatus::Tracked(TrackedStatus {
300                            index_status: if head == index {
301                                StatusCode::Unmodified
302                            } else {
303                                StatusCode::Modified
304                            },
305                            worktree_status: if fs == index {
306                                StatusCode::Unmodified
307                            } else {
308                                StatusCode::Modified
309                            },
310                        })
311                    }
312                    (_, Some(head), Some(index), None) => FileStatus::Tracked(TrackedStatus {
313                        index_status: if head == index {
314                            StatusCode::Unmodified
315                        } else {
316                            StatusCode::Modified
317                        },
318                        worktree_status: StatusCode::Deleted,
319                    }),
320                    (_, Some(_), None, Some(_)) => FileStatus::Tracked(TrackedStatus {
321                        index_status: StatusCode::Deleted,
322                        worktree_status: StatusCode::Added,
323                    }),
324                    (_, Some(_), None, None) => FileStatus::Tracked(TrackedStatus {
325                        index_status: StatusCode::Deleted,
326                        worktree_status: StatusCode::Deleted,
327                    }),
328                    (_, None, Some(index), Some((fs, _))) => FileStatus::Tracked(TrackedStatus {
329                        index_status: StatusCode::Added,
330                        worktree_status: if fs == index {
331                            StatusCode::Unmodified
332                        } else {
333                            StatusCode::Modified
334                        },
335                    }),
336                    (_, None, Some(_), None) => FileStatus::Tracked(TrackedStatus {
337                        index_status: StatusCode::Added,
338                        worktree_status: StatusCode::Deleted,
339                    }),
340                    (_, None, None, Some((_, is_ignored))) => {
341                        if *is_ignored {
342                            continue;
343                        }
344                        FileStatus::Untracked
345                    }
346                    (_, None, None, None) => {
347                        unreachable!();
348                    }
349                };
350                if status
351                    != FileStatus::Tracked(TrackedStatus {
352                        index_status: StatusCode::Unmodified,
353                        worktree_status: StatusCode::Unmodified,
354                    })
355                {
356                    entries.push((path.clone(), status));
357                }
358            }
359            entries.sort_by(|a, b| a.0.cmp(&b.0));
360            anyhow::Ok(GitStatus {
361                entries: entries.into(),
362            })
363        });
364        Task::ready(match result {
365            Ok(result) => result,
366            Err(e) => Err(e),
367        })
368    }
369
370    fn stash_entries(&self) -> BoxFuture<'_, Result<git::stash::GitStash>> {
371        async { Ok(git::stash::GitStash::default()) }.boxed()
372    }
373
374    fn branches(&self) -> BoxFuture<'_, Result<Vec<Branch>>> {
375        self.with_state_async(false, move |state| {
376            let current_branch = &state.current_branch_name;
377            Ok(state
378                .branches
379                .iter()
380                .map(|branch_name| Branch {
381                    is_head: Some(branch_name) == current_branch.as_ref(),
382                    ref_name: branch_name.into(),
383                    most_recent_commit: None,
384                    upstream: None,
385                })
386                .collect())
387        })
388    }
389
390    fn worktrees(&self) -> BoxFuture<'_, Result<Vec<Worktree>>> {
391        unimplemented!()
392    }
393
394    fn create_worktree(
395        &self,
396        _: String,
397        _: PathBuf,
398        _: Option<String>,
399    ) -> BoxFuture<'_, Result<()>> {
400        unimplemented!()
401    }
402
403    fn change_branch(&self, name: String) -> BoxFuture<'_, Result<()>> {
404        self.with_state_async(true, |state| {
405            state.current_branch_name = Some(name);
406            Ok(())
407        })
408    }
409
410    fn create_branch(&self, name: String) -> BoxFuture<'_, Result<()>> {
411        self.with_state_async(true, move |state| {
412            state.branches.insert(name);
413            Ok(())
414        })
415    }
416
417    fn rename_branch(&self, branch: String, new_name: String) -> BoxFuture<'_, Result<()>> {
418        self.with_state_async(true, move |state| {
419            if !state.branches.remove(&branch) {
420                bail!("no such branch: {branch}");
421            }
422            state.branches.insert(new_name.clone());
423            if state.current_branch_name == Some(branch) {
424                state.current_branch_name = Some(new_name);
425            }
426            Ok(())
427        })
428    }
429
430    fn blame(&self, path: RepoPath, _content: Rope) -> BoxFuture<'_, Result<git::blame::Blame>> {
431        self.with_state_async(false, move |state| {
432            state
433                .blames
434                .get(&path)
435                .with_context(|| format!("failed to get blame for {:?}", path.0))
436                .cloned()
437        })
438    }
439
440    fn stage_paths(
441        &self,
442        paths: Vec<RepoPath>,
443        _env: Arc<HashMap<String, String>>,
444    ) -> BoxFuture<'_, Result<()>> {
445        Box::pin(async move {
446            let contents = paths
447                .into_iter()
448                .map(|path| {
449                    let abs_path = self
450                        .dot_git_path
451                        .parent()
452                        .unwrap()
453                        .join(&path.as_std_path());
454                    Box::pin(async move { (path.clone(), self.fs.load(&abs_path).await.ok()) })
455                })
456                .collect::<Vec<_>>();
457            let contents = join_all(contents).await;
458            self.with_state_async(true, move |state| {
459                for (path, content) in contents {
460                    if let Some(content) = content {
461                        state.index_contents.insert(path, content);
462                    } else {
463                        state.index_contents.remove(&path);
464                    }
465                }
466                Ok(())
467            })
468            .await
469        })
470    }
471
472    fn unstage_paths(
473        &self,
474        paths: Vec<RepoPath>,
475        _env: Arc<HashMap<String, String>>,
476    ) -> BoxFuture<'_, Result<()>> {
477        self.with_state_async(true, move |state| {
478            for path in paths {
479                match state.head_contents.get(&path) {
480                    Some(content) => state.index_contents.insert(path, content.clone()),
481                    None => state.index_contents.remove(&path),
482                };
483            }
484            Ok(())
485        })
486    }
487
488    fn stash_paths(
489        &self,
490        _paths: Vec<RepoPath>,
491        _env: Arc<HashMap<String, String>>,
492    ) -> BoxFuture<'_, Result<()>> {
493        unimplemented!()
494    }
495
496    fn stash_pop(
497        &self,
498        _index: Option<usize>,
499        _env: Arc<HashMap<String, String>>,
500    ) -> BoxFuture<'_, Result<()>> {
501        unimplemented!()
502    }
503
504    fn stash_apply(
505        &self,
506        _index: Option<usize>,
507        _env: Arc<HashMap<String, String>>,
508    ) -> BoxFuture<'_, Result<()>> {
509        unimplemented!()
510    }
511
512    fn stash_drop(
513        &self,
514        _index: Option<usize>,
515        _env: Arc<HashMap<String, String>>,
516    ) -> BoxFuture<'_, Result<()>> {
517        unimplemented!()
518    }
519
520    fn commit(
521        &self,
522        _message: gpui::SharedString,
523        _name_and_email: Option<(gpui::SharedString, gpui::SharedString)>,
524        _options: CommitOptions,
525        _env: Arc<HashMap<String, String>>,
526    ) -> BoxFuture<'_, Result<()>> {
527        unimplemented!()
528    }
529
530    fn push(
531        &self,
532        _branch: String,
533        _remote: String,
534        _options: Option<PushOptions>,
535        _askpass: AskPassDelegate,
536        _env: Arc<HashMap<String, String>>,
537        _cx: AsyncApp,
538    ) -> BoxFuture<'_, Result<git::repository::RemoteCommandOutput>> {
539        unimplemented!()
540    }
541
542    fn pull(
543        &self,
544        _branch: String,
545        _remote: String,
546        _askpass: AskPassDelegate,
547        _env: Arc<HashMap<String, String>>,
548        _cx: AsyncApp,
549    ) -> BoxFuture<'_, Result<git::repository::RemoteCommandOutput>> {
550        unimplemented!()
551    }
552
553    fn fetch(
554        &self,
555        _fetch_options: FetchOptions,
556        _askpass: AskPassDelegate,
557        _env: Arc<HashMap<String, String>>,
558        _cx: AsyncApp,
559    ) -> BoxFuture<'_, Result<git::repository::RemoteCommandOutput>> {
560        unimplemented!()
561    }
562
563    fn get_remotes(&self, _branch: Option<String>) -> BoxFuture<'_, Result<Vec<Remote>>> {
564        unimplemented!()
565    }
566
567    fn check_for_pushed_commit(&self) -> BoxFuture<'_, Result<Vec<gpui::SharedString>>> {
568        future::ready(Ok(Vec::new())).boxed()
569    }
570
571    fn diff(&self, _diff: git::repository::DiffType) -> BoxFuture<'_, Result<String>> {
572        unimplemented!()
573    }
574
575    fn checkpoint(&self) -> BoxFuture<'static, Result<GitRepositoryCheckpoint>> {
576        let executor = self.executor.clone();
577        let fs = self.fs.clone();
578        let checkpoints = self.checkpoints.clone();
579        let repository_dir_path = self.repository_dir_path.parent().unwrap().to_path_buf();
580        async move {
581            executor.simulate_random_delay().await;
582            let oid = git::Oid::random(&mut executor.rng());
583            let entry = fs.entry(&repository_dir_path)?;
584            checkpoints.lock().insert(oid, entry);
585            Ok(GitRepositoryCheckpoint { commit_sha: oid })
586        }
587        .boxed()
588    }
589
590    fn restore_checkpoint(&self, checkpoint: GitRepositoryCheckpoint) -> BoxFuture<'_, Result<()>> {
591        let executor = self.executor.clone();
592        let fs = self.fs.clone();
593        let checkpoints = self.checkpoints.clone();
594        let repository_dir_path = self.repository_dir_path.parent().unwrap().to_path_buf();
595        async move {
596            executor.simulate_random_delay().await;
597            let checkpoints = checkpoints.lock();
598            let entry = checkpoints
599                .get(&checkpoint.commit_sha)
600                .context(format!("invalid checkpoint: {}", checkpoint.commit_sha))?;
601            fs.insert_entry(&repository_dir_path, entry.clone())?;
602            Ok(())
603        }
604        .boxed()
605    }
606
607    fn compare_checkpoints(
608        &self,
609        left: GitRepositoryCheckpoint,
610        right: GitRepositoryCheckpoint,
611    ) -> BoxFuture<'_, Result<bool>> {
612        let executor = self.executor.clone();
613        let checkpoints = self.checkpoints.clone();
614        async move {
615            executor.simulate_random_delay().await;
616            let checkpoints = checkpoints.lock();
617            let left = checkpoints
618                .get(&left.commit_sha)
619                .context(format!("invalid left checkpoint: {}", left.commit_sha))?;
620            let right = checkpoints
621                .get(&right.commit_sha)
622                .context(format!("invalid right checkpoint: {}", right.commit_sha))?;
623
624            Ok(left == right)
625        }
626        .boxed()
627    }
628
629    fn diff_checkpoints(
630        &self,
631        _base_checkpoint: GitRepositoryCheckpoint,
632        _target_checkpoint: GitRepositoryCheckpoint,
633    ) -> BoxFuture<'_, Result<String>> {
634        unimplemented!()
635    }
636
637    fn default_branch(&self) -> BoxFuture<'_, Result<Option<SharedString>>> {
638        async { Ok(Some("main".into())) }.boxed()
639    }
640}
641
642#[cfg(test)]
643mod tests {
644    use crate::{FakeFs, Fs};
645    use gpui::BackgroundExecutor;
646    use serde_json::json;
647    use std::path::Path;
648    use util::path;
649
650    #[gpui::test]
651    async fn test_checkpoints(executor: BackgroundExecutor) {
652        let fs = FakeFs::new(executor);
653        fs.insert_tree(
654            path!("/"),
655            json!({
656                "bar": {
657                    "baz": "qux"
658                },
659                "foo": {
660                    ".git": {},
661                    "a": "lorem",
662                    "b": "ipsum",
663                },
664            }),
665        )
666        .await;
667        fs.with_git_state(Path::new("/foo/.git"), true, |_git| {})
668            .unwrap();
669        let repository = fs
670            .open_repo(Path::new("/foo/.git"), Some("git".as_ref()))
671            .unwrap();
672
673        let checkpoint_1 = repository.checkpoint().await.unwrap();
674        fs.write(Path::new("/foo/b"), b"IPSUM").await.unwrap();
675        fs.write(Path::new("/foo/c"), b"dolor").await.unwrap();
676        let checkpoint_2 = repository.checkpoint().await.unwrap();
677        let checkpoint_3 = repository.checkpoint().await.unwrap();
678
679        assert!(
680            repository
681                .compare_checkpoints(checkpoint_2.clone(), checkpoint_3.clone())
682                .await
683                .unwrap()
684        );
685        assert!(
686            !repository
687                .compare_checkpoints(checkpoint_1.clone(), checkpoint_2.clone())
688                .await
689                .unwrap()
690        );
691
692        repository.restore_checkpoint(checkpoint_1).await.unwrap();
693        assert_eq!(
694            fs.files_with_contents(Path::new("")),
695            [
696                (Path::new(path!("/bar/baz")).into(), b"qux".into()),
697                (Path::new(path!("/foo/a")).into(), b"lorem".into()),
698                (Path::new(path!("/foo/b")).into(), b"ipsum".into())
699            ]
700        );
701    }
702}