WIP: tests: add more tests to git crate
All checks were successful
ci/woodpecker/push/push-next Pipeline was successful
ci/woodpecker/push/cron-docker-builder Pipeline was successful
ci/woodpecker/push/tag-created Pipeline was successful

This commit is contained in:
Paul Campbell 2024-06-09 10:21:09 +01:00
parent 926851db19
commit ca4900209b
14 changed files with 454 additions and 161 deletions

View file

@ -1,5 +1,7 @@
use derive_more::Display;
/// The name of a Branch /// The name of a Branch
#[derive(Clone, Default, Debug, Hash, PartialEq, Eq, derive_more::Display)] #[derive(Clone, Default, Debug, Hash, PartialEq, Eq, Display, PartialOrd, Ord)]
pub struct BranchName(String); pub struct BranchName(String);
impl BranchName { impl BranchName {
pub fn new(str: impl Into<String>) -> Self { pub fn new(str: impl Into<String>) -> Self {

View file

@ -55,6 +55,7 @@ actix = { workspace = true }
# Testing # Testing
assert2 = { workspace = true } assert2 = { workspace = true }
rand = { workspace = true } rand = { workspace = true }
pretty_assertions = { workspace = true }
[lints.clippy] [lints.clippy]
nursery = { level = "warn", priority = -1 } nursery = { level = "warn", priority = -1 }

View file

@ -37,7 +37,7 @@ pub enum Error {
NoTreeInCommit(String), NoTreeInCommit(String),
#[error("no .git-next.toml file found in repo")] #[error("no .git-next.toml file found in repo")]
NoGitNextToml, FileNotFound,
#[error("find reference: {0}")] #[error("find reference: {0}")]
FindReference(String), FindReference(String),

View file

@ -7,9 +7,7 @@ use super::{Generation, GitRemote};
/// The derived information about a repo, used to interact with it /// The derived information about a repo, used to interact with it
#[derive(Clone, Default, Debug, derive_more::Display, derive_with::With)] #[derive(Clone, Default, Debug, derive_more::Display, derive_with::With)]
#[display("gen-{}:{}:{}/{}:{}@{}/{}@{}", generation, forge.forge_type(), #[display("gen-{}:{}:{}/{}", generation, forge.forge_type(), forge.forge_alias(), repo_alias )]
forge.forge_alias(), repo_alias, forge.user(), forge.hostname(), repo_path,
branch)]
pub struct RepoDetails { pub struct RepoDetails {
pub generation: Generation, pub generation: Generation,
pub repo_alias: RepoAlias, pub repo_alias: RepoAlias,

View file

@ -6,19 +6,12 @@ use std::{
sync::{Arc, Mutex}, sync::{Arc, Mutex},
}; };
use crate::{self as git, Repository}; use crate as git;
use crate::{
repository::{
open::{OpenRepository, OpenRepositoryLike},
Direction, RepositoryLike,
},
GitRemote, RepoDetails,
};
use git_next_config as config; use git_next_config as config;
#[derive(Debug, Default, Clone)] #[derive(Debug, Default, Clone)]
pub struct MockRepository { pub struct MockRepository {
open_repos: Arc<Mutex<HashMap<config::GitDir, MockOpenRepository>>>, open_repos: Arc<Mutex<HashMap<config::GitDir, git::repository::MockOpenRepository>>>,
} }
impl MockRepository { impl MockRepository {
pub fn new() -> Self { pub fn new() -> Self {
@ -27,8 +20,11 @@ impl MockRepository {
} }
} }
pub fn given_can_be_opened(&mut self, gitdir: &config::GitDir) -> MockOpenRepository { pub fn given_can_be_opened(
let open_repo = MockOpenRepository::new(); &mut self,
gitdir: &config::GitDir,
) -> git::repository::MockOpenRepository {
let open_repo = git::repository::MockOpenRepository::new();
#[allow(clippy::unwrap_used)] #[allow(clippy::unwrap_used)]
self.open_repos self.open_repos
.lock() .lock()
@ -37,19 +33,25 @@ impl MockRepository {
open_repo open_repo
} }
pub fn seal(self) -> (Repository, Self) { pub fn seal(self) -> (git::Repository, Self) {
(Repository::Mock(self.clone()), self) (git::Repository::Mock(self.clone()), self)
} }
pub fn unseal(self, _repository: Repository) -> Self { pub fn unseal(self, _repository: git::Repository) -> Self {
// drop repository to allow same mutable access to mock repository // drop repository to allow same mutable access to mock repository
self self
} }
pub fn get(&self, gitdir: &config::GitDir) -> Option<git::repository::MockOpenRepository> {
self.open_repos
.lock()
.map(|or| or.get(gitdir).cloned())
.unwrap_or(None)
} }
impl RepositoryLike for MockRepository { }
impl git::repository::RepositoryLike for MockRepository {
fn open( fn open(
&self, &self,
gitdir: &config::GitDir, gitdir: &config::GitDir,
) -> std::result::Result<OpenRepository, crate::repository::Error> { ) -> std::result::Result<git::repository::OpenRepository, crate::repository::Error> {
#[allow(clippy::unwrap_used)] #[allow(clippy::unwrap_used)]
self.open_repos self.open_repos
.lock() .lock()
@ -62,96 +64,8 @@ impl RepositoryLike for MockRepository {
fn git_clone( fn git_clone(
&self, &self,
_repo_details: &RepoDetails, _repo_details: &git::RepoDetails,
) -> std::result::Result<OpenRepository, crate::repository::Error> { ) -> std::result::Result<git::repository::OpenRepository, crate::repository::Error> {
todo!("MockRepository::git_clone") todo!("MockRepository::git_clone")
} }
} }
#[derive(Clone, Debug, Default)]
pub struct MockOpenRepository {
default_push_remote: Arc<Mutex<Option<GitRemote>>>,
default_fetch_remote: Arc<Mutex<Option<GitRemote>>>,
}
impl MockOpenRepository {
pub fn new() -> Self {
Self::default()
}
pub fn given_has_default_remote(&mut self, direction: Direction, remote: Option<GitRemote>) {
#[allow(clippy::unwrap_used)]
match direction {
Direction::Push => self
.default_push_remote
.lock()
.map(|mut o| match remote {
Some(gr) => o.replace(gr),
None => o.take(),
})
.unwrap(),
Direction::Fetch => self
.default_fetch_remote
.lock()
.map(|mut o| match remote {
Some(gr) => o.replace(gr),
None => o.take(),
})
.unwrap(),
};
}
}
impl From<MockOpenRepository> for OpenRepository {
fn from(value: MockOpenRepository) -> Self {
Self::Mock(value)
}
}
#[allow(clippy::unwrap_used)]
impl OpenRepositoryLike for MockOpenRepository {
fn remote_branches(&self) -> git::push::Result<Vec<config::BranchName>> {
todo!("MockOpenRepository::remote_branched")
}
fn find_default_remote(&self, direction: Direction) -> Option<GitRemote> {
match direction {
Direction::Push => self
.default_push_remote
.lock()
.map(|r| r.clone())
.unwrap_or(None),
Direction::Fetch => self
.default_fetch_remote
.lock()
.map(|r| r.clone())
.unwrap_or(None),
}
}
fn fetch(&self) -> core::result::Result<(), crate::fetch::Error> {
todo!("MockOpenRepository::fetch")
}
fn push(
&self,
_repo_details: &RepoDetails,
_branch_name: &git_next_config::BranchName,
_to_commit: &crate::GitRef,
_force: &crate::push::Force,
) -> core::result::Result<(), crate::push::Error> {
todo!("MockOpenRepository::push")
}
fn commit_log(
&self,
_branch_name: &git_next_config::BranchName,
_find_commits: &[git::Commit],
) -> core::result::Result<Vec<crate::Commit>, git::commit::log::Error> {
todo!("MockOpenRepository::commit_log")
}
fn read_file(
&self,
_branch_name: &git_next_config::BranchName,
_file_name: &str,
) -> git::file::Result<String> {
todo!("MockOpenRepository::read_file")
}
}

View file

@ -1,4 +1,5 @@
// //
#[cfg(test)]
mod mock; mod mock;
mod open; mod open;
mod real; mod real;
@ -9,8 +10,14 @@ mod tests;
use git_next_config as config; use git_next_config as config;
use git_next_config::GitDir; use git_next_config::GitDir;
#[cfg(test)]
pub use mock::MockRepository; pub use mock::MockRepository;
#[cfg(test)]
pub use open::MockOpenRepository;
pub use open::OpenRepository; pub use open::OpenRepository;
pub use open::OpenRepositoryLike;
pub use open::RealOpenRepository;
pub use real::RealRepository;
use tracing::info; use tracing::info;
use crate::validation::repo::validate_repo; use crate::validation::repo::validate_repo;
@ -20,11 +27,13 @@ use super::RepoDetails;
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub enum Repository { pub enum Repository {
Real, Real,
#[cfg(test)]
Mock(MockRepository), Mock(MockRepository),
} }
pub const fn new() -> Repository { pub const fn new() -> Repository {
Repository::Real Repository::Real
} }
#[cfg(test)]
pub fn mock() -> MockRepository { pub fn mock() -> MockRepository {
MockRepository::new() MockRepository::new()
// (Repository::Mock(mock_repository.clone()), mock_repository) // (Repository::Mock(mock_repository.clone()), mock_repository)
@ -32,6 +41,7 @@ pub fn mock() -> MockRepository {
/// Opens a repository, cloning if necessary /// Opens a repository, cloning if necessary
#[tracing::instrument(skip_all)] #[tracing::instrument(skip_all)]
#[cfg(not(tarpaulin_include))] // requires network access to either clone new and/or fetch.
pub fn open( pub fn open(
repository: &Repository, repository: &Repository,
repo_details: &RepoDetails, repo_details: &RepoDetails,
@ -59,6 +69,7 @@ impl std::ops::Deref for Repository {
fn deref(&self) -> &Self::Target { fn deref(&self) -> &Self::Target {
match self { match self {
Self::Real => &real::RealRepository, Self::Real => &real::RealRepository,
#[cfg(test)]
Self::Mock(mock_repository) => mock_repository, Self::Mock(mock_repository) => mock_repository,
} }
} }

View file

@ -1,32 +1,70 @@
// //
#![allow(dead_code)]
#[cfg(test)] #[cfg(test)]
mod tests; mod tests;
pub mod oreal; pub mod oreal;
#[cfg(test)]
pub mod otest;
#[cfg(test)]
pub mod omock;
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
use crate as git; use crate as git;
use git::repository::open::oreal::RealOpenRepository;
use git::repository::Direction; use git::repository::Direction;
use git_next_config as config; use git_next_config as config;
#[cfg(test)]
pub use omock::MockOpenRepository;
pub use oreal::RealOpenRepository;
#[cfg(test)]
pub use otest::TestOpenRepository;
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub enum OpenRepository { pub enum OpenRepository {
/// A real git repository.
///
/// This variant is the normal implementation for use in production code.
Real(RealOpenRepository), Real(RealOpenRepository),
Mock(git::repository::mock::MockOpenRepository), // TODO: (#38) contain a mock model of a repo /// A fake git repository.
///
/// This variant has no on-disk presense, and only fakes some of
/// the behaviour of a git repository. Once the [Self::LocalOnly]
/// variant is ready for use, tests should be converted to using
/// that instead.
#[cfg(test)]
Mock(git::repository::MockOpenRepository), // TODO: (#38) contain a mock model of a repo
/// A real git repository, but with preprogrammed responses to network access.
///
/// This variant is for use only in testing. Requests to methods
/// that would require network access, such as to the git remote
/// server will result in an error, unless a predefined change
/// has been scheduled for that request.
#[cfg(test)]
Test(TestOpenRepository),
} }
impl OpenRepository {
pub fn real(gix_repo: gix::Repository) -> Self { pub fn real(gix_repo: gix::Repository) -> OpenRepository {
Self::Real(oreal::RealOpenRepository::new(Arc::new(Mutex::new( OpenRepository::Real(oreal::RealOpenRepository::new(Arc::new(Mutex::new(
gix_repo, gix_repo,
)))) ))))
} }
#[cfg(not(tarpaulin_include))] // don't test mocks #[cfg(not(tarpaulin_include))] // don't test mocks
pub const fn mock(mock: git::repository::mock::MockOpenRepository) -> Self { #[cfg(test)]
Self::Mock(mock) pub const fn mock(mock: git::repository::MockOpenRepository) -> OpenRepository {
OpenRepository::Mock(mock)
} }
#[cfg(not(tarpaulin_include))] // don't test mocks
#[cfg(test)]
pub fn test(fs: &kxio::fs::FileSystem) -> OpenRepository {
OpenRepository::Test(TestOpenRepository::new(fs))
} }
pub trait OpenRepositoryLike { pub trait OpenRepositoryLike {
fn remote_branches(&self) -> git::push::Result<Vec<config::BranchName>>; fn remote_branches(&self) -> git::push::Result<Vec<config::BranchName>>;
fn find_default_remote(&self, direction: Direction) -> Option<git::GitRemote>; fn find_default_remote(&self, direction: Direction) -> Option<git::GitRemote>;
@ -61,7 +99,10 @@ impl std::ops::Deref for OpenRepository {
fn deref(&self) -> &Self::Target { fn deref(&self) -> &Self::Target {
match self { match self {
Self::Real(real) => real, Self::Real(real) => real,
#[cfg(test)]
Self::Mock(mock) => mock, Self::Mock(mock) => mock,
#[cfg(test)]
Self::Test(test) => test,
} }
} }
} }

View file

@ -0,0 +1,118 @@
//
use crate as git;
use git_next_config as config;
use std::sync::{Arc, Mutex};
#[derive(Clone, Debug, Default)]
pub struct MockOpenRepository {
default_push_remote: Arc<Mutex<Option<git::GitRemote>>>,
default_fetch_remote: Arc<Mutex<Option<git::GitRemote>>>,
operations: Arc<Mutex<Vec<String>>>,
}
impl MockOpenRepository {
pub fn new() -> Self {
Self::default()
}
pub fn given_has_default_remote(
&mut self,
direction: git::repository::Direction,
remote: Option<git::GitRemote>,
) {
#[allow(clippy::unwrap_used)]
match direction {
git::repository::Direction::Push => self
.default_push_remote
.lock()
.map(|mut o| match remote {
Some(gr) => o.replace(gr),
None => o.take(),
})
.unwrap(),
git::repository::Direction::Fetch => self
.default_fetch_remote
.lock()
.map(|mut o| match remote {
Some(gr) => o.replace(gr),
None => o.take(),
})
.unwrap(),
};
}
pub fn operations(&self) -> Vec<String> {
self.operations
.lock()
.map(|operations| operations.clone())
.unwrap_or_default()
}
}
impl From<MockOpenRepository> for git::OpenRepository {
fn from(value: MockOpenRepository) -> Self {
Self::Mock(value)
}
}
#[allow(clippy::unwrap_used)]
impl git::repository::OpenRepositoryLike for MockOpenRepository {
fn remote_branches(&self) -> git::push::Result<Vec<config::BranchName>> {
todo!("MockOpenRepository::remote_branched")
}
fn find_default_remote(&self, direction: git::repository::Direction) -> Option<git::GitRemote> {
match direction {
git::repository::Direction::Push => self
.default_push_remote
.lock()
.map(|r| r.clone())
.unwrap_or(None),
git::repository::Direction::Fetch => self
.default_fetch_remote
.lock()
.map(|r| r.clone())
.unwrap_or(None),
}
}
fn fetch(&self) -> core::result::Result<(), crate::fetch::Error> {
self.operations
.lock()
.map_err(|_| crate::fetch::Error::Lock)
.map(|mut operations| operations.push("fetch".to_string()))?;
Ok(())
}
fn push(
&self,
repo_details: &git::RepoDetails,
branch_name: &git_next_config::BranchName,
to_commit: &crate::GitRef,
force: &crate::push::Force,
) -> core::result::Result<(), crate::push::Error> {
let forge_alias = repo_details.forge.forge_alias();
let repo_alias = &repo_details.repo_alias;
self.operations
.lock()
.map_err(|_| crate::fetch::Error::Lock)
.map(|mut operations| {
operations.push(format!(
"push fa:{forge_alias} ra:{repo_alias} bn:{branch_name} tc:{to_commit} f:{force}"
))
})?;
Ok(())
}
fn commit_log(
&self,
_branch_name: &git_next_config::BranchName,
_find_commits: &[git::Commit],
) -> core::result::Result<Vec<crate::Commit>, git::commit::log::Error> {
todo!("MockOpenRepository::commit_log")
}
fn read_file(
&self,
_branch_name: &git_next_config::BranchName,
_file_name: &str,
) -> git::file::Result<String> {
todo!("MockOpenRepository::read_file")
}
}

View file

@ -1,13 +1,14 @@
// //
use crate as git; use crate as git;
use config::BranchName; use config::BranchName;
use derive_more::Constructor;
use git_next_config as config; use git_next_config as config;
use gix::bstr::BStr; use gix::bstr::BStr;
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
use tracing::{info, warn}; use tracing::{info, warn};
#[derive(Clone, Debug, derive_more::Constructor)] #[derive(Clone, Debug, Constructor)]
pub struct RealOpenRepository(Arc<Mutex<gix::Repository>>); pub struct RealOpenRepository(Arc<Mutex<gix::Repository>>);
impl super::OpenRepositoryLike for RealOpenRepository { impl super::OpenRepositoryLike for RealOpenRepository {
fn remote_branches(&self) -> git::push::Result<Vec<config::BranchName>> { fn remote_branches(&self) -> git::push::Result<Vec<config::BranchName>> {
@ -45,6 +46,7 @@ impl super::OpenRepositoryLike for RealOpenRepository {
} }
#[tracing::instrument(skip_all)] #[tracing::instrument(skip_all)]
#[cfg(not(tarpaulin_include))] // would require writing to external service
fn fetch(&self) -> Result<(), git::fetch::Error> { fn fetch(&self) -> Result<(), git::fetch::Error> {
let Ok(repository) = self.0.lock() else { let Ok(repository) = self.0.lock() else {
#[cfg(not(tarpaulin_include))] // don't test mutex lock failure #[cfg(not(tarpaulin_include))] // don't test mutex lock failure
@ -171,8 +173,8 @@ impl super::OpenRepositoryLike for RealOpenRepository {
let commit = obj.into_commit(); let commit = obj.into_commit();
let tree = commit.tree()?; let tree = commit.tree()?;
let ent = tree let ent = tree
.find_entry(".git-next.toml") .find_entry(file_name)
.ok_or(git::file::Error::NoGitNextToml)?; .ok_or(git::file::Error::FileNotFound)?;
let fobj = ent.object()?; let fobj = ent.object()?;
let blob = fobj.into_blob().take_data(); let blob = fobj.into_blob().take_data();
let content = String::from_utf8(blob)?; let content = String::from_utf8(blob)?;

View file

@ -0,0 +1,64 @@
//
use crate as git;
use git::tests::given;
use git_next_config as config;
use std::sync::{Arc, Mutex};
use assert2::let_assert;
#[derive(Clone, Debug)]
pub struct TestOpenRepository {
real: git::repository::RealOpenRepository,
}
impl git::repository::OpenRepositoryLike for TestOpenRepository {
fn remote_branches(&self) -> crate::push::Result<Vec<config::BranchName>> {
self.real.remote_branches()
}
fn find_default_remote(
&self,
direction: crate::repository::Direction,
) -> Option<crate::GitRemote> {
self.real.find_default_remote(direction)
}
fn fetch(&self) -> Result<(), crate::fetch::Error> {
todo!()
}
fn push(
&self,
_repo_details: &crate::RepoDetails,
_branch_name: &config::BranchName,
_to_commit: &crate::GitRef,
_force: &crate::push::Force,
) -> crate::push::Result<()> {
todo!()
}
fn commit_log(
&self,
branch_name: &config::BranchName,
find_commits: &[crate::Commit],
) -> crate::commit::log::Result<Vec<crate::Commit>> {
self.real.commit_log(branch_name, find_commits)
}
fn read_file(
&self,
branch_name: &config::BranchName,
file_name: &str,
) -> crate::file::Result<String> {
self.real.read_file(branch_name, file_name)
}
}
impl TestOpenRepository {
pub fn new(fs: &kxio::fs::FileSystem) -> Self {
let directory = fs.base().join(given::a_name());
let_assert!(Ok(gix) = gix::init_bare(directory), "git init bare");
Self {
real: git::repository::RealOpenRepository::new(Arc::new(Mutex::new(gix))),
}
}
}

View file

@ -1,22 +1,27 @@
// //
use crate as git;
use crate::repository::RepositoryLike as _;
use git_next_config as config;
use assert2::let_assert;
mod find_default_remote { mod find_default_remote {
use assert2::let_assert; use super::*;
use git_next_config::{GitDir, Hostname, RepoPath};
use assert2::let_assert;
use crate::GitRemote;
#[test] #[test]
fn should_find_default_push_remote() { fn should_find_default_push_remote() {
// uses the current repo // uses the current repo
let_assert!(Ok(cwd) = std::env::current_dir()); let_assert!(Ok(cwd) = std::env::current_dir());
let gitdir = GitDir::from(cwd.join("../..")); // from ./crate/git directory to the project rook let gitdir = config::GitDir::from(cwd.join("../..")); // from ./crate/git directory to the project rook
let_assert!(Ok(repo) = crate::repository::new().open(&gitdir)); let_assert!(Ok(repo) = crate::repository::new().open(&gitdir));
let_assert!(Some(remote) = repo.find_default_remote(crate::repository::Direction::Push)); let_assert!(Some(remote) = repo.find_default_remote(crate::repository::Direction::Push));
assert_eq!( assert_eq!(
remote, remote,
GitRemote::new( git::GitRemote::new(
Hostname::new("git.kemitix.net"), config::Hostname::new("git.kemitix.net"),
RepoPath::new("kemitix/git-next".to_string()) config::RepoPath::new("kemitix/git-next".to_string())
) )
) )
} }
@ -36,3 +41,99 @@ mod fetch {
let_assert!(Ok(_) = repo.fetch()); let_assert!(Ok(_) = repo.fetch());
} }
} }
mod remote_branches {
use super::*;
#[test]
// assumes running in the git-next repo which should have main, next and dev as remote branches
fn should_return_remote_branches() {
let open_repo = given_open_real_repository();
let_assert!(Ok(mut remote_branches) = open_repo.remote_branches());
remote_branches.sort();
let mut expected = [
config::BranchName::new("main"),
config::BranchName::new("next"),
config::BranchName::new("dev"),
];
expected.sort();
assert_eq!(remote_branches, expected);
}
}
mod commit_log {
use git::tests::given;
use super::*;
#[test]
// assumes running in the git-next repo which should have main, next and dev as remote branches
fn should_return_single_item_in_commit_log_when_not_searching() {
let open_repo = given_open_real_repository();
let_assert!(Ok(result) = open_repo.commit_log(&config::BranchName::new("dev"), &[]));
assert_eq!(result.len(), 1)
}
#[test]
// assumes running in the git-next repo which should have main, next and dev as remote branches
fn should_return_capacity_50_in_commit_log_when_searching_for_garbage() {
let open_repo = given_open_real_repository();
let_assert!(
Ok(result) =
open_repo.commit_log(&config::BranchName::new("dev"), &[given::a_commit()])
);
assert_eq!(result.len(), 50)
}
#[test]
// assumes running in the git-next repo which should have main, next and dev as remote branches
fn should_return_25_in_commit_log_when_searching_for_25th_item() {
let open_repo = given_open_real_repository();
// search to garbage to get full page of 50 items
let_assert!(
Ok(long_list) =
open_repo.commit_log(&config::BranchName::new("dev"), &[given::a_commit()])
);
// pick the 25th item
let search = &long_list[24]; // zero-based
// search for the 25th item
let_assert!(
Ok(result) = open_repo.commit_log(&config::BranchName::new("dev"), &[search.clone()])
);
// returns
assert_eq!(result.len(), 25)
}
}
mod read_file {
use git::tests::given;
use super::*;
#[test]
// assumes running in the git-next repo which should have main, next and dev as remote branches
fn should_return_file() {
let open_repo = given_open_real_repository();
let_assert!(
Ok(result) =
open_repo.read_file(&config::BranchName::new("dev"), "server-default.toml")
);
let expected = include_str!("../../../../../server-default.toml");
assert_eq!(result, expected);
}
#[test]
// assumes running in the git-next repo which should have main, next and dev as remote branches
fn should_error_on_missing_file() {
let open_repo = given_open_real_repository();
let_assert!(
Err(err) = open_repo.read_file(&config::BranchName::new("dev"), &given::a_name())
);
assert!(matches!(err, git::file::Error::FileNotFound));
}
}
fn given_open_real_repository() -> git::OpenRepository {
// assumes the current directory is a clone of this repo
let_assert!(Ok(current_dir) = std::env::current_dir()); // ./crates/git
let gitdir: config::GitDir = current_dir.join("../..").into(); // cd back to project root
let_assert!(Ok(real_open_repository) = git::repository::RealRepository.open(&gitdir));
real_open_repository
}

View file

@ -1,22 +1,23 @@
//
use std::sync::atomic::AtomicBool; use std::sync::atomic::AtomicBool;
use crate as git;
use derive_more::Deref as _; use derive_more::Deref as _;
use git_next_config::GitDir; use git_next_config::GitDir;
use crate::{
repository::{open::OpenRepository, Error, RepositoryLike},
RepoDetails,
};
pub struct RealRepository; pub struct RealRepository;
impl RepositoryLike for RealRepository { impl git::repository::RepositoryLike for RealRepository {
fn open(&self, gitdir: &GitDir) -> Result<OpenRepository, Error> { fn open(&self, gitdir: &GitDir) -> Result<git::OpenRepository, git::repository::Error> {
let gix_repo = gix::ThreadSafeRepository::open(gitdir.to_path_buf())?.to_thread_local(); let gix_repo = gix::ThreadSafeRepository::open(gitdir.to_path_buf())?.to_thread_local();
Ok(OpenRepository::real(gix_repo)) Ok(git::repository::open::real(gix_repo))
} }
#[tracing::instrument(skip_all)] #[tracing::instrument(skip_all)]
fn git_clone(&self, repo_details: &RepoDetails) -> Result<OpenRepository, Error> { #[cfg(not(tarpaulin_include))] // requires external server
fn git_clone(
&self,
repo_details: &git::RepoDetails,
) -> Result<git::OpenRepository, git::repository::Error> {
tracing::info!("creating"); tracing::info!("creating");
use secrecy::ExposeSecret; use secrecy::ExposeSecret;
let (gix_repo, _outcome) = gix::prepare_clone_bare( let (gix_repo, _outcome) = gix::prepare_clone_bare(
@ -26,6 +27,6 @@ impl RepositoryLike for RealRepository {
.fetch_only(gix::progress::Discard, &AtomicBool::new(false))?; .fetch_only(gix::progress::Discard, &AtomicBool::new(false))?;
tracing::info!("created"); tracing::info!("created");
Ok(OpenRepository::real(gix_repo)) Ok(git::repository::open::real(gix_repo))
} }
} }

View file

@ -81,23 +81,59 @@ mod gitremote {
} }
} }
mod push { mod push {
use crate::{commit, push::Force, Commit, GitRef}; use super::*;
use crate::GitRef;
#[test] #[test]
fn force_no_should_display() { fn force_no_should_display() {
assert_eq!(Force::No.to_string(), "fast-forward") assert_eq!(git::push::Force::No.to_string(), "fast-forward")
} }
#[test] #[test]
fn force_from_should_display() { fn force_from_should_display() {
let commit = Commit::new( let sha = given::a_name();
commit::Sha::new("sha".to_string()), let commit = given::a_commit_with_sha(&git::commit::Sha::new(sha.clone()));
commit::Message::new("message".to_string()),
);
assert_eq!( assert_eq!(
Force::From(GitRef::from(commit)).to_string(), git::push::Force::From(GitRef::from(commit)).to_string(),
"force-if-from:sha" format!("force-if-from:{sha}")
) )
} }
mod reset {
use super::*;
use crate::{tests::given, OpenRepository};
use assert2::let_assert;
#[test]
fn should_perform_a_fetch_then_push() {
let fs = given::a_filesystem();
let (mock_open_repository, gitdir, mock_repository) = given::an_open_repository(&fs);
let open_repository: OpenRepository = mock_open_repository.into();
let repo_details = given::repo_details(&fs);
let branch_name = &repo_details.branch;
let commit = given::a_commit();
let gitref = GitRef::from(commit);
let_assert!(
Ok(_) = git::push::reset(
&open_repository,
&repo_details,
branch_name,
&gitref,
&git::push::Force::No
)
);
let_assert!(Some(mock_open_repository) = mock_repository.get(&gitdir));
let operations = mock_open_repository.operations();
let forge_alias = repo_details.forge.forge_alias();
let repo_alias = &repo_details.repo_alias;
let to_commit = gitref;
let force = "fast-forward";
assert_eq!(
operations,
vec![format!("fetch"), format!("push fa:{forge_alias} ra:{repo_alias} bn:{branch_name} tc:{to_commit} f:{force}")]
);
}
}
} }
mod repo_details { mod repo_details {
@ -172,10 +208,13 @@ mod repo_details {
); );
} }
} }
mod given { pub mod given {
#![allow(dead_code)] #![allow(dead_code)]
// //
use crate as git; use crate::{
self as git,
repository::{MockOpenRepository, MockRepository},
};
use config::{ use config::{
BranchName, ForgeAlias, ForgeConfig, ForgeType, GitDir, RepoAlias, RepoBranches, BranchName, ForgeAlias, ForgeConfig, ForgeType, GitDir, RepoAlias, RepoBranches,
ServerRepoConfig, WebhookAuth, WebhookId, ServerRepoConfig, WebhookAuth, WebhookId,
@ -335,11 +374,12 @@ mod given {
) )
} }
// pub fn an_open_repository(fs: &kxio::fs::FileSystem) -> (OpenRepository, MockRepository) { pub fn an_open_repository(
// let (repo, mock) = git::repository::mock(); fs: &kxio::fs::FileSystem,
// ) -> (MockOpenRepository, GitDir, MockRepository) {
// let gitdir = a_git_dir(fs); let mut mock = git::repository::mock();
// let op = repo.open(&gitdir).unwrap(); let gitdir = a_git_dir(fs);
// (op, mock) let or = mock.given_can_be_opened(&gitdir);
// } (or, gitdir, mock)
}
} }

View file

@ -93,7 +93,7 @@ impl Actor for RepoActor {
pub struct CloneRepo; pub struct CloneRepo;
impl Handler<CloneRepo> for RepoActor { impl Handler<CloneRepo> for RepoActor {
type Result = (); type Result = ();
#[tracing::instrument(name = "RepoActor::CloneRepo", skip_all, fields(repo = %self.repo_details, gitdir = %self.repo_details.gitdir))] #[tracing::instrument(name = "RepoActor::CloneRepo", skip_all, fields(repo = %self.repo_details /*, gitdir = %self.repo_details.gitdir */))]
fn handle(&mut self, _msg: CloneRepo, ctx: &mut Self::Context) -> Self::Result { fn handle(&mut self, _msg: CloneRepo, ctx: &mut Self::Context) -> Self::Result {
let gitdir = self.repo_details.gitdir.clone(); let gitdir = self.repo_details.gitdir.clone();
match git::repository::open(&self.repository, &self.repo_details, gitdir) { match git::repository::open(&self.repository, &self.repo_details, gitdir) {