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 8a4f4c0ae3
19 changed files with 726 additions and 183 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

@ -40,21 +40,19 @@ pub struct Histories {
pub mod log { pub mod log {
use git_next_config as config;
pub type Result<T> = core::result::Result<T, Error>; pub type Result<T> = core::result::Result<T, Error>;
#[derive(Debug, thiserror::Error)] #[derive(Debug, thiserror::Error)]
pub enum Error { pub enum Error {
#[error("gix: {0}")] #[error("branch: {branch}, error: {error}")]
Gix(String), Gix {
branch: config::BranchName,
error: String,
},
#[error("lock")] #[error("lock")]
Lock, Lock,
} }
impl From<String> for Error {
#[cfg(not(tarpaulin_include))]
fn from(e: String) -> Self {
Self::Gix(e)
}
}
} }

View file

@ -1,4 +1,7 @@
#[derive(Debug, thiserror::Error)] //
pub type Result<T> = core::result::Result<T, Error>;
#[derive(Clone, Debug, thiserror::Error)]
pub enum Error { pub enum Error {
#[error("unable to open repo: {0}")] #[error("unable to open repo: {0}")]
UnableToOpenRepo(String), UnableToOpenRepo(String),
@ -17,4 +20,12 @@ pub enum Error {
#[error("lock")] #[error("lock")]
Lock, Lock,
#[cfg(test)]
#[error("expected failure in test")]
TestFailureExpected,
#[cfg(test)]
#[error("unexpected fetch in test")]
TestUnexpectedFetch,
} }

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,7 +1,10 @@
// //
#[cfg(test)]
mod mock; mod mock;
mod open; mod open;
mod real; mod real;
#[cfg(test)]
mod test;
#[cfg(test)] #[cfg(test)]
mod tests; mod tests;
@ -9,10 +12,21 @@ 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::otest::OnFetch;
#[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;
#[cfg(test)]
use crate::repository::test::TestRepository;
use crate::validation::repo::validate_repo; use crate::validation::repo::validate_repo;
use super::RepoDetails; use super::RepoDetails;
@ -20,18 +34,26 @@ use super::RepoDetails;
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub enum Repository { pub enum Repository {
Real, Real,
#[cfg(test)]
Mock(MockRepository), Mock(MockRepository),
#[cfg(test)]
Test(TestRepository),
} }
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) }
#[cfg(test)]
pub const fn test(fs: kxio::fs::FileSystem) -> TestRepository {
TestRepository::new(fs, None)
} }
/// 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,7 +81,10 @@ 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,
#[cfg(test)]
Self::Test(test_repository) => test_repository,
} }
} }
} }

View file

