WIP: add more tests to repo-actor crate
This commit is contained in:
parent
be78597331
commit
5faaddcead
8 changed files with 775 additions and 98 deletions
|
@ -8,7 +8,7 @@ pub use open::MockOpenRepository;
|
|||
|
||||
mod open;
|
||||
mod real;
|
||||
mod test;
|
||||
pub mod test;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
@ -49,8 +49,8 @@ pub fn mock() -> MockRepository {
|
|||
MockRepository::new()
|
||||
}
|
||||
|
||||
pub const fn test(fs: kxio::fs::FileSystem) -> TestRepository {
|
||||
TestRepository::new(false, fs, vec![], vec![])
|
||||
pub fn test(fs: kxio::fs::FileSystem) -> TestRepository {
|
||||
TestRepository::new(false, fs, Default::default(), Default::default())
|
||||
}
|
||||
|
||||
// #[cfg(test)]
|
||||
|
|
|
@ -58,8 +58,8 @@ pub fn real(gix_repo: gix::Repository) -> OpenRepository {
|
|||
pub fn test(
|
||||
gitdir: &config::GitDir,
|
||||
fs: kxio::fs::FileSystem,
|
||||
on_fetch: Vec<otest::OnFetch>,
|
||||
on_push: Vec<otest::OnPush>,
|
||||
on_fetch: Arc<Mutex<Vec<otest::OnFetch>>>,
|
||||
on_push: Arc<Mutex<Vec<otest::OnPush>>>,
|
||||
) -> OpenRepository {
|
||||
OpenRepository::Test(TestOpenRepository::new(gitdir, fs, on_fetch, on_push))
|
||||
}
|
||||
|
@ -68,8 +68,8 @@ pub fn test(
|
|||
pub fn test_bare(
|
||||
gitdir: &config::GitDir,
|
||||
fs: kxio::fs::FileSystem,
|
||||
on_fetch: Vec<otest::OnFetch>,
|
||||
on_push: Vec<otest::OnPush>,
|
||||
on_fetch: Arc<Mutex<Vec<otest::OnFetch>>>,
|
||||
on_push: Arc<Mutex<Vec<otest::OnPush>>>,
|
||||
) -> OpenRepository {
|
||||
OpenRepository::Test(TestOpenRepository::new_bare(gitdir, fs, on_fetch, on_push))
|
||||
}
|
||||
|
|
|
@ -61,9 +61,9 @@ impl OnPush {
|
|||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct TestOpenRepository {
|
||||
on_fetch: Vec<OnFetch>,
|
||||
on_fetch: Arc<Mutex<Vec<OnFetch>>>,
|
||||
fetch_counter: Arc<RwLock<usize>>,
|
||||
on_push: Vec<OnPush>,
|
||||
on_push: Arc<Mutex<Vec<OnPush>>>,
|
||||
push_counter: Arc<RwLock<usize>>,
|
||||
real: git::repository::RealOpenRepository,
|
||||
}
|
||||
|
@ -87,9 +87,14 @@ impl git::repository::OpenRepositoryLike for TestOpenRepository {
|
|||
.write()
|
||||
.map_err(|_| git::fetch::Error::Lock)
|
||||
.map(|mut c| *c += 1)?;
|
||||
self.on_fetch.get(i).map(|f| f.invoke()).unwrap_or_else(|| {
|
||||
unimplemented!("Unexpected fetch");
|
||||
})
|
||||
self.on_fetch
|
||||
.lock()
|
||||
.map_err(|_| git::fetch::Error::Lock)
|
||||
.map(|a| {
|
||||
a.get(i).map(|f| f.invoke()).unwrap_or_else(|| {
|
||||
unimplemented!("Unexpected fetch");
|
||||
})
|
||||
})?
|
||||
}
|
||||
|
||||
fn push(
|
||||
|
@ -110,11 +115,15 @@ impl git::repository::OpenRepositoryLike for TestOpenRepository {
|
|||
.map_err(|_| git::fetch::Error::Lock)
|
||||
.map(|mut c| *c += 1)?;
|
||||
self.on_push
|
||||
.get(i)
|
||||
.map(|f| f.invoke(repo_details, branch_name, to_commit, force))
|
||||
.unwrap_or_else(|| {
|
||||
unimplemented!("Unexpected push");
|
||||
})
|
||||
.lock()
|
||||
.map_err(|_| git::fetch::Error::Lock)
|
||||
.map(|a| {
|
||||
a.get(i)
|
||||
.map(|f| f.invoke(repo_details, branch_name, to_commit, force))
|
||||
.unwrap_or_else(|| {
|
||||
unimplemented!("Unexpected push");
|
||||
})
|
||||
})?
|
||||
}
|
||||
|
||||
fn commit_log(
|
||||
|
@ -137,8 +146,8 @@ impl TestOpenRepository {
|
|||
pub fn new(
|
||||
gitdir: &config::GitDir,
|
||||
fs: kxio::fs::FileSystem,
|
||||
on_fetch: Vec<OnFetch>,
|
||||
on_push: Vec<OnPush>,
|
||||
on_fetch: Arc<Mutex<Vec<OnFetch>>>,
|
||||
on_push: Arc<Mutex<Vec<OnPush>>>,
|
||||
) -> Self {
|
||||
let pathbuf = fs.base().join(gitdir.to_path_buf());
|
||||
#[allow(clippy::expect_used)]
|
||||
|
@ -155,8 +164,8 @@ impl TestOpenRepository {
|
|||
pub fn new_bare(
|
||||
gitdir: &config::GitDir,
|
||||
fs: kxio::fs::FileSystem,
|
||||
on_fetch: Vec<OnFetch>,
|
||||
on_push: Vec<OnPush>,
|
||||
on_fetch: Arc<Mutex<Vec<OnFetch>>>,
|
||||
on_push: Arc<Mutex<Vec<OnPush>>>,
|
||||
) -> Self {
|
||||
let pathbuf = fs.base().join(gitdir.to_path_buf());
|
||||
#[allow(clippy::expect_used)]
|
||||
|
|
|
@ -1,3 +1,5 @@
|
|||
use std::sync::{Arc, Mutex};
|
||||
|
||||
//
|
||||
use derive_more::Constructor;
|
||||
|
||||
|
@ -9,16 +11,16 @@ use git_next_config as config;
|
|||
pub struct TestRepository {
|
||||
is_bare: bool,
|
||||
fs: kxio::fs::FileSystem,
|
||||
on_fetch: Vec<git::repository::open::otest::OnFetch>,
|
||||
on_push: Vec<git::repository::open::otest::OnPush>,
|
||||
on_fetch: Arc<Mutex<Vec<git::repository::open::otest::OnFetch>>>,
|
||||
on_push: Arc<Mutex<Vec<git::repository::open::otest::OnPush>>>,
|
||||
}
|
||||
impl TestRepository {
|
||||
pub fn on_fetch(&mut self, on_fetch: git::repository::OnFetch) {
|
||||
self.on_fetch.push(on_fetch);
|
||||
let _ = self.on_fetch.lock().map(|mut a| a.push(on_fetch));
|
||||
}
|
||||
|
||||
pub fn on_push(&mut self, on_push: git::repository::OnPush) {
|
||||
self.on_push.push(on_push);
|
||||
let _ = self.on_push.lock().map(|mut a| a.push(on_push));
|
||||
}
|
||||
|
||||
pub const fn fs(&self) -> &kxio::fs::FileSystem {
|
||||
|
|
|
@ -42,12 +42,19 @@ ulid = { workspace = true }
|
|||
|
||||
# boilerplate
|
||||
derive_more = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
|
||||
# Actors
|
||||
actix = { workspace = true }
|
||||
actix-rt = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
# Testing
|
||||
assert2 = { workspace = true }
|
||||
rand = { workspace = true }
|
||||
pretty_assertions = { workspace = true }
|
||||
|
||||
[lints.clippy]
|
||||
nursery = { level = "warn", priority = -1 }
|
||||
# pedantic = "warn"
|
||||
|
|
|
@ -1,78 +1,67 @@
|
|||
//
|
||||
use actix::prelude::*;
|
||||
|
||||
use crate as actor;
|
||||
use git_next_config as config;
|
||||
use git_next_git as git;
|
||||
|
||||
use derive_more::Display;
|
||||
use tracing::{info, warn};
|
||||
|
||||
use crate::{MessageToken, ValidateRepo};
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
// advance next to the next commit towards the head of the dev branch
|
||||
#[tracing::instrument(fields(next), skip_all)]
|
||||
pub async fn advance_next(
|
||||
next: git::Commit,
|
||||
dev_commit_history: Vec<git::Commit>,
|
||||
next: &git::Commit,
|
||||
dev_commit_history: &[git::Commit],
|
||||
repo_details: git::RepoDetails,
|
||||
repo_config: config::RepoConfig,
|
||||
repository: git::OpenRepository,
|
||||
addr: Addr<super::RepoActor>,
|
||||
message_token: MessageToken,
|
||||
) {
|
||||
let next_commit = find_next_commit_on_dev(next, dev_commit_history);
|
||||
let Some(commit) = next_commit else {
|
||||
warn!("No commits to advance next to");
|
||||
return;
|
||||
};
|
||||
if let Some(problem) = validate_commit_message(commit.message()) {
|
||||
warn!("Can't advance next to commit '{}': {}", commit, problem);
|
||||
return;
|
||||
}
|
||||
message_token: actor::MessageToken,
|
||||
) -> Result<actor::MessageToken> {
|
||||
let commit =
|
||||
find_next_commit_on_dev(next, dev_commit_history).ok_or_else(|| Error::NextAtDev)?;
|
||||
validate_commit_message(commit.message())?;
|
||||
info!("Advancing next to commit '{}'", commit);
|
||||
if let Err(err) = git::push::reset(
|
||||
git::push::reset(
|
||||
&repository,
|
||||
&repo_details,
|
||||
&repo_config.branches().next(),
|
||||
&commit.into(),
|
||||
&git::push::Force::No,
|
||||
) {
|
||||
warn!(?err, "Failed")
|
||||
}
|
||||
tokio::time::sleep(Duration::from_secs(10)).await;
|
||||
addr.do_send(ValidateRepo { message_token })
|
||||
)?;
|
||||
Ok(message_token)
|
||||
}
|
||||
|
||||
#[tracing::instrument]
|
||||
fn validate_commit_message(message: &git::commit::Message) -> Option<String> {
|
||||
fn validate_commit_message(message: &git::commit::Message) -> Result<()> {
|
||||
let message = &message.to_string();
|
||||
if message.to_ascii_lowercase().starts_with("wip") {
|
||||
return Some("Is Work-In-Progress".to_string());
|
||||
return Err(Error::IsWorkInProgress);
|
||||
}
|
||||
match git_conventional::Commit::parse(message) {
|
||||
Ok(commit) => {
|
||||
info!(?commit, "Pass");
|
||||
None
|
||||
Ok(())
|
||||
}
|
||||
Err(err) => {
|
||||
warn!(?err, "Fail");
|
||||
Some(err.kind().to_string())
|
||||
Err(Error::InvalidCommitMessage {
|
||||
reason: err.kind().to_string(),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn find_next_commit_on_dev(
|
||||
next: git::Commit,
|
||||
dev_commit_history: Vec<git::Commit>,
|
||||
next: &git::Commit,
|
||||
dev_commit_history: &[git::Commit],
|
||||
) -> Option<git::Commit> {
|
||||
let mut next_commit: Option<git::Commit> = None;
|
||||
for commit in dev_commit_history.into_iter() {
|
||||
let mut next_commit: Option<&git::Commit> = None;
|
||||
for commit in dev_commit_history.iter() {
|
||||
if commit == next {
|
||||
break;
|
||||
};
|
||||
next_commit.replace(commit);
|
||||
}
|
||||
next_commit
|
||||
next_commit.cloned()
|
||||
}
|
||||
|
||||
// advance main branch to the commit 'next'
|
||||
|
@ -82,15 +71,30 @@ pub async fn advance_main(
|
|||
repo_details: &git::RepoDetails,
|
||||
repo_config: &config::RepoConfig,
|
||||
repository: &git::OpenRepository,
|
||||
) {
|
||||
) -> Result<()> {
|
||||
info!("Advancing main to next");
|
||||
if let Err(err) = git::push::reset(
|
||||
git::push::reset(
|
||||
repository,
|
||||
repo_details,
|
||||
&repo_config.branches().main(),
|
||||
&next.into(),
|
||||
&git::push::Force::No,
|
||||
) {
|
||||
warn!(?err, "Failed")
|
||||
};
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub type Result<T> = core::result::Result<T, Error>;
|
||||
#[derive(Debug, thiserror::Error, Display)]
|
||||
pub enum Error {
|
||||
#[display("push: {}", 0)]
|
||||
Push(#[from] git::push::Error),
|
||||
|
||||
#[display("no commits to advance next to")]
|
||||
NextAtDev,
|
||||
|
||||
#[display("commit is a Work-in-progress")]
|
||||
IsWorkInProgress,
|
||||
|
||||
#[display("commit message is not in conventional commit format: {reason}")]
|
||||
InvalidCommitMessage { reason: String },
|
||||
}
|
||||
|
|
|
@ -259,15 +259,27 @@ impl Handler<StartMonitoring> for RepoActor {
|
|||
.wait(ctx);
|
||||
} else if dev_ahead_of_next {
|
||||
if let Some(repository) = self.open_repository.clone() {
|
||||
branch::advance_next(
|
||||
msg.next,
|
||||
msg.dev_commit_history,
|
||||
self.repo_details.clone(),
|
||||
repo_config,
|
||||
repository,
|
||||
addr,
|
||||
self.message_token,
|
||||
)
|
||||
let repo_details = self.repo_details.clone();
|
||||
let message_token = self.message_token;
|
||||
async move {
|
||||
match branch::advance_next(
|
||||
&msg.next,
|
||||
&msg.dev_commit_history,
|
||||
repo_details,
|
||||
repo_config,
|
||||
repository,
|
||||
message_token,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(message_token) => {
|
||||
// pause to allow any CI checks to be started
|
||||
tokio::time::sleep(Duration::from_secs(10)).await;
|
||||
addr.do_send(ValidateRepo { message_token })
|
||||
}
|
||||
Err(err) => warn!("advance next: {err}"),
|
||||
}
|
||||
}
|
||||
.in_current_span()
|
||||
.into_actor(self)
|
||||
.wait(ctx);
|
||||
|
@ -312,12 +324,16 @@ impl Handler<AdvanceMainTo> for RepoActor {
|
|||
let addr = ctx.address();
|
||||
let message_token = self.message_token;
|
||||
async move {
|
||||
branch::advance_main(msg.0, &repo_details, &repo_config, &repository).await;
|
||||
match repo_config.source() {
|
||||
git_next_config::RepoConfigSource::Repo => addr.do_send(LoadConfigFromRepo),
|
||||
git_next_config::RepoConfigSource::Server => {
|
||||
addr.do_send(ValidateRepo { message_token })
|
||||
match branch::advance_main(msg.0, &repo_details, &repo_config, &repository).await {
|
||||
Err(err) => {
|
||||
warn!("advance main: {err}");
|
||||
}
|
||||
Ok(_) => match repo_config.source() {
|
||||
git_next_config::RepoConfigSource::Repo => addr.do_send(LoadConfigFromRepo),
|
||||
git_next_config::RepoConfigSource::Server => {
|
||||
addr.do_send(ValidateRepo { message_token })
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
.in_current_span()
|
||||
|
|
|
@ -1,34 +1,673 @@
|
|||
//
|
||||
#![allow(unused_imports)] // TODO remove this
|
||||
|
||||
use crate as actor;
|
||||
use git_next_config as config;
|
||||
use git_next_forge as forge;
|
||||
use git_next_git as git;
|
||||
|
||||
use super::*;
|
||||
|
||||
use assert2::let_assert;
|
||||
|
||||
type TestResult = Result<(), Box<dyn std::error::Error>>;
|
||||
|
||||
mod branch {
|
||||
use super::super::branch::*;
|
||||
use super::*;
|
||||
|
||||
mod advance_next {
|
||||
use super::*;
|
||||
mod when_at_dev {
|
||||
// next and dev branches are the same
|
||||
use super::*;
|
||||
#[tokio::test]
|
||||
async fn should_not_push() -> TestResult {
|
||||
let next = given::a_commit();
|
||||
let dev_commit_history = &[next.clone()];
|
||||
let fs = given::a_filesystem();
|
||||
let repo_details = given::repo_details(&fs);
|
||||
let repo_config = given::a_repo_config();
|
||||
let (repository, _, _) = given::an_open_repository(&fs);
|
||||
// no on_push defined - so any call to push will cause an error
|
||||
let message_token = given::a_message_token();
|
||||
let_assert!(
|
||||
Err(err) = actor::branch::advance_next(
|
||||
&next,
|
||||
dev_commit_history,
|
||||
repo_details,
|
||||
repo_config,
|
||||
repository,
|
||||
message_token,
|
||||
)
|
||||
.await
|
||||
);
|
||||
eprintln!("Got: {err}");
|
||||
assert!(matches!(err, actor::branch::Error::NextAtDev));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
mod can_advance {
|
||||
// dev has at least one commit ahead of next
|
||||
use super::*;
|
||||
mod to_wip_commit {
|
||||
// commit on dev is either invalid message or a WIP
|
||||
use super::*;
|
||||
#[tokio::test]
|
||||
async fn should_not_push() -> TestResult {
|
||||
let next = given::a_commit();
|
||||
let dev = given::a_commit_with_message(&git::commit::Message::new(
|
||||
"wip: test: message".to_string(),
|
||||
));
|
||||
let dev_commit_history = &[dev.clone(), next.clone()];
|
||||
let fs = given::a_filesystem();
|
||||
let repo_details = given::repo_details(&fs);
|
||||
let repo_config = given::a_repo_config();
|
||||
let (repository, _, _) = given::an_open_repository(&fs);
|
||||
// no on_push defined - so any call to push will cause an error
|
||||
let message_token = given::a_message_token();
|
||||
let_assert!(
|
||||
Err(err) = actor::branch::advance_next(
|
||||
&next,
|
||||
dev_commit_history,
|
||||
repo_details,
|
||||
repo_config,
|
||||
repository,
|
||||
message_token,
|
||||
)
|
||||
.await
|
||||
);
|
||||
eprintln!("Got: {err}");
|
||||
assert!(matches!(err, actor::branch::Error::IsWorkInProgress));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
mod to_invalid_commit {
|
||||
// commit on dev is either invalid message or a WIP
|
||||
use super::*;
|
||||
#[tokio::test]
|
||||
async fn should_not_push_and_error() -> TestResult {
|
||||
let next = given::a_commit();
|
||||
let dev = given::a_commit();
|
||||
let dev_commit_history = &[dev.clone(), next.clone()];
|
||||
let fs = given::a_filesystem();
|
||||
let repo_details = given::repo_details(&fs);
|
||||
let repo_config = given::a_repo_config();
|
||||
let (repository, _, _) = given::an_open_repository(&fs);
|
||||
// no on_push defined - so any call to push will cause an error
|
||||
let message_token = given::a_message_token();
|
||||
let_assert!(
|
||||
Err(err) = actor::branch::advance_next(
|
||||
&next,
|
||||
dev_commit_history,
|
||||
repo_details,
|
||||
repo_config,
|
||||
repository,
|
||||
message_token,
|
||||
)
|
||||
.await
|
||||
);
|
||||
eprintln!("Got: {err}");
|
||||
assert!(matches!(
|
||||
err,
|
||||
actor::branch::Error::InvalidCommitMessage{reason}
|
||||
if reason == "Missing type in the commit summary, expected `type: description`"
|
||||
));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
mod to_valid_commit {
|
||||
// commit on dev is valid conventional commit message
|
||||
use super::*;
|
||||
mod push_is_err {
|
||||
use git::repository::{OnFetch, OnPush};
|
||||
|
||||
// the git push command fails
|
||||
use super::*;
|
||||
#[tokio::test]
|
||||
async fn should_error() -> TestResult {
|
||||
let next = given::a_commit();
|
||||
let dev = given::a_commit_with_message(&git::commit::Message::new(
|
||||
"test: message".to_string(),
|
||||
));
|
||||
let dev_commit_history = &[dev.clone(), next.clone()];
|
||||
let fs = given::a_filesystem();
|
||||
let repo_details = given::repo_details(&fs);
|
||||
let repo_config = given::a_repo_config();
|
||||
let (repository, gitdir, mut test_repository) =
|
||||
given::an_open_repository(&fs);
|
||||
let repo_branches = repo_config.branches();
|
||||
test_repository.on_fetch(OnFetch::new(
|
||||
repo_branches.clone(),
|
||||
gitdir.clone(),
|
||||
fs.clone(),
|
||||
|_, _, _| git::fetch::Result::Ok(()),
|
||||
));
|
||||
test_repository.on_push(OnPush::new(
|
||||
repo_branches.clone(),
|
||||
gitdir,
|
||||
fs,
|
||||
|_, _, _, _, _, _, _| git::push::Result::Err(git::push::Error::Lock),
|
||||
));
|
||||
let message_token = given::a_message_token();
|
||||
let_assert!(
|
||||
Err(err) = actor::branch::advance_next(
|
||||
&next,
|
||||
dev_commit_history,
|
||||
repo_details,
|
||||
repo_config,
|
||||
repository,
|
||||
message_token,
|
||||
)
|
||||
.await
|
||||
);
|
||||
eprintln!("Got: {err:?}");
|
||||
assert!(matches!(
|
||||
err,
|
||||
actor::branch::Error::Push(git::push::Error::Lock)
|
||||
));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
mod push_is_ok {
|
||||
// the git push command succeeds
|
||||
use git_next_git::repository::{OnFetch, OnPush};
|
||||
|
||||
// the git push command fails
|
||||
use super::*;
|
||||
#[tokio::test]
|
||||
async fn should_ok() -> TestResult {
|
||||
let next = given::a_commit();
|
||||
let dev = given::a_commit_with_message(&git::commit::Message::new(
|
||||
"test: message".to_string(),
|
||||
));
|
||||
let dev_commit_history = &[dev.clone(), next.clone()];
|
||||
let fs = given::a_filesystem();
|
||||
let repo_details = given::repo_details(&fs);
|
||||
let repo_config = given::a_repo_config();
|
||||
let (repository, gitdir, mut test_repository) =
|
||||
given::an_open_repository(&fs);
|
||||
let repo_branches = repo_config.branches();
|
||||
test_repository.on_fetch(OnFetch::new(
|
||||
repo_branches.clone(),
|
||||
gitdir.clone(),
|
||||
fs.clone(),
|
||||
|_, _, _| git::fetch::Result::Ok(()),
|
||||
));
|
||||
test_repository.on_push(OnPush::new(
|
||||
repo_branches.clone(),
|
||||
gitdir,
|
||||
fs,
|
||||
|_, _, _, _, _, _, _| git::push::Result::Ok(()),
|
||||
));
|
||||
let message_token = given::a_message_token();
|
||||
let_assert!(
|
||||
Ok(mt) = actor::branch::advance_next(
|
||||
&next,
|
||||
dev_commit_history,
|
||||
repo_details,
|
||||
repo_config,
|
||||
repository,
|
||||
message_token,
|
||||
)
|
||||
.await
|
||||
);
|
||||
eprintln!("Got: {mt:?}");
|
||||
assert_eq!(mt, message_token);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
mod advance_main {
|
||||
use git::repository::{OnFetch, OnPush};
|
||||
|
||||
use super::*;
|
||||
#[tokio::test]
|
||||
async fn push_is_error_should_error() {
|
||||
let commit = given::a_commit();
|
||||
let fs = given::a_filesystem();
|
||||
let repo_details = given::repo_details(&fs);
|
||||
let repo_config = given::a_repo_config();
|
||||
let (open_repository, gitdir, mut test_repository) = given::an_open_repository(&fs);
|
||||
let repo_branches = repo_config.branches();
|
||||
test_repository.on_fetch(OnFetch::new(
|
||||
repo_branches.clone(),
|
||||
gitdir.clone(),
|
||||
fs.clone(),
|
||||
|_, _, _| git::fetch::Result::Ok(()),
|
||||
));
|
||||
test_repository.on_push(OnPush::new(
|
||||
repo_branches.clone(),
|
||||
gitdir,
|
||||
fs,
|
||||
|_, _, _, _, _, _, _| git::push::Result::Err(git::push::Error::Lock),
|
||||
));
|
||||
let_assert!(
|
||||
Err(err) = actor::branch::advance_main(
|
||||
commit,
|
||||
&repo_details,
|
||||
&repo_config,
|
||||
&open_repository
|
||||
)
|
||||
.await
|
||||
);
|
||||
assert!(matches!(
|
||||
err,
|
||||
actor::branch::Error::Push(git::push::Error::Lock)
|
||||
));
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn push_is_ok_should_ok() {
|
||||
let commit = given::a_commit();
|
||||
let fs = given::a_filesystem();
|
||||
let repo_details = given::repo_details(&fs);
|
||||
let repo_config = given::a_repo_config();
|
||||
let (open_repository, gitdir, mut test_repository) = given::an_open_repository(&fs);
|
||||
let repo_branches = repo_config.branches();
|
||||
test_repository.on_fetch(OnFetch::new(
|
||||
repo_branches.clone(),
|
||||
gitdir.clone(),
|
||||
fs.clone(),
|
||||
|_, _, _| git::fetch::Result::Ok(()),
|
||||
));
|
||||
test_repository.on_push(OnPush::new(
|
||||
repo_branches.clone(),
|
||||
gitdir,
|
||||
fs,
|
||||
|_, _, _, _, _, _, _| git::push::Result::Ok(()),
|
||||
));
|
||||
let_assert!(
|
||||
Ok(_) = actor::branch::advance_main(
|
||||
commit,
|
||||
&repo_details,
|
||||
&repo_config,
|
||||
&open_repository
|
||||
)
|
||||
.await
|
||||
);
|
||||
}
|
||||
}
|
||||
#[actix_rt::test]
|
||||
async fn test_find_next_commit_on_dev() {
|
||||
let next = git::Commit::new(
|
||||
git::commit::Sha::new("current-next".to_string()),
|
||||
git::commit::Message::new("foo".to_string()),
|
||||
);
|
||||
let expected = git::Commit::new(
|
||||
git::commit::Sha::new("dev-next".to_string()),
|
||||
git::commit::Message::new("next-should-go-here".to_string()),
|
||||
);
|
||||
let next = given::a_commit();
|
||||
let expected = given::a_commit();
|
||||
let dev_commit_history = vec![
|
||||
git::Commit::new(
|
||||
git::commit::Sha::new("dev".to_string()),
|
||||
git::commit::Message::new("future".to_string()),
|
||||
),
|
||||
given::a_commit(), // dev HEAD
|
||||
expected.clone(),
|
||||
next.clone(),
|
||||
git::Commit::new(
|
||||
git::commit::Sha::new("current-main".to_string()),
|
||||
git::commit::Message::new("history".to_string()),
|
||||
),
|
||||
next.clone(), // next - advancing towards dev HEAD
|
||||
given::a_commit(), // parent of next
|
||||
];
|
||||
|
||||
let next_commit = find_next_commit_on_dev(next, dev_commit_history);
|
||||
let next_commit = actor::branch::find_next_commit_on_dev(&next, &dev_commit_history);
|
||||
|
||||
assert_eq!(next_commit, Some(expected), "Found the wrong commit");
|
||||
}
|
||||
}
|
||||
pub mod given {
|
||||
#![allow(dead_code)] // TODO: remove this
|
||||
#![allow(unused_imports)] // TODO: remove this
|
||||
|
||||
use git_next_git::repository::RepositoryLike as _;
|
||||
use rand::RngCore;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use super::*;
|
||||
use config::{
|
||||
BranchName, ForgeAlias, ForgeConfig, ForgeType, GitDir, RepoAlias, RepoBranches,
|
||||
RepoConfig, ServerRepoConfig, WebhookAuth, WebhookId,
|
||||
};
|
||||
use git::RepoDetails;
|
||||
|
||||
pub fn a_webhook_auth() -> WebhookAuth {
|
||||
WebhookAuth::generate()
|
||||
}
|
||||
|
||||
pub enum Header {
|
||||
Valid(WebhookAuth, config::webhook::message::Body),
|
||||
Missing,
|
||||
Invalid,
|
||||
}
|
||||
|
||||
pub fn a_webhook_message_body() -> config::webhook::message::Body {
|
||||
config::webhook::message::Body::new(a_name())
|
||||
}
|
||||
|
||||
pub fn repo_branches() -> RepoBranches {
|
||||
RepoBranches::new(
|
||||
format!("main-{}", a_name()),
|
||||
format!("next-{}", a_name()),
|
||||
format!("dev-{}", a_name()),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn a_forge_alias() -> ForgeAlias {
|
||||
ForgeAlias::new(a_name())
|
||||
}
|
||||
|
||||
pub fn a_repo_alias() -> RepoAlias {
|
||||
RepoAlias::new(a_name())
|
||||
}
|
||||
|
||||
pub fn a_network() -> kxio::network::MockNetwork {
|
||||
kxio::network::MockNetwork::new()
|
||||
}
|
||||
|
||||
pub fn a_webhook_url(
|
||||
forge_alias: &ForgeAlias,
|
||||
repo_alias: &RepoAlias,
|
||||
) -> git_next_config::server::WebhookUrl {
|
||||
config::server::Webhook::new(a_name()).url(forge_alias, repo_alias)
|
||||
}
|
||||
|
||||
pub fn any_webhook_url() -> git_next_config::server::WebhookUrl {
|
||||
a_webhook_url(&a_forge_alias(), &a_repo_alias())
|
||||
}
|
||||
|
||||
pub fn a_pathbuf() -> PathBuf {
|
||||
PathBuf::from(given::a_name())
|
||||
}
|
||||
|
||||
pub fn a_name() -> String {
|
||||
use rand::Rng;
|
||||
use std::iter;
|
||||
|
||||
fn generate(len: usize) -> String {
|
||||
const CHARSET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
|
||||
let mut rng = rand::thread_rng();
|
||||
let one_char = || CHARSET[rng.gen_range(0..CHARSET.len())] as char;
|
||||
iter::repeat_with(one_char).take(len).collect()
|
||||
}
|
||||
generate(5)
|
||||
}
|
||||
|
||||
pub fn a_webhook_id() -> WebhookId {
|
||||
WebhookId::new(a_name())
|
||||
}
|
||||
|
||||
pub fn a_github_webhook_id() -> i64 {
|
||||
rand::thread_rng().next_u32().into()
|
||||
}
|
||||
|
||||
pub fn a_branch_name() -> BranchName {
|
||||
BranchName::new(a_name())
|
||||
}
|
||||
|
||||
pub fn a_git_dir(fs: &kxio::fs::FileSystem) -> GitDir {
|
||||
let dir_name = a_name();
|
||||
let dir = fs.base().join(dir_name);
|
||||
GitDir::new(&dir)
|
||||
}
|
||||
|
||||
pub fn a_forge_config() -> ForgeConfig {
|
||||
ForgeConfig::new(
|
||||
ForgeType::MockForge,
|
||||
a_name(),
|
||||
a_name(),
|
||||
a_name(),
|
||||
Default::default(), // no repos
|
||||
)
|
||||
}
|
||||
|
||||
pub fn a_server_repo_config() -> ServerRepoConfig {
|
||||
let main = a_branch_name().into_string();
|
||||
let next = a_branch_name().into_string();
|
||||
let dev = a_branch_name().into_string();
|
||||
ServerRepoConfig::new(
|
||||
format!("{}/{}", a_name(), a_name()),
|
||||
main.clone(),
|
||||
None,
|
||||
Some(main),
|
||||
Some(next),
|
||||
Some(dev),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn a_repo_config() -> RepoConfig {
|
||||
RepoConfig::new(given::repo_branches(), config::RepoConfigSource::Repo)
|
||||
}
|
||||
|
||||
pub fn a_commit() -> git::Commit {
|
||||
git::Commit::new(a_commit_sha(), a_commit_message())
|
||||
}
|
||||
|
||||
pub fn a_commit_with_message(message: &git::commit::Message) -> git::Commit {
|
||||
git::Commit::new(a_commit_sha(), message.to_owned())
|
||||
}
|
||||
|
||||
pub fn a_commit_with_sha(sha: &git::commit::Sha) -> git::Commit {
|
||||
git::Commit::new(sha.to_owned(), a_commit_message())
|
||||
}
|
||||
|
||||
pub fn a_commit_with(sha: &git::commit::Sha, message: &git::commit::Message) -> git::Commit {
|
||||
git::Commit::new(sha.to_owned(), message.to_owned())
|
||||
}
|
||||
|
||||
pub fn a_commit_message() -> git::commit::Message {
|
||||
git::commit::Message::new(a_name())
|
||||
}
|
||||
|
||||
pub fn a_commit_sha() -> git::commit::Sha {
|
||||
git::commit::Sha::new(a_name())
|
||||
}
|
||||
|
||||
pub fn a_webhook_push(
|
||||
sha: &git::commit::Sha,
|
||||
message: &git::commit::Message,
|
||||
) -> config::webhook::Push {
|
||||
let branch = a_branch_name();
|
||||
config::webhook::Push::new(branch, sha.to_string(), message.to_string())
|
||||
}
|
||||
|
||||
pub fn a_filesystem() -> kxio::fs::FileSystem {
|
||||
kxio::fs::temp().unwrap_or_else(|e| panic!("{}", e))
|
||||
}
|
||||
|
||||
pub fn repo_details(fs: &kxio::fs::FileSystem) -> git::RepoDetails {
|
||||
let generation = git::Generation::new();
|
||||
let repo_alias = a_repo_alias();
|
||||
let server_repo_config = a_server_repo_config();
|
||||
let forge_alias = a_forge_alias();
|
||||
let forge_config = a_forge_config();
|
||||
let gitdir = a_git_dir(fs);
|
||||
RepoDetails::new(
|
||||
generation,
|
||||
&repo_alias,
|
||||
&server_repo_config,
|
||||
&forge_alias,
|
||||
&forge_config,
|
||||
gitdir,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn an_open_repository(
|
||||
fs: &kxio::fs::FileSystem,
|
||||
) -> (
|
||||
git::repository::OpenRepository,
|
||||
GitDir,
|
||||
git::repository::test::TestRepository,
|
||||
) {
|
||||
#![allow(clippy::expect_used)]
|
||||
let gitdir = a_git_dir(fs);
|
||||
let repo = git::repository::test(fs.clone());
|
||||
let or = repo.open(&gitdir).expect("open repo");
|
||||
(or, gitdir, repo)
|
||||
}
|
||||
|
||||
pub fn a_message_token() -> MessageToken {
|
||||
MessageToken::new()
|
||||
}
|
||||
}
|
||||
pub mod then {
|
||||
#![allow(dead_code)] // TODO: remove this
|
||||
#![allow(unused_imports)] // TODO: remove this
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
type TestResult = Result<(), Box<dyn std::error::Error>>;
|
||||
|
||||
use super::*;
|
||||
|
||||
pub fn commit_named_file_to_branch(
|
||||
file_name: &Path,
|
||||
contents: &str,
|
||||
fs: &kxio::fs::FileSystem,
|
||||
gitdir: &config::GitDir,
|
||||
branch_name: &config::BranchName,
|
||||
) -> TestResult {
|
||||
// git checkout ${branch_name}
|
||||
git_checkout_new_branch(branch_name, gitdir)?;
|
||||
// echo ${word} > file-${word}
|
||||
let pathbuf = PathBuf::from(gitdir);
|
||||
let file = fs.base().join(pathbuf).join(file_name);
|
||||
#[allow(clippy::expect_used)]
|
||||
fs.file_write(&file, contents)?;
|
||||
// git add ${file}
|
||||
git_add_file(gitdir, &file)?;
|
||||
// git commit -m"Added ${file}"
|
||||
git_commit(gitdir, &file)?;
|
||||
|
||||
then::push_branch(fs, gitdir, branch_name)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn create_a_commit_on_branch(
|
||||
fs: &kxio::fs::FileSystem,
|
||||
gitdir: &config::GitDir,
|
||||
branch_name: &config::BranchName,
|
||||
) -> TestResult {
|
||||
// git checkout ${branch_name}
|
||||
git_checkout_new_branch(branch_name, gitdir)?;
|
||||
// echo ${word} > file-${word}
|
||||
let word = given::a_name();
|
||||
let pathbuf = PathBuf::from(gitdir);
|
||||
let file = fs.base().join(pathbuf).join(&word);
|
||||
fs.file_write(&file, &word)?;
|
||||
// git add ${file}
|
||||
git_add_file(gitdir, &file)?;
|
||||
// git commit -m"Added ${file}"
|
||||
git_commit(gitdir, &file)?;
|
||||
|
||||
then::push_branch(fs, gitdir, branch_name)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn push_branch(
|
||||
fs: &kxio::fs::FileSystem,
|
||||
gitdir: &config::GitDir,
|
||||
branch_name: &config::BranchName,
|
||||
) -> TestResult {
|
||||
let gitrefs = fs
|
||||
.base()
|
||||
.join(gitdir.to_path_buf())
|
||||
.join(".git")
|
||||
.join("refs");
|
||||
let local_branch = gitrefs.join("heads").join(branch_name.to_string().as_str());
|
||||
let origin_heads = gitrefs.join("remotes").join("origin");
|
||||
let remote_branch = origin_heads.join(branch_name.to_string().as_str());
|
||||
let contents = fs.file_read_to_string(&local_branch)?;
|
||||
fs.dir_create_all(&origin_heads)?;
|
||||
fs.file_write(&remote_branch, &contents)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn git_checkout_new_branch(
|
||||
branch_name: &git_next_config::BranchName,
|
||||
gitdir: &git_next_config::GitDir,
|
||||
) -> TestResult {
|
||||
exec(
|
||||
format!("git checkout -b {}", branch_name),
|
||||
std::process::Command::new("/usr/bin/git")
|
||||
.current_dir(gitdir.to_path_buf())
|
||||
.args(["checkout", "-b", branch_name.to_string().as_str()])
|
||||
.output(),
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn git_switch(
|
||||
branch_name: &git_next_config::BranchName,
|
||||
gitdir: &git_next_config::GitDir,
|
||||
) -> TestResult {
|
||||
exec(
|
||||
format!("git switch {}", branch_name),
|
||||
std::process::Command::new("/usr/bin/git")
|
||||
.current_dir(gitdir.to_path_buf())
|
||||
.args(["switch", branch_name.to_string().as_str()])
|
||||
.output(),
|
||||
)
|
||||
}
|
||||
|
||||
fn exec(label: String, output: Result<std::process::Output, std::io::Error>) -> TestResult {
|
||||
eprintln!("== {label}");
|
||||
match output {
|
||||
Ok(output) => {
|
||||
eprintln!(
|
||||
"\nstdout:\n{}",
|
||||
String::from_utf8_lossy(output.stdout.as_slice())
|
||||
);
|
||||
eprintln!(
|
||||
"\nstderr:\n{}",
|
||||
String::from_utf8_lossy(output.stderr.as_slice())
|
||||
);
|
||||
eprintln!("=============================");
|
||||
Ok(())
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!("ERROR: {err:#?}");
|
||||
Ok(Err(err)?)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn git_add_file(gitdir: &git_next_config::GitDir, file: &Path) -> TestResult {
|
||||
exec(
|
||||
format!("git add {file:?}"),
|
||||
std::process::Command::new("/usr/bin/git")
|
||||
.current_dir(gitdir.to_path_buf())
|
||||
.args(["add", file.display().to_string().as_str()])
|
||||
.output(),
|
||||
)
|
||||
}
|
||||
|
||||
fn git_commit(gitdir: &git_next_config::GitDir, file: &Path) -> TestResult {
|
||||
exec(
|
||||
format!(r#"git commit -m"Added {file:?}""#),
|
||||
std::process::Command::new("/usr/bin/git")
|
||||
.current_dir(gitdir.to_path_buf())
|
||||
.args([
|
||||
"commit",
|
||||
format!(r#"-m"Added {}"#, file.display().to_string().as_str()).as_str(),
|
||||
])
|
||||
.output(),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn git_log_all(gitdir: &config::GitDir) -> TestResult {
|
||||
exec(
|
||||
"git log --all --oneline --decorate --graph".to_string(),
|
||||
std::process::Command::new("/usr/bin/git")
|
||||
.current_dir(gitdir.to_path_buf())
|
||||
.args(["log", "--all", "--oneline", "--decorate", "--graph"])
|
||||
.output(),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn get_sha_for_branch(
|
||||
fs: &kxio::fs::FileSystem,
|
||||
gitdir: &git_next_config::GitDir,
|
||||
branch_name: &git_next_config::BranchName,
|
||||
) -> Result<git::commit::Sha, Box<dyn std::error::Error>> {
|
||||
let main_ref = fs
|
||||
.base()
|
||||
.join(gitdir.to_path_buf())
|
||||
.join(".git")
|
||||
.join("refs")
|
||||
.join("heads")
|
||||
.join(branch_name.to_string().as_str());
|
||||
let sha = fs.file_read_to_string(&main_ref)?;
|
||||
Ok(git::commit::Sha::new(sha.trim().to_string()))
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue