From cf8e2b059f94739c6f93369f73334b5227e349e1 Mon Sep 17 00:00:00 2001 From: DanConwayDev Date: Wed, 31 Jul 2024 13:38:07 +0100 Subject: test(remote): add `recreate_as_bare` helper as gitlib2 cannot push to a non bare git repo in a directory --- test_utils/src/git.rs | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) (limited to 'test_utils/src') diff --git a/test_utils/src/git.rs b/test_utils/src/git.rs index 5e8aed5..c7047cf 100644 --- a/test_utils/src/git.rs +++ b/test_utils/src/git.rs @@ -58,6 +58,49 @@ impl GitTestRepo { Self::new("main").unwrap() } + fn clone(existing_repo: &GitTestRepo) -> Result { + let path = current_dir()?.join(format!("tmpgit-{}", rand::random::())); + let git_repo = git2::Repository::clone(existing_repo.dir.to_str().unwrap(), path.clone())?; + Ok(Self { + dir: path, + git_repo, + }) + } + + pub fn recreate_as_bare(existing_repo: &GitTestRepo) -> Result { + // create bare repo + let path = current_dir()?.join(format!("tmpgit-{}", rand::random::())); + let git_repo = git2::Repository::init_opts( + &path, + RepositoryInitOptions::new() + .initial_head("main") + .bare(true) + .mkpath(true), + )?; + // clone existing to a temp repo + let tmp_repo = Self::clone(existing_repo)?; + // add bare as a remote and push branches + let mut remote = tmp_repo.git_repo.remote("tmp", path.to_str().unwrap())?; + let refspecs = tmp_repo + .git_repo + .branches(Some(git2::BranchType::Local))? + .filter_map(|b| b.ok()) + .map(|(b, _)| { + format!( + "refs/heads/{}:refs/heads/{}", + b.name().unwrap().unwrap(), + b.name().unwrap().unwrap(), + ) + }) + .collect::>(); + remote.push(&refspecs, None)?; + // TODO: push tags + Ok(Self { + dir: path, + git_repo, + }) + } + pub fn initial_commit(&self) -> Result { let oid = self.git_repo.index()?.write_tree()?; let tree = self.git_repo.find_tree(oid)?; -- cgit v1.2.3