@ -1,32 +1,74 @@
// //
#![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
pub const fn mock(mock: git::repository::mock::MockOpenRepository) -> Self {
Self::Mock(mock)
}
} }
#[cfg(not(tarpaulin_include))] // don't test mocks
#[cfg(test)]
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(
gitdir: &config::GitDir,
fs: kxio::fs::FileSystem,
on_fetch: Option<otest::OnFetch>,
) -> OpenRepository {
OpenRepository::Test(TestOpenRepository::new(gitdir, fs, on_fetch))
}
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 +103,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
@ -123,23 +125,40 @@ impl super::OpenRepositoryLike for RealOpenRepository {
.lock() .lock()
.map_err(|_| git::commit::log::Error::Lock) .map_err(|_| git::commit::log::Error::Lock)
.map(|repo| { .map(|repo| {
let branch_name = format!("remotes/origin/{branch_name}"); let branch = format!("remotes/origin/{branch_name}");
let branch_name = BStr::new(&branch_name); let branch = BStr::new(&branch);
let branch_head = repo let branch_head = repo
.rev_parse_single(branch_name) .rev_parse_single(branch)
.map_err(|e| e.to_string())?; .map_err(|e| e.to_string())
let object = branch_head.object().map_err(|e| e.to_string())?; .map_err(as_gix_error(branch_name.clone()))?;
let commit = object.try_into_commit().map_err(|e| e.to_string())?; let object = branch_head
.object()
.map_err(|e| e.to_string())
.map_err(as_gix_error(branch_name.clone()))?;
let commit = object
.try_into_commit()
.map_err(|e| e.to_string())
.map_err(as_gix_error(branch_name.clone()))?;
let walk = repo let walk = repo
.rev_walk([commit.id]) .rev_walk([commit.id])
.all() .all()
.map_err(|e| e.to_string())?; .map_err(|e| e.to_string())
.map_err(as_gix_error(branch_name.clone()))?;
let mut commits = vec![]; let mut commits = vec![];
for item in walk.take(limit) { for item in walk.take(limit) {
let item = item.map_err(|e| e.to_string())?; let item = item
let commit = item.object().map_err(|e| e.to_string())?; .map_err(|e| e.to_string())
.map_err(as_gix_error(branch_name.clone()))?;
let commit = item
.object()
.map_err(|e| e.to_string())
.map_err(as_gix_error(branch_name.clone()))?;
let id = commit.id().to_string(); let id = commit.id().to_string();
let message = commit.message_raw().map_err(|e| e.to_string())?.to_string(); let message = commit
.message_raw()
.map_err(|e| e.to_string())
.map_err(as_gix_error(branch_name.clone()))?
.to_string();
let commit = git::Commit::new( let commit = git::Commit::new(
git::commit::Sha::new(id), git::commit::Sha::new(id),
git::commit::Message::new(message), git::commit::Message::new(message),
@ -171,8 +190,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)?;
@ -181,6 +200,10 @@ impl super::OpenRepositoryLike for RealOpenRepository {
} }
} }
fn as_gix_error(branch: BranchName) -> impl FnOnce(String) -> git::commit::log::Error {
|error| git::commit::log::Error::Gix { branch, error }
}
impl From<&gix::Url> for git::GitRemote { impl From<&gix::Url> for git::GitRemote {
fn from(url: &gix::Url) -> Self { fn from(url: &gix::Url) -> Self {
let host = url.host().unwrap_or_default(); let host = url.host().unwrap_or_default();

View file

@ -0,0 +1,89 @@
//
use crate as git;
use derive_more::Constructor;
use git_next_config as config;
use std::sync::{Arc, Mutex};
use assert2::let_assert;
pub type OnFetchFn =
fn(&config::BranchName, &config::GitDir, &kxio::fs::FileSystem) -> git::fetch::Result<()>;
#[derive(Clone, Debug, Constructor)]
pub struct OnFetch {
branch_name: config::BranchName,
gitdir: config::GitDir,
fs: kxio::fs::FileSystem,
action: OnFetchFn,
}
impl OnFetch {
pub fn invoke(&self) -> git::fetch::Result<()> {
(self.action)(&self.branch_name, &self.gitdir, &self.fs)
}
}
#[derive(Clone, Debug)]
pub struct TestOpenRepository {
gitdir: config::GitDir,
fs: kxio::fs::FileSystem,
on_fetch: Option<OnFetch>,
real: git::repository::RealOpenRepository,
}
impl git::repository::OpenRepositoryLike for TestOpenRepository {
fn remote_branches(&self) -> git::push::Result<Vec<config::BranchName>> {
self.real.remote_branches()
}
fn find_default_remote(&self, direction: git::repository::Direction) -> Option<git::GitRemote> {
self.real.find_default_remote(direction)
}
fn fetch(&self) -> Result<(), git::fetch::Error> {
self.on_fetch
.clone()
.map(|f| f.invoke())
.unwrap_or(Err(git::fetch::Error::TestUnexpectedFetch))
}
fn push(
&self,
_repo_details: &git::RepoDetails,
_branch_name: &config::BranchName,
_to_commit: &git::GitRef,
_force: &git::push::Force,
) -> git::push::Result<()> {
todo!()
}
fn commit_log(
&self,
branch_name: &config::BranchName,
find_commits: &[git::Commit],
) -> git::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,
) -> git::file::Result<String> {
self.real.read_file(branch_name, file_name)
}
}
impl TestOpenRepository {
pub fn new(
gitdir: &config::GitDir,
fs: kxio::fs::FileSystem,
on_fetch: Option<OnFetch>,
) -> Self {
let pathbuf = fs.base().join(gitdir.to_path_buf());
let_assert!(Ok(gix) = gix::init_bare(pathbuf), "git init bare");
Self {
gitdir: gitdir.clone(),
fs,
on_fetch,
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,94 @@ 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(remote_branches) = open_repo.remote_branches());
assert!(remote_branches.contains(&config::BranchName::new("main")));
assert!(remote_branches.contains(&config::BranchName::new("next")));
assert!(remote_branches.contains(&config::BranchName::new("dev")));
}
}
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

@ -0,0 +1,37 @@
//
use derive_more::Constructor;
use crate::{self as git, repository::open::otest::OnFetch};
use git::repository::RepositoryLike;
use git_next_config as config;
#[derive(Clone, Debug, Constructor)]
pub struct TestRepository {
fs: kxio::fs::FileSystem,
on_fetch: Option<git::repository::open::otest::OnFetch>,
}
impl TestRepository {
pub fn on_fetch(&mut self, on_fetch: OnFetch) {
self.on_fetch.replace(on_fetch);
}
pub const fn fs(&self) -> &kxio::fs::FileSystem {
&self.fs
}
}
impl RepositoryLike for TestRepository {
fn open(&self, gitdir: &config::GitDir) -> super::Result<crate::OpenRepository> {
Ok(git::repository::open::test(
gitdir,
self.fs.clone(),
self.on_fetch.clone(),
))
}
fn git_clone(
&self,
_repo_details: &crate::RepoDetails,
) -> super::Result<crate::OpenRepository> {
todo!()
}
}

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,13 +208,17 @@ 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},
tests::given,
};
use config::{ use config::{
BranchName, ForgeAlias, ForgeConfig, ForgeType, GitDir, RepoAlias, RepoBranches, BranchName, ForgeAlias, ForgeConfig, ForgeType, GitDir, RepoAlias, RepoBranches,
ServerRepoConfig, WebhookAuth, WebhookId, RepoConfig, ServerRepoConfig, WebhookAuth, WebhookId,
}; };
use git_next_config as config; use git_next_config as config;
@ -282,6 +322,10 @@ mod given {
) )
} }
pub fn a_repo_config() -> RepoConfig {
RepoConfig::new(given::repo_branches(), config::RepoConfigSource::Repo)
}
pub fn a_commit() -> git::Commit { pub fn a_commit() -> git::Commit {
git::Commit::new(a_commit_sha(), a_commit_message()) git::Commit::new(a_commit_sha(), a_commit_message())
} }
@ -335,11 +379,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

@ -1,2 +1,5 @@
pub mod positions; pub mod positions;
pub mod repo; pub mod repo;
#[cfg(test)]
mod tests;

View file

@ -0,0 +1,137 @@
//
use crate as git;
use git::tests::given;
use git_next_config as config;
use assert2::let_assert;
mod positions {
use super::*;
use git::repository::RepositoryLike as _;
mod validate_positions {
use git::validation::positions::validate_positions;
use super::*;
#[test]
fn where_fetch_fails_should_error() {
let_assert!(Ok(fs) = kxio::fs::temp(), "temp fs");
let gitdir: config::GitDir = fs.base().to_path_buf().into();
let mut test_repository = git::repository::test(fs.clone());
test_repository.on_fetch(git::repository::OnFetch::new(
given::a_branch_name(),
gitdir.clone(),
fs.clone(),
|_, _, _| git::fetch::Result::Err(git::fetch::Error::TestFailureExpected),
));
let_assert!(Ok(repository) = test_repository.open(&gitdir), "open repo");
let repo_details = given::repo_details(&fs).with_gitdir(gitdir);
let repo_config = given::a_repo_config();
let_assert!(
Err(err) = validate_positions(&repository, &repo_details, repo_config),
"validate"
);
assert!(matches!(
err,
git::validation::positions::Error::Fetch(git::fetch::Error::TestFailureExpected)
));
}
#[test]
fn where_main_branch_is_missing_or_commit_log_is_empty_should_error() {
let_assert!(Ok(fs) = kxio::fs::temp(), "temp fs");
let gitdir: config::GitDir = fs.base().to_path_buf().into();
let mut test_repository = git::repository::test(fs.clone());
test_repository.on_fetch(git::repository::OnFetch::new(
given::a_branch_name(),
gitdir.clone(),
fs.clone(),
|_, _, _| git::fetch::Result::Ok(()),
));
// test repo is a new bare repo with no commits
let_assert!(Ok(repository) = test_repository.open(&gitdir), "open repo");
let repo_details = given::repo_details(&fs).with_gitdir(gitdir);
let repo_config = given::a_repo_config();
let_assert!(
Err(err) = validate_positions(&repository, &repo_details, repo_config.clone()),
"validate"
);
let branch_name = repo_config.branches().main();
let error_message = format!(
r#"The ref partially named "remotes/origin/{branch_name}" could not be found"#
);
eprintln!("{err:#?}");
assert!(matches!(
err,
git::validation::positions::Error::CommitLog(git::commit::log::Error::Gix {
branch,
error
}) if branch == branch_name && error == error_message
));
}
#[test]
#[ignore]
fn where_next_branch_is_missing_or_commit_log_is_empty_should_error() {
let_assert!(Ok(fs) = kxio::fs::temp(), "temp fs");
let gitdir: config::GitDir = fs.base().to_path_buf().into();
let mut test_repository = git::repository::test(fs.clone());
let repo_config = given::a_repo_config();
test_repository.on_fetch(git::repository::OnFetch::new(
repo_config.branches().main(),
gitdir.clone(),
fs.clone(),
|main_branch, gitdir, fs| {
then::create_a_commit_on_branch(&fs, &gitdir, main_branch);
git::fetch::Result::Ok(())
},
));
let_assert!(Ok(repository) = test_repository.open(&gitdir), "open repo");
let repo_details = given::repo_details(&fs).with_gitdir(gitdir);
let_assert!(
Err(err) = validate_positions(&repository, &repo_details, repo_config.clone()),
"validate"
);
let branch_name = repo_config.branches().next();
let error_message = format!(
r#"The ref partially named "remotes/origin/{branch_name}" could not be found"#
);
eprintln!("Expected: branch: {branch_name}, error: {error_message}");
eprintln!("{err:#?}");
assert!(matches!(
err,
git::validation::positions::Error::CommitLog(git::commit::log::Error::Gix {
branch,
error
}) if branch == branch_name && error == error_message
));
}
// where dev branch is missing or commit log is empty should error
// where dev branch os not based on main should error
// where next branch is not based on main should reset next branch to main and then error
// where next branch os not based on main and reset of next fails should error
// where dev branch is not based on next should reset next branch to main and then error
// where dev branch is not based on next and reset of next fails should error
// where dev branch is not based on main should error
}
}
mod then {
use super::*;
pub const fn create_a_commit_on_branch(
_fs: &kxio::fs::FileSystem,
_gitdir: &config::GitDir,
_branch: &config::BranchName,
) {
// TODO: create a commit on the branch
}
}

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) {