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

This commit is contained in:
Paul Campbell 2024-06-14 09:26:27 +01:00
parent 2e71e40378
commit 6298440add
33 changed files with 1565 additions and 496 deletions

View file

@ -1,35 +1,10 @@
// //
#[macro_export] #[macro_export]
macro_rules! newtype { macro_rules! newtype {
($name:ident is a $type:ty, without Display) => { ($name:ident) => {
#[derive(
Clone,
Default,
Debug,
derive_more::From,
PartialEq,
Eq,
PartialOrd,
Ord,
Hash,
derive_more::AsRef,
derive_more::Deref,
serde::Deserialize,
serde::Serialize,
)]
pub struct $name($type);
impl $name {
pub fn new(value: impl Into<$type>) -> Self {
Self(value.into())
}
pub fn unwrap(self) -> $type {
self.0
}
}
};
($name:ident is a $type:ty) => {
#[derive( #[derive(
Clone, Clone,
Copy,
Default, Default,
Debug, Debug,
derive_more::Display, derive_more::Display,
@ -40,18 +15,67 @@ macro_rules! newtype {
Ord, Ord,
Hash, Hash,
derive_more::AsRef, derive_more::AsRef,
// serde::Deserialize,
// serde::Serialize,
)]
pub struct $name;
impl $name {
pub fn new() -> Self {
Self
}
}
};
($name:ident is a $type:ty $(, $derive:ty)*) => {
#[derive(
Clone,
Debug,
derive_more::From,
PartialEq,
Eq,
PartialOrd,
Ord,
Hash,
derive_more::AsRef,
derive_more::Deref, derive_more::Deref,
serde::Deserialize, // serde::Deserialize,
serde::Serialize, // serde::Serialize,
$($derive),*
)] )]
pub struct $name($type); pub struct $name($type);
impl $name { impl $name {
pub fn new(value: impl Into<$type>) -> Self { pub fn new(value: impl Into<$type>) -> Self {
Self(value.into()) Self(value.into())
} }
#[allow(clippy::missing_const_for_fn)]
pub fn unwrap(self) -> $type { pub fn unwrap(self) -> $type {
self.0 self.0
} }
} }
}; };
// ($name:ident is a $type:ty, without Display) => {
// #[derive(
// Clone,
// Default,
// Debug,
// derive_more::From,
// PartialEq,
// Eq,
// PartialOrd,
// Ord,
// Hash,
// derive_more::AsRef,
// derive_more::Deref,
// serde::Deserialize,
// serde::Serialize,
// )]
// pub struct $name($type);
// impl $name {
// pub fn new(value: impl Into<$type>) -> Self {
// Self(value.into())
// }
// pub fn unwrap(self) -> $type {
// self.0
// }
// }
// };
} }

View file

@ -2,7 +2,17 @@ use crate::BranchName;
/// Mapped from `.git-next.toml` file at `branches` /// Mapped from `.git-next.toml` file at `branches`
#[derive( #[derive(
Clone, Debug, PartialEq, Eq, serde::Deserialize, derive_more::Constructor, derive_more::Display, Clone,
Hash,
Debug,
PartialEq,
Eq,
PartialOrd,
Ord,
serde::Deserialize,
serde::Serialize,
derive_more::Constructor,
derive_more::Display,
)] )]
#[display("{},{},{}", main, next, dev)] #[display("{},{},{}", main, next, dev)]
pub struct RepoBranches { pub struct RepoBranches {

View file

@ -5,7 +5,17 @@ use crate::RepoConfigSource;
/// Is also derived from the optional parameters in `git-next-server.toml` at /// Is also derived from the optional parameters in `git-next-server.toml` at
/// `forge.{forge}.repos.{repo}.(main|next|dev)` /// `forge.{forge}.repos.{repo}.(main|next|dev)`
#[derive( #[derive(
Clone, Debug, PartialEq, Eq, serde::Deserialize, derive_more::Constructor, derive_more::Display, Clone,
Hash,
Debug,
PartialEq,
Eq,
PartialOrd,
Ord,
serde::Deserialize,
serde::Serialize,
derive_more::Constructor,
derive_more::Display,
)] )]
#[display("{}", branches)] #[display("{}", branches)]
pub struct RepoConfig { pub struct RepoConfig {
@ -13,7 +23,7 @@ pub struct RepoConfig {
source: RepoConfigSource, source: RepoConfigSource,
} }
impl RepoConfig { impl RepoConfig {
pub fn load(toml: &str) -> Result<Self, toml::de::Error> { pub fn parse(toml: &str) -> Result<Self, toml::de::Error> {
toml::from_str(format!("source = \"Repo\"\n{}", toml).as_str()) toml::from_str(format!("source = \"Repo\"\n{}", toml).as_str())
} }

View file

@ -1,4 +1,6 @@
#[derive(Copy, Clone, Debug, PartialEq, Eq, serde::Deserialize)] #[derive(
Copy, Hash, Clone, Debug, PartialEq, Eq, serde::Deserialize, PartialOrd, Ord, serde::Serialize,
)]
pub enum RepoConfigSource { pub enum RepoConfigSource {
Repo, Repo,
Server, Server,

View file

@ -110,7 +110,7 @@ mod repo_config {
"# "#
); );
let rc = RepoConfig::load(toml.as_str())?; let rc = RepoConfig::parse(toml.as_str())?;
assert_eq!( assert_eq!(
rc, rc,

View file

@ -1,7 +1,7 @@
#[derive(Clone, Debug, PartialEq, Eq, derive_more::Deref, derive_more::Display)] //
pub struct WebhookAuth(ulid::Ulid); crate::newtype!(WebhookAuth is a ulid::Ulid, derive_more::Display);
impl WebhookAuth { impl WebhookAuth {
pub fn new(authorisation: &str) -> Result<Self, ulid::DecodeError> { pub fn try_new(authorisation: &str) -> Result<Self, ulid::DecodeError> {
use std::str::FromStr as _; use std::str::FromStr as _;
let id = ulid::Ulid::from_str(authorisation)?; let id = ulid::Ulid::from_str(authorisation)?;
tracing::info!("Parse auth token: {}", id); tracing::info!("Parse auth token: {}", id);

View file

@ -1,4 +1,2 @@
use derive_more::{Constructor, Deref, Display}; //
crate::newtype!(WebhookId is a String, derive_more::Display);
#[derive(Clone, Debug, PartialEq, Eq, Constructor, Deref, Display)]
pub struct WebhookId(String);

View file

@ -5,7 +5,7 @@ mod auth {
fn bytes() -> Result<(), Box<dyn std::error::Error>> { fn bytes() -> Result<(), Box<dyn std::error::Error>> {
let ulid = ulid::Ulid::new(); let ulid = ulid::Ulid::new();
let wa = WebhookAuth::new(ulid.to_string().as_str())?; let wa = WebhookAuth::try_new(ulid.to_string().as_str())?;
assert_eq!(ulid.to_bytes(), wa.to_bytes()); assert_eq!(ulid.to_bytes(), wa.to_bytes());
@ -16,7 +16,7 @@ mod auth {
fn string() -> Result<(), Box<dyn std::error::Error>> { fn string() -> Result<(), Box<dyn std::error::Error>> {
let ulid = ulid::Ulid::new(); let ulid = ulid::Ulid::new();
let wa = WebhookAuth::new(ulid.to_string().as_str())?; let wa = WebhookAuth::try_new(ulid.to_string().as_str())?;
assert_eq!(ulid.to_string(), wa.to_string()); assert_eq!(ulid.to_string(), wa.to_string());

View file

@ -36,7 +36,7 @@ impl git::ForgeLike for ForgeJo {
tracing::info!(?authorization, %expected, "is message authorised?"); tracing::info!(?authorization, %expected, "is message authorised?");
authorization authorization
.and_then(|header| header.strip_prefix("Basic ").map(|v| v.to_owned())) .and_then(|header| header.strip_prefix("Basic ").map(|v| v.to_owned()))
.and_then(|value| config::WebhookAuth::new(value.as_str()).ok()) .and_then(|value| config::WebhookAuth::try_new(value.as_str()).ok())
.map(|auth| &auth == expected) .map(|auth| &auth == expected)
.unwrap_or(false) .unwrap_or(false)
} }

View file

@ -1,7 +1,19 @@
use config::newtype;
use derive_more::Display;
// //
use git_next_config as config; use git_next_config as config;
#[derive(Clone, Debug, PartialEq, Eq, derive_more::Constructor, derive_more::Display)] #[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
PartialOrd,
Ord,
derive_more::Constructor,
derive_more::Display,
)]
#[display("{}", sha)] #[display("{}", sha)]
pub struct Commit { pub struct Commit {
sha: Sha, sha: Sha,
@ -25,11 +37,8 @@ impl From<config::webhook::Push> for Commit {
} }
} }
#[derive(Clone, Debug, PartialEq, Eq, derive_more::Constructor, derive_more::Display)] newtype!(Sha is a String, Display);
pub struct Sha(String); newtype!(Message is a String);
#[derive(Clone, Debug, PartialEq, Eq, derive_more::Constructor, derive_more::Display)]
pub struct Message(String);
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct Histories { pub struct Histories {

View file

@ -8,7 +8,7 @@ pub use open::MockOpenRepository;
mod open; mod open;
mod real; mod real;
mod test; pub mod test;
#[cfg(test)] #[cfg(test)]
mod tests; mod tests;
@ -49,8 +49,8 @@ pub fn mock() -> MockRepository {
MockRepository::new() MockRepository::new()
} }
pub const fn test(fs: kxio::fs::FileSystem) -> TestRepository { pub fn test(fs: kxio::fs::FileSystem) -> TestRepository {
TestRepository::new(false, fs, vec![], vec![]) TestRepository::new(false, fs, Default::default(), Default::default())
} }
// #[cfg(test)] // #[cfg(test)]

View file

@ -58,8 +58,8 @@ pub fn real(gix_repo: gix::Repository) -> OpenRepository {
pub fn test( pub fn test(
gitdir: &config::GitDir, gitdir: &config::GitDir,
fs: kxio::fs::FileSystem, fs: kxio::fs::FileSystem,
on_fetch: Vec<otest::OnFetch>, on_fetch: Arc<Mutex<Vec<otest::OnFetch>>>,
on_push: Vec<otest::OnPush>, on_push: Arc<Mutex<Vec<otest::OnPush>>>,
) -> OpenRepository { ) -> OpenRepository {
OpenRepository::Test(TestOpenRepository::new(gitdir, fs, on_fetch, on_push)) OpenRepository::Test(TestOpenRepository::new(gitdir, fs, on_fetch, on_push))
} }
@ -68,8 +68,8 @@ pub fn test(
pub fn test_bare( pub fn test_bare(
gitdir: &config::GitDir, gitdir: &config::GitDir,
fs: kxio::fs::FileSystem, fs: kxio::fs::FileSystem,
on_fetch: Vec<otest::OnFetch>, on_fetch: Arc<Mutex<Vec<otest::OnFetch>>>,
on_push: Vec<otest::OnPush>, on_push: Arc<Mutex<Vec<otest::OnPush>>>,
) -> OpenRepository { ) -> OpenRepository {
OpenRepository::Test(TestOpenRepository::new_bare(gitdir, fs, on_fetch, on_push)) OpenRepository::Test(TestOpenRepository::new_bare(gitdir, fs, on_fetch, on_push))
} }

View file

@ -61,9 +61,9 @@ impl OnPush {
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct TestOpenRepository { pub struct TestOpenRepository {
on_fetch: Vec<OnFetch>, on_fetch: Arc<Mutex<Vec<OnFetch>>>,
fetch_counter: Arc<RwLock<usize>>, fetch_counter: Arc<RwLock<usize>>,
on_push: Vec<OnPush>, on_push: Arc<Mutex<Vec<OnPush>>>,
push_counter: Arc<RwLock<usize>>, push_counter: Arc<RwLock<usize>>,
real: git::repository::RealOpenRepository, real: git::repository::RealOpenRepository,
} }
@ -87,9 +87,14 @@ impl git::repository::OpenRepositoryLike for TestOpenRepository {
.write() .write()
.map_err(|_| git::fetch::Error::Lock) .map_err(|_| git::fetch::Error::Lock)
.map(|mut c| *c += 1)?; .map(|mut c| *c += 1)?;
self.on_fetch.get(i).map(|f| f.invoke()).unwrap_or_else(|| { self.on_fetch
unimplemented!("Unexpected 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( fn push(
@ -110,11 +115,15 @@ impl git::repository::OpenRepositoryLike for TestOpenRepository {
.map_err(|_| git::fetch::Error::Lock) .map_err(|_| git::fetch::Error::Lock)
.map(|mut c| *c += 1)?; .map(|mut c| *c += 1)?;
self.on_push self.on_push
.get(i) .lock()
.map(|f| f.invoke(repo_details, branch_name, to_commit, force)) .map_err(|_| git::fetch::Error::Lock)
.unwrap_or_else(|| { .map(|a| {
unimplemented!("Unexpected push"); a.get(i)
}) .map(|f| f.invoke(repo_details, branch_name, to_commit, force))
.unwrap_or_else(|| {
unimplemented!("Unexpected push");
})
})?
} }
fn commit_log( fn commit_log(
@ -137,8 +146,8 @@ impl TestOpenRepository {
pub fn new( pub fn new(
gitdir: &config::GitDir, gitdir: &config::GitDir,
fs: kxio::fs::FileSystem, fs: kxio::fs::FileSystem,
on_fetch: Vec<OnFetch>, on_fetch: Arc<Mutex<Vec<OnFetch>>>,
on_push: Vec<OnPush>, on_push: Arc<Mutex<Vec<OnPush>>>,
) -> Self { ) -> Self {
let pathbuf = fs.base().join(gitdir.to_path_buf()); let pathbuf = fs.base().join(gitdir.to_path_buf());
#[allow(clippy::expect_used)] #[allow(clippy::expect_used)]
@ -155,8 +164,8 @@ impl TestOpenRepository {
pub fn new_bare( pub fn new_bare(
gitdir: &config::GitDir, gitdir: &config::GitDir,
fs: kxio::fs::FileSystem, fs: kxio::fs::FileSystem,
on_fetch: Vec<OnFetch>, on_fetch: Arc<Mutex<Vec<OnFetch>>>,
on_push: Vec<OnPush>, on_push: Arc<Mutex<Vec<OnPush>>>,
) -> Self { ) -> Self {
let pathbuf = fs.base().join(gitdir.to_path_buf()); let pathbuf = fs.base().join(gitdir.to_path_buf());
#[allow(clippy::expect_used)] #[allow(clippy::expect_used)]

View file

@ -114,7 +114,7 @@ mod repo_config {
"# "#
); );
let rc = config::RepoConfig::load(toml.as_str())?; let rc = config::RepoConfig::parse(toml.as_str())?;
assert_eq!( assert_eq!(
rc, rc,

View file

@ -1,3 +1,5 @@
use std::sync::{Arc, Mutex};
// //
use derive_more::Constructor; use derive_more::Constructor;
@ -9,16 +11,16 @@ use git_next_config as config;
pub struct TestRepository { pub struct TestRepository {
is_bare: bool, is_bare: bool,
fs: kxio::fs::FileSystem, fs: kxio::fs::FileSystem,
on_fetch: Vec<git::repository::open::otest::OnFetch>, on_fetch: Arc<Mutex<Vec<git::repository::open::otest::OnFetch>>>,
on_push: Vec<git::repository::open::otest::OnPush>, on_push: Arc<Mutex<Vec<git::repository::open::otest::OnPush>>>,
} }
impl TestRepository { impl TestRepository {
pub fn on_fetch(&mut self, on_fetch: git::repository::OnFetch) { 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) { 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 { pub const fn fs(&self) -> &kxio::fs::FileSystem {

View file

@ -42,12 +42,19 @@ ulid = { workspace = true }
# boilerplate # boilerplate
derive_more = { workspace = true } derive_more = { workspace = true }
thiserror = { workspace = true }
# Actors # Actors
actix = { workspace = true } actix = { workspace = true }
actix-rt = { workspace = true } actix-rt = { workspace = true }
tokio = { workspace = true } tokio = { workspace = true }
[dev-dependencies]
# Testing
assert2 = { workspace = true }
rand = { workspace = true }
pretty_assertions = { workspace = true }
[lints.clippy] [lints.clippy]
nursery = { level = "warn", priority = -1 } nursery = { level = "warn", priority = -1 }
# pedantic = "warn" # pedantic = "warn"

View file

@ -1,78 +1,67 @@
// //
use actix::prelude::*; use crate as actor;
use git_next_config as config; use git_next_config as config;
use git_next_git as git; use git_next_git as git;
use derive_more::Display;
use tracing::{info, warn}; 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 // advance next to the next commit towards the head of the dev branch
#[tracing::instrument(fields(next), skip_all)] #[tracing::instrument(fields(next), skip_all)]
pub async fn advance_next( pub async fn advance_next(
next: git::Commit, next: &git::Commit,
dev_commit_history: Vec<git::Commit>, dev_commit_history: &[git::Commit],
repo_details: git::RepoDetails, repo_details: git::RepoDetails,
repo_config: config::RepoConfig, repo_config: config::RepoConfig,
repository: git::OpenRepository, repository: git::OpenRepository,
addr: Addr<super::RepoActor>, message_token: actor::messages::MessageToken,
message_token: MessageToken, ) -> Result<actor::messages::MessageToken> {
) { let commit =
let next_commit = find_next_commit_on_dev(next, dev_commit_history); find_next_commit_on_dev(next, dev_commit_history).ok_or_else(|| Error::NextAtDev)?;
let Some(commit) = next_commit else { validate_commit_message(commit.message())?;
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;
}
info!("Advancing next to commit '{}'", commit); info!("Advancing next to commit '{}'", commit);
if let Err(err) = git::push::reset( git::push::reset(
&repository, &repository,
&repo_details, &repo_details,
&repo_config.branches().next(), &repo_config.branches().next(),
&commit.into(), &commit.into(),
&git::push::Force::No, &git::push::Force::No,
) { )?;
warn!(?err, "Failed") Ok(message_token)
}
tokio::time::sleep(Duration::from_secs(10)).await;
addr.do_send(ValidateRepo { message_token })
} }
#[tracing::instrument] #[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(); let message = &message.to_string();
if message.to_ascii_lowercase().starts_with("wip") { 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) { match git_conventional::Commit::parse(message) {
Ok(commit) => { Ok(commit) => {
info!(?commit, "Pass"); info!(?commit, "Pass");
None Ok(())
} }
Err(err) => { Err(err) => {
warn!(?err, "Fail"); warn!(?err, "Fail");
Some(err.kind().to_string()) Err(Error::InvalidCommitMessage {
reason: err.kind().to_string(),
})
} }
} }
} }
pub fn find_next_commit_on_dev( pub fn find_next_commit_on_dev(
next: git::Commit, next: &git::Commit,
dev_commit_history: Vec<git::Commit>, dev_commit_history: &[git::Commit],
) -> Option<git::Commit> { ) -> Option<git::Commit> {
let mut next_commit: Option<git::Commit> = None; let mut next_commit: Option<&git::Commit> = None;
for commit in dev_commit_history.into_iter() { for commit in dev_commit_history.iter() {
if commit == next { if commit == next {
break; break;
}; };
next_commit.replace(commit); next_commit.replace(commit);
} }
next_commit next_commit.cloned()
} }
// advance main branch to the commit 'next' // advance main branch to the commit 'next'
@ -82,15 +71,30 @@ pub async fn advance_main(
repo_details: &git::RepoDetails, repo_details: &git::RepoDetails,
repo_config: &config::RepoConfig, repo_config: &config::RepoConfig,
repository: &git::OpenRepository, repository: &git::OpenRepository,
) { ) -> Result<()> {
info!("Advancing main to next"); info!("Advancing main to next");
if let Err(err) = git::push::reset( git::push::reset(
repository, repository,
repo_details, repo_details,
&repo_config.branches().main(), &repo_config.branches().main(),
&next.into(), &next.into(),
&git::push::Force::No, &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 },
} }

View file

@ -0,0 +1,52 @@
//
use actix::prelude::*;
use tracing::Instrument as _;
use crate as actor;
impl Handler<actor::messages::AdvanceMainTo> for actor::RepoActor {
type Result = ();
#[tracing::instrument(name = "RepoActor::AdvanceMainTo", skip_all, fields(repo = %self.repo_details, commit = ?msg))]
fn handle(
&mut self,
msg: actor::messages::AdvanceMainTo,
ctx: &mut Self::Context,
) -> Self::Result {
let Some(repo_config) = self.repo_details.repo_config.clone() else {
tracing::warn!("No config loaded");
return;
};
let Some(repository) = self.open_repository.clone() else {
tracing::warn!("No repository opened");
return;
};
let repo_details = self.repo_details.clone();
let addr = ctx.address();
let message_token = self.message_token;
async move {
match actor::branch::advance_main(
msg.unwrap(),
&repo_details,
&repo_config,
&repository,
)
.await
{
Err(err) => {
tracing::warn!("advance main: {err}");
}
Ok(_) => match repo_config.source() {
git_next_config::RepoConfigSource::Repo => {
addr.do_send(actor::messages::LoadConfigFromRepo)
}
git_next_config::RepoConfigSource::Server => {
addr.do_send(actor::messages::ValidateRepo::new(message_token))
}
},
}
}
.in_current_span()
.into_actor(self)
.wait(ctx);
}
}

View file

@ -0,0 +1,29 @@
//
use actix::prelude::*;
use crate as actor;
use git_next_git as git;
impl Handler<actor::messages::CloneRepo> for actor::RepoActor {
type Result = ();
#[tracing::instrument(name = "RepoActor::CloneRepo", skip_all, fields(repo = %self.repo_details /*, gitdir = %self.repo_details.gitdir */))]
fn handle(
&mut self,
_msg: actor::messages::CloneRepo,
ctx: &mut Self::Context,
) -> Self::Result {
let gitdir = self.repo_details.gitdir.clone();
match git::repository::open(&self.repository, &self.repo_details, gitdir) {
Ok(repository) => {
self.open_repository.replace(repository);
if self.repo_details.repo_config.is_none() {
ctx.address().do_send(actor::messages::LoadConfigFromRepo);
} else {
ctx.address()
.do_send(actor::messages::ValidateRepo::new(self.message_token));
}
}
Err(err) => tracing::warn!("Could not open repo: {err}"),
}
}
}

View file

@ -0,0 +1,31 @@
//
use actix::prelude::*;
use tracing::Instrument as _;
use crate as actor;
impl Handler<actor::messages::LoadConfigFromRepo> for actor::RepoActor {
type Result = ();
#[tracing::instrument(name = "RepoActor::LoadConfigFromRepo", skip_all, fields(repo = %self.repo_details))]
fn handle(
&mut self,
_msg: actor::messages::LoadConfigFromRepo,
ctx: &mut Self::Context,
) -> Self::Result {
let details = self.repo_details.clone();
let addr = ctx.address();
let Some(open_repository) = self.open_repository.clone() else {
tracing::warn!("missing open repository - can't load configuration");
return;
};
async move {
match actor::load::config_from_repository(details, open_repository).await {
Ok(repo_config) => addr.do_send(actor::messages::LoadedConfig::new(repo_config)),
Err(err) => tracing::warn!(?err, "Failed to load config"),
}
}
.in_current_span()
.into_actor(self)
.wait(ctx);
}
}

View file

@ -0,0 +1,20 @@
//
use actix::prelude::*;
use crate as actor;
impl Handler<actor::messages::LoadedConfig> for actor::RepoActor {
type Result = ();
#[tracing::instrument(name = "RepoActor::LoadedConfig", skip_all, fields(repo = %self.repo_details, branches = ?msg))]
fn handle(
&mut self,
msg: actor::messages::LoadedConfig,
ctx: &mut Self::Context,
) -> Self::Result {
let repo_config = msg.unwrap();
self.repo_details.repo_config.replace(repo_config);
ctx.address()
.do_send(actor::messages::ValidateRepo::new(self.message_token));
}
}

View file

@ -0,0 +1,8 @@
pub mod advance_to_main;
pub mod clone;
pub mod load_config_from_repo;
pub mod loaded_config;
pub mod start_monitoring;
pub mod validate_repo;
pub mod webhook_message;
pub mod webhook_registered;

View file

@ -0,0 +1,81 @@
//
use actix::prelude::*;
use tracing::Instrument as _;
use crate as actor;
use git_next_git as git;
impl Handler<actor::messages::StartMonitoring> for actor::RepoActor {
type Result = ();
#[tracing::instrument(name = "RepoActor::StartMonitoring", skip_all,
fields(token = %self.message_token, repo = %self.repo_details, main = %msg.main(), next = %msg.next(), dev = %msg.dev()))
]
fn handle(
&mut self,
msg: actor::messages::StartMonitoring,
ctx: &mut Self::Context,
) -> Self::Result {
let Some(repo_config) = self.repo_details.repo_config.clone() else {
tracing::warn!("No config loaded");
return;
};
let next_ahead_of_main = msg.main() != msg.next();
let dev_ahead_of_next = msg.next() != msg.dev();
tracing::info!(next_ahead_of_main, dev_ahead_of_next, "StartMonitoring");
let addr = ctx.address();
let forge = self.forge.clone();
if next_ahead_of_main {
let message_token = self.message_token;
async move {
// get the status - pass, fail, pending (all others map to fail, e.g. error)
let status = forge.commit_status(msg.next()).await;
tracing::info!(?status, "Checking next branch");
match status {
git::forge::commit::Status::Pass => {
addr.do_send(actor::messages::AdvanceMainTo::new(msg.next().clone()));
}
git::forge::commit::Status::Pending => {
tokio::time::sleep(tokio::time::Duration::from_secs(10)).await;
addr.do_send(actor::messages::ValidateRepo::new(message_token));
}
git::forge::commit::Status::Fail => {
tracing::warn!("Checks have failed");
}
}
}
.in_current_span()
.into_actor(self)
.wait(ctx);
} else if dev_ahead_of_next {
if let Some(repository) = self.open_repository.clone() {
let repo_details = self.repo_details.clone();
let message_token = self.message_token;
async move {
match actor::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(std::time::Duration::from_secs(10)).await;
addr.do_send(actor::messages::ValidateRepo::new(message_token))
}
Err(err) => tracing::warn!("advance next: {err}"),
}
}
.in_current_span()
.into_actor(self)
.wait(ctx);
}
}
}
}

View file

@ -0,0 +1,95 @@
//
use actix::prelude::*;
use derive_more::Deref as _;
use tracing::Instrument as _;
use crate as actor;
use git_next_git as git;
impl Handler<actor::messages::ValidateRepo> for actor::RepoActor {
type Result = ();
#[tracing::instrument(name = "RepoActor::ValidateRepo", skip_all, fields(repo = %self.repo_details, token = %msg.deref()))]
fn handle(
&mut self,
msg: actor::messages::ValidateRepo,
ctx: &mut Self::Context,
) -> Self::Result {
match msg.unwrap() {
message_token if self.message_token < message_token => {
tracing::info!(%message_token, "New message token");
self.message_token = message_token;
}
message_token if self.message_token > message_token => {
tracing::info!("Dropping message from previous generation");
return; // message is expired
}
_ => {
// do nothing
}
}
if self.webhook_id.is_none() {
let forge_alias = self.repo_details.forge.forge_alias();
let repo_alias = &self.repo_details.repo_alias;
let webhook_url = self.webhook.url(forge_alias, repo_alias);
let forge = self.forge.clone();
let addr = ctx.address();
async move {
if let Err(err) =
forge
.register_webhook(&webhook_url)
.await
.and_then(|registered_webhook| {
addr.try_send(actor::messages::WebhookRegistered::from(
registered_webhook,
))
.map_err(|e| {
git::forge::webhook::Error::FailedToNotifySelf(e.to_string())
})
})
{
tracing::warn!("registering webhook: {err}");
}
}
.in_current_span()
.into_actor(self)
.wait(ctx);
}
if let (Some(repository), Some(repo_config)) = (
self.open_repository.clone(),
self.repo_details.repo_config.clone(),
) {
let repo_details = self.repo_details.clone();
let addr = ctx.address();
let message_token = self.message_token;
async move {
match git::validation::positions::validate_positions(
&repository,
&repo_details,
repo_config,
) {
Ok(git::validation::positions::Positions {
main,
next,
dev,
dev_commit_history,
}) => {
addr.do_send(actor::messages::StartMonitoring::new(
main,
next,
dev,
dev_commit_history,
));
}
Err(err) => {
tracing::warn!("{:?}", err);
tokio::time::sleep(std::time::Duration::from_secs(10)).await;
addr.do_send(actor::messages::ValidateRepo::new(message_token));
}
}
}
.in_current_span()
.into_actor(self)
.wait(ctx);
}
}
}

View file

@ -1,13 +1,13 @@
// //
use actix::prelude::*; use actix::prelude::*;
use crate::{RepoActor, ValidateRepo}; use crate as actor;
use git_next_config as config; use git_next_config as config;
use git_next_git as git; use git_next_git as git;
use tracing::{info, warn}; use tracing::{info, warn};
impl Handler<config::WebhookMessage> for RepoActor { impl Handler<config::WebhookMessage> for actor::RepoActor {
type Result = (); type Result = ();
#[allow(clippy::cognitive_complexity)] // TODO: (#49) reduce complexity #[allow(clippy::cognitive_complexity)] // TODO: (#49) reduce complexity
@ -88,6 +88,7 @@ impl Handler<config::WebhookMessage> for RepoActor {
token = %message_token, token = %message_token,
"New commit" "New commit"
); );
ctx.address().do_send(ValidateRepo { message_token }); ctx.address()
.do_send(actor::messages::ValidateRepo::new(message_token));
} }
} }

View file

@ -0,0 +1,17 @@
//
use actix::prelude::*;
use crate as actor;
impl Handler<actor::messages::WebhookRegistered> for actor::RepoActor {
type Result = ();
#[tracing::instrument(name = "RepoActor::WebhookRegistered", skip_all, fields(repo = %self.repo_details, webhook_id = %msg.webhook_id()))]
fn handle(
&mut self,
msg: actor::messages::WebhookRegistered,
_ctx: &mut Self::Context,
) -> Self::Result {
self.webhook_id.replace(msg.webhook_id().clone());
self.webhook_auth.replace(msg.webhook_auth().clone());
}
}

View file

@ -1,18 +1,13 @@
mod branch; mod branch;
pub mod handlers;
mod load; mod load;
pub mod status; pub mod messages;
pub mod webhook;
#[cfg(test)] #[cfg(test)]
mod tests; mod tests;
use std::time::Duration;
use actix::prelude::*; use actix::prelude::*;
use config::RegisteredWebhook;
use git::validation::positions::{validate_positions, Positions};
use crate as repo_actor;
use git_next_config as config; use git_next_config as config;
use git_next_forge as forge; use git_next_forge as forge;
use git_next_git as git; use git_next_git as git;
@ -24,7 +19,7 @@ use tracing::{debug, info, warn, Instrument};
#[display("{}:{}:{}", generation, repo_details.forge.forge_alias(), repo_details.repo_alias)] #[display("{}:{}:{}", generation, repo_details.forge.forge_alias(), repo_details.repo_alias)]
pub struct RepoActor { pub struct RepoActor {
generation: git::Generation, generation: git::Generation,
message_token: MessageToken, message_token: messages::MessageToken,
repo_details: git::RepoDetails, repo_details: git::RepoDetails,
webhook: config::server::Webhook, webhook: config::server::Webhook,
webhook_id: Option<config::WebhookId>, // INFO: if [None] then no webhook is configured webhook_id: Option<config::WebhookId>, // INFO: if [None] then no webhook is configured
@ -49,7 +44,7 @@ impl RepoActor {
debug!(?forge, "new"); debug!(?forge, "new");
Self { Self {
generation, generation,
message_token: MessageToken::new(), message_token: messages::MessageToken::default(),
repo_details: details, repo_details: details,
webhook, webhook,
webhook_id: None, webhook_id: None,
@ -87,252 +82,3 @@ impl Actor for RepoActor {
} }
} }
} }
#[derive(Message)]
#[rtype(result = "()")]
pub struct CloneRepo;
impl Handler<CloneRepo> for RepoActor {
type Result = ();
#[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 {
let gitdir = self.repo_details.gitdir.clone();
match git::repository::open(&self.repository, &self.repo_details, gitdir) {
Ok(repository) => {
self.open_repository.replace(repository);
if self.repo_details.repo_config.is_none() {
ctx.address().do_send(LoadConfigFromRepo);
} else {
ctx.address().do_send(ValidateRepo {
message_token: self.message_token,
});
}
}
Err(err) => warn!("Could not open repo: {err}"),
}
}
}
#[derive(Message)]
#[rtype(result = "()")]
pub struct LoadConfigFromRepo;
impl Handler<LoadConfigFromRepo> for RepoActor {
type Result = ();
#[tracing::instrument(name = "RepoActor::LoadConfigFromRepo", skip_all, fields(repo = %self.repo_details))]
fn handle(&mut self, _msg: LoadConfigFromRepo, ctx: &mut Self::Context) -> Self::Result {
let details = self.repo_details.clone();
let addr = ctx.address();
let Some(open_repository) = self.open_repository.clone() else {
warn!("missing open repository - can't load configuration");
return;
};
repo_actor::load::load_file(details, addr, open_repository)
.in_current_span()
.into_actor(self)
.wait(ctx);
}
}
#[derive(Message)]
#[rtype(result = "()")]
struct LoadedConfig(git_next_config::RepoConfig);
impl Handler<LoadedConfig> for RepoActor {
type Result = ();
#[tracing::instrument(name = "RepoActor::LoadedConfig", skip_all, fields(repo = %self.repo_details, branches = %msg.0))]
fn handle(&mut self, msg: LoadedConfig, ctx: &mut Self::Context) -> Self::Result {
let repo_config = msg.0;
self.repo_details.repo_config.replace(repo_config);
ctx.address().do_send(ValidateRepo {
message_token: self.message_token,
});
}
}
#[derive(derive_more::Constructor, Message)]
#[rtype(result = "()")]
pub struct ValidateRepo {
message_token: MessageToken,
}
impl Handler<ValidateRepo> for RepoActor {
type Result = ();
#[tracing::instrument(name = "RepoActor::ValidateRepo", skip_all, fields(repo = %self.repo_details, token = %msg.message_token))]
fn handle(&mut self, msg: ValidateRepo, ctx: &mut Self::Context) -> Self::Result {
match msg.message_token {
message_token if self.message_token < message_token => {
info!(%message_token, "New message token");
self.message_token = msg.message_token;
}
message_token if self.message_token > message_token => {
info!("Dropping message from previous generation");
return; // message is expired
}
_ => {
// do nothing
}
}
if self.webhook_id.is_none() {
let forge_alias = self.repo_details.forge.forge_alias();
let repo_alias = &self.repo_details.repo_alias;
let webhook_url = self.webhook.url(forge_alias, repo_alias);
let forge = self.forge.clone();
let addr = ctx.address();
async move {
if let Err(err) =
forge
.register_webhook(&webhook_url)
.await
.and_then(|registered_webhook| {
addr.try_send(WebhookRegistered::from(registered_webhook))
.map_err(|e| {
git::forge::webhook::Error::FailedToNotifySelf(e.to_string())
})
})
{
warn!("registering webhook: {err}");
}
}
.in_current_span()
.into_actor(self)
.wait(ctx);
}
if let (Some(repository), Some(repo_config)) = (
self.open_repository.clone(),
self.repo_details.repo_config.clone(),
) {
let repo_details = self.repo_details.clone();
let addr = ctx.address();
let message_token = self.message_token;
async move {
match validate_positions(&repository, &repo_details, repo_config) {
Ok(Positions {
main,
next,
dev,
dev_commit_history,
}) => {
addr.do_send(StartMonitoring::new(main, next, dev, dev_commit_history));
}
Err(err) => {
warn!("{:?}", err);
tokio::time::sleep(Duration::from_secs(10)).await;
addr.do_send(ValidateRepo::new(message_token));
}
}
}
.in_current_span()
.into_actor(self)
.wait(ctx);
}
}
}
#[derive(Debug, derive_more::Constructor, Message)]
#[rtype(result = "()")]
pub struct StartMonitoring {
main: git::Commit,
next: git::Commit,
dev: git::Commit,
dev_commit_history: Vec<git::Commit>,
}
impl Handler<StartMonitoring> for RepoActor {
type Result = ();
#[tracing::instrument(name = "RepoActor::StartMonitoring", skip_all,
fields(token = %self.message_token, repo = %self.repo_details, main = %msg.main, next= %msg.next, dev = %msg.dev))
]
fn handle(&mut self, msg: StartMonitoring, ctx: &mut Self::Context) -> Self::Result {
let Some(repo_config) = self.repo_details.repo_config.clone() else {
warn!("No config loaded");
return;
};
let next_ahead_of_main = msg.main != msg.next;
let dev_ahead_of_next = msg.next != msg.dev;
info!(next_ahead_of_main, dev_ahead_of_next, "StartMonitoring");
let addr = ctx.address();
let forge = self.forge.clone();
if next_ahead_of_main {
status::check_next(msg.next, addr, forge, self.message_token)
.in_current_span()
.into_actor(self)
.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,
)
.in_current_span()
.into_actor(self)
.wait(ctx);
}
}
}
}
#[derive(Message)]
#[rtype(result = "()")]
pub struct WebhookRegistered(config::WebhookId, config::WebhookAuth);
impl From<RegisteredWebhook> for WebhookRegistered {
fn from(value: RegisteredWebhook) -> Self {
Self(value.id().clone(), value.auth().clone())
}
}
impl Handler<WebhookRegistered> for RepoActor {
type Result = ();
#[tracing::instrument(name = "RepoActor::WebhookRegistered", skip_all, fields(repo = %self.repo_details, webhook_id = %msg.0))]
fn handle(&mut self, msg: WebhookRegistered, _ctx: &mut Self::Context) -> Self::Result {
self.webhook_id.replace(msg.0);
self.webhook_auth.replace(msg.1);
}
}
#[derive(Message)]
#[rtype(result = "()")]
pub struct AdvanceMainTo(git::Commit);
impl Handler<AdvanceMainTo> for RepoActor {
type Result = ();
#[tracing::instrument(name = "RepoActor::AdvanceMainTo", skip_all, fields(repo = %self.repo_details, commit = %msg.0))]
fn handle(&mut self, msg: AdvanceMainTo, ctx: &mut Self::Context) -> Self::Result {
let Some(repo_config) = self.repo_details.repo_config.clone() else {
warn!("No config loaded");
return;
};
let Some(repository) = self.open_repository.clone() else {
warn!("No repository opened");
return;
};
let repo_details = self.repo_details.clone();
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 })
}
}
}
.in_current_span()
.into_actor(self)
.wait(ctx);
}
}
#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, PartialOrd, Ord, derive_more::Display)]
pub struct MessageToken(u32);
impl MessageToken {
pub fn new() -> Self {
Self::default()
}
pub const fn next(&self) -> Self {
Self(self.0 + 1)
}
}

View file

@ -1,75 +1,54 @@
use std::path::PathBuf;
// //
use actix::prelude::*; use derive_more::Display;
use std::path::PathBuf;
use tracing::{error, info}; use tracing::info;
use git_next_config as config; use git_next_config as config;
use git_next_git as git; use git_next_git as git;
use super::{LoadedConfig, RepoActor};
/// Loads the [RepoConfig] from the `.git-next.toml` file in the repository /// Loads the [RepoConfig] from the `.git-next.toml` file in the repository
#[tracing::instrument(skip_all, fields(branch = %repo_details.branch))] #[tracing::instrument(skip_all, fields(branch = %repo_details.branch))]
pub async fn load_file( pub async fn config_from_repository(
repo_details: git::RepoDetails, repo_details: git::RepoDetails,
addr: Addr<RepoActor>,
open_repository: git::OpenRepository, open_repository: git::OpenRepository,
) { ) -> Result<config::RepoConfig> {
info!("Loading .git-next.toml from repo"); info!("Loading .git-next.toml from repo");
let repo_config = match load(&repo_details, &open_repository).await { let contents =
Ok(repo_config) => repo_config, open_repository.read_file(&repo_details.branch, &PathBuf::from(".git-next.toml"))?;
Err(err) => { let config = config::RepoConfig::parse(&contents)?;
error!(?err, "Failed to load config"); let branches = open_repository.remote_branches()?;
return; required_branch(&config.branches().main(), &branches)?;
} required_branch(&config.branches().next(), &branches)?;
}; required_branch(&config.branches().dev(), &branches)?;
info!("Loaded .git-next.toml from repo");
addr.do_send(LoadedConfig(repo_config));
}
async fn load(
details: &git::RepoDetails,
open_repository: &git::OpenRepository,
) -> Result<config::RepoConfig, Error> {
let contents = open_repository.read_file(&details.branch, &PathBuf::from(".git-next.toml"))?;
let config = config::RepoConfig::load(&contents)?;
let config = validate(config, open_repository).await?;
Ok(config) Ok(config)
} }
#[derive(Debug, derive_more::From, derive_more::Display)] fn required_branch(
branch_name: &config::BranchName,
branches: &[config::BranchName],
) -> Result<()> {
branches
.iter()
.find(|branch| *branch == branch_name)
.ok_or_else(|| Error::BranchNotFound(branch_name.clone()))?;
Ok(())
}
pub type Result<T> = core::result::Result<T, Error>;
#[derive(Debug, thiserror::Error, Display)]
pub enum Error { pub enum Error {
File(git::file::Error), #[display("file")]
Config(config::server::Error), File(#[from] git::file::Error),
Toml(toml::de::Error),
Branch(git::push::Error), #[display("config")]
Config(#[from] config::server::Error),
#[display("toml")]
Toml(#[from] toml::de::Error),
#[display("push")]
Push(#[from] git::push::Error),
#[display("branch not found: {}", 0)]
BranchNotFound(config::BranchName), BranchNotFound(config::BranchName),
} }
pub async fn validate(
config: config::RepoConfig,
open_repository: &git::OpenRepository,
) -> Result<config::RepoConfig, Error> {
let branches = open_repository.remote_branches()?;
if !branches
.iter()
.any(|branch| branch == &config.branches().main())
{
return Err(Error::BranchNotFound(config.branches().main()));
}
if !branches
.iter()
.any(|branch| branch == &config.branches().next())
{
return Err(Error::BranchNotFound(config.branches().next()));
}
if !branches
.iter()
.any(|branch| branch == &config.branches().dev())
{
return Err(Error::BranchNotFound(config.branches().dev()));
}
Ok(config)
}

View file

@ -0,0 +1,88 @@
//
use actix::prelude::*;
use config::newtype;
use derive_more::{Constructor, Display};
use git_next_config as config;
use git_next_git as git;
macro_rules! message {
($name:ident wraps $value:ty) => {
config::newtype!($name is a $value);
impl Message for $name {
type Result = ();
}
};
($name:ident) => {
config::newtype!($name);
impl Message for $name {
type Result = ();
}
};
($name:ident wraps $value:ty => $result:ty) => {
config::newtype!($name is a $value);
impl Message for $name {
type Result = $result;
}
};
($name:ident => $result:ty) => {
config::newtype!($name);
impl Message for $name {
type Result = $result;
}
};
}
message!(LoadConfigFromRepo);
message!(CloneRepo);
message!(LoadedConfig wraps config::RepoConfig);
message!(ValidateRepo wraps MessageToken);
#[derive(Debug, Constructor, Message)]
#[rtype(result = "()")]
pub struct StartMonitoring {
main: git::Commit,
next: git::Commit,
dev: git::Commit,
dev_commit_history: Vec<git::Commit>,
}
impl StartMonitoring {
pub const fn main(&self) -> &git::Commit {
&self.main
}
pub const fn next(&self) -> &git::Commit {
&self.next
}
pub const fn dev(&self) -> &git::Commit {
&self.dev
}
pub fn dev_commit_history(&self) -> &[git::Commit] {
&self.dev_commit_history
}
}
message!(WebhookRegistered wraps (config::WebhookId, config::WebhookAuth));
impl WebhookRegistered {
pub const fn webhook_id(&self) -> &config::WebhookId {
&self.0 .0
}
pub const fn webhook_auth(&self) -> &config::WebhookAuth {
&self.0 .1
}
}
impl From<config::RegisteredWebhook> for WebhookRegistered {
fn from(value: config::RegisteredWebhook) -> Self {
let webhook_id = value.id().clone();
let webhook_auth = value.auth().clone();
Self::from((webhook_id, webhook_auth))
}
}
message!(AdvanceMainTo wraps git::Commit);
newtype!(MessageToken is a u32, Copy, Default, Display);
impl MessageToken {
pub const fn next(&self) -> Self {
Self(self.0 + 1)
}
}

View file

@ -1,33 +0,0 @@
//
use actix::prelude::*;
use git_next_forge as forge;
use git_next_git as git;
use tracing::{info, warn};
use crate::{MessageToken, ValidateRepo};
use super::AdvanceMainTo;
pub async fn check_next(
next: git::Commit,
addr: Addr<super::RepoActor>,
forge: forge::Forge,
message_token: MessageToken,
) {
// get the status - pass, fail, pending (all others map to fail, e.g. error)
let status = forge.commit_status(&next).await;
info!(?status, "Checking next branch");
match status {
git::forge::commit::Status::Pass => {
addr.do_send(AdvanceMainTo(next));
}
git::forge::commit::Status::Pending => {
tokio::time::sleep(tokio::time::Duration::from_secs(10)).await;
addr.do_send(ValidateRepo { message_token });
}
git::forge::commit::Status::Fail => {
warn!("Checks have failed");
}
}
}

View file

@ -1,34 +1,913 @@
// //
#![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 super::*;
use assert2::let_assert;
type TestResult = Result<(), Box<dyn std::error::Error>>;
mod repo_actor {
mod create {
//
}
}
mod branch { mod branch {
use super::super::branch::*;
use super::*; 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] #[actix_rt::test]
async fn test_find_next_commit_on_dev() { async fn test_find_next_commit_on_dev() {
let next = git::Commit::new( let next = given::a_commit();
git::commit::Sha::new("current-next".to_string()), let expected = given::a_commit();
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 dev_commit_history = vec![ let dev_commit_history = vec![
git::Commit::new( given::a_commit(), // dev HEAD
git::commit::Sha::new("dev".to_string()),
git::commit::Message::new("future".to_string()),
),
expected.clone(), expected.clone(),
next.clone(), next.clone(), // next - advancing towards dev HEAD
git::Commit::new( given::a_commit(), // parent of next
git::commit::Sha::new("current-main".to_string()),
git::commit::Message::new("history".to_string()),
),
]; ];
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"); assert_eq!(next_commit, Some(expected), "Found the wrong commit");
} }
} }
mod load {
use std::path::PathBuf;
use git_next_git::common::repo_details;
use super::*;
#[tokio::test]
async fn when_file_not_found_should_error() -> TestResult {
//given
let fs = given::a_filesystem();
let repo_details = given::repo_details(&fs);
let (open_repository, gitdir, _) = given::an_open_repository(&fs);
// create file to create commit on the branch that we then look for config file on
let file_name = given::a_pathbuf(); // not the file we want to load
let contents = given::a_name();
let branch_name = &repo_details.branch;
let_assert!(
Ok(_) =
then::commit_named_file_to_branch(&file_name, &contents, &fs, &gitdir, branch_name),
"create branch"
);
//when
let_assert!(
Err(err) = actor::load::config_from_repository(repo_details, open_repository).await
);
//then
eprintln!("Got: {err:?}");
assert!(matches!(
err,
actor::load::Error::File(git::file::Error::FileNotFound)
));
Ok(())
}
#[tokio::test]
async fn when_file_format_invalid_should_error() -> TestResult {
//given
let fs = given::a_filesystem();
let repo_details = given::repo_details(&fs);
let (open_repository, gitdir, _) = given::an_open_repository(&fs);
// create file to create commit on the branch that we then look for config file on
let file_name = PathBuf::from(".git-next.toml"); // the file we want to load
let contents = given::a_name(); // not a valid file content
let branch_name = &repo_details.branch;
let_assert!(
Ok(_) =
then::commit_named_file_to_branch(&file_name, &contents, &fs, &gitdir, branch_name),
"create branch"
);
//when
let_assert!(
Err(err) = actor::load::config_from_repository(repo_details, open_repository).await
);
//then
eprintln!("Got: {err:?}");
assert!(matches!(err, actor::load::Error::Toml(_)));
Ok(())
}
#[tokio::test]
async fn when_main_branch_is_missing_should_error() -> TestResult {
//given
let fs = given::a_filesystem();
let repo_details = given::repo_details(&fs);
let (open_repository, gitdir, _) = given::an_open_repository(&fs);
// create file to create commit on the branch that we then look for config file on
let file_name = PathBuf::from(".git-next.toml"); // the file we want to load
let branches = given::repo_branches();
let main = branches.main();
let next = branches.next();
let dev = branches.dev();
let contents = format!(
r#"
[branches]
main = "{main}"
next = "{next}"
dev = "{dev}"
"#
);
let branch_name = &repo_details.branch;
let_assert!(
Ok(_) =
then::commit_named_file_to_branch(&file_name, &contents, &fs, &gitdir, branch_name),
"create branch"
);
//when
let_assert!(
Err(err) = actor::load::config_from_repository(repo_details, open_repository).await
);
//then
eprintln!("Got: {err:?}");
assert!(matches!(err, actor::load::Error::BranchNotFound(branch) if branch == main));
Ok(())
}
#[tokio::test]
async fn when_next_branch_is_missing_should_error() -> TestResult {
//given
let fs = given::a_filesystem();
let repo_details = given::repo_details(&fs);
let (open_repository, gitdir, _) = given::an_open_repository(&fs);
// create file to create commit on the branch that we then look for config file on
let file_name = PathBuf::from(".git-next.toml"); // the file we want to load
let branches = given::repo_branches();
let main = branches.main();
let next = branches.next();
let dev = branches.dev();
let contents = format!(
r#"
[branches]
main = "{main}"
next = "{next}"
dev = "{dev}"
"#
);
let branch_name = &repo_details.branch;
let_assert!(
Ok(_) =
then::commit_named_file_to_branch(&file_name, &contents, &fs, &gitdir, branch_name),
"create branch"
);
// create main branch
let_assert!(
Ok(_) = then::create_a_commit_on_branch(&fs, &gitdir, &main),
"create main branch"
);
//when
let_assert!(
Err(err) = actor::load::config_from_repository(repo_details, open_repository).await
);
//then
eprintln!("Got: {err:?}");
assert!(matches!(err, actor::load::Error::BranchNotFound(branch) if branch == next));
Ok(())
}
#[tokio::test]
async fn when_dev_branch_is_missing_should_error() -> TestResult {
//given
let fs = given::a_filesystem();
let repo_details = given::repo_details(&fs);
let (open_repository, gitdir, _) = given::an_open_repository(&fs);
// create file to create commit on the branch that we then look for config file on
let file_name = PathBuf::from(".git-next.toml"); // the file we want to load
let branches = given::repo_branches();
let main = branches.main();
let next = branches.next();
let dev = branches.dev();
let contents = format!(
r#"
[branches]
main = "{main}"
next = "{next}"
dev = "{dev}"
"#
);
let branch_name = &repo_details.branch;
let_assert!(
Ok(_) =
then::commit_named_file_to_branch(&file_name, &contents, &fs, &gitdir, branch_name),
"create branch"
);
// create main branch
let_assert!(
Ok(_) = then::create_a_commit_on_branch(&fs, &gitdir, &main),
"create main branch"
);
// create next branch
let_assert!(
Ok(_) = then::create_a_commit_on_branch(&fs, &gitdir, &next),
"create next branch"
);
//when
let_assert!(
Err(err) = actor::load::config_from_repository(repo_details, open_repository).await
);
//then
eprintln!("Got: {err:?}");
assert!(matches!(err, actor::load::Error::BranchNotFound(branch) if branch == dev));
Ok(())
}
#[tokio::test]
async fn when_valid_file_should_return_repo_config() -> TestResult {
//given
let fs = given::a_filesystem();
let repo_details = given::repo_details(&fs);
let (open_repository, gitdir, _) = given::an_open_repository(&fs);
// create file to create commit on the branch that we then look for config file on
let file_name = PathBuf::from(".git-next.toml"); // the file we want to load
let repo_config = given::a_repo_config();
let branches = repo_config.branches();
let main = branches.main();
let next = branches.next();
let dev = branches.dev();
let contents = format!(
r#"
[branches]
main = "{main}"
next = "{next}"
dev = "{dev}"
"#
);
let branch_name = &repo_details.branch;
let_assert!(
Ok(_) =
then::commit_named_file_to_branch(&file_name, &contents, &fs, &gitdir, branch_name),
"create branch"
);
// create main branch
let_assert!(
Ok(_) = then::create_a_commit_on_branch(&fs, &gitdir, &main),
"create main branch"
);
// create next branch
let_assert!(
Ok(_) = then::create_a_commit_on_branch(&fs, &gitdir, &next),
"create next branch"
);
// create dev branch
let_assert!(
Ok(_) = then::create_a_commit_on_branch(&fs, &gitdir, &dev),
"create dev branch"
);
//when
let_assert!(
Ok(result) = actor::load::config_from_repository(repo_details, open_repository).await
);
//then
eprintln!("Got: {result:?}");
assert_eq!(result, repo_config);
Ok(())
}
}
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() -> messages::MessageToken {
messages::MessageToken::default()
}
}
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()))
}
}

View file

@ -8,7 +8,7 @@ use git_next_config::{
self as config, ForgeAlias, ForgeConfig, GitDir, RepoAlias, ServerRepoConfig, self as config, ForgeAlias, ForgeConfig, GitDir, RepoAlias, ServerRepoConfig,
}; };
use git_next_git::{Generation, RepoDetails, Repository}; use git_next_git::{Generation, RepoDetails, Repository};
use git_next_repo_actor::{CloneRepo, RepoActor}; use git_next_repo_actor as repo_actor;
use kxio::{fs::FileSystem, network::Network}; use kxio::{fs::FileSystem, network::Network};
use tracing::{error, info, warn}; use tracing::{error, info, warn};
@ -151,7 +151,7 @@ impl Server {
forge_name: ForgeAlias, forge_name: ForgeAlias,
server_storage: &ServerStorage, server_storage: &ServerStorage,
webhook: &Webhook, webhook: &Webhook,
) -> Vec<(ForgeAlias, RepoAlias, RepoActor)> { ) -> Vec<(ForgeAlias, RepoAlias, repo_actor::RepoActor)> {
let span = let span =
tracing::info_span!("create_forge_repos", name = %forge_name, config = %forge_config); tracing::info_span!("create_forge_repos", name = %forge_name, config = %forge_config);
@ -176,7 +176,8 @@ impl Server {
forge_config: ForgeConfig, forge_config: ForgeConfig,
server_storage: &ServerStorage, server_storage: &ServerStorage,
webhook: &Webhook, webhook: &Webhook,
) -> impl Fn((RepoAlias, &ServerRepoConfig)) -> (ForgeAlias, RepoAlias, RepoActor) { ) -> impl Fn((RepoAlias, &ServerRepoConfig)) -> (ForgeAlias, RepoAlias, repo_actor::RepoActor)
{
let server_storage = server_storage.clone(); let server_storage = server_storage.clone();
let webhook = webhook.clone(); let webhook = webhook.clone();
let net = self.net.clone(); let net = self.net.clone();
@ -208,7 +209,7 @@ impl Server {
gitdir, gitdir,
); );
info!("Starting Repo Actor"); info!("Starting Repo Actor");
let actor = RepoActor::new( let actor = repo_actor::RepoActor::new(
repo_details, repo_details,
webhook.clone(), webhook.clone(),
generation, generation,
@ -221,13 +222,13 @@ impl Server {
fn start_actor( fn start_actor(
&self, &self,
actor: (ForgeAlias, RepoAlias, RepoActor), actor: (ForgeAlias, RepoAlias, repo_actor::RepoActor),
) -> (RepoAlias, Addr<RepoActor>) { ) -> (RepoAlias, Addr<repo_actor::RepoActor>) {
let (forge_name, repo_alias, actor) = actor; let (forge_name, repo_alias, actor) = actor;
let span = tracing::info_span!("start_actor", forge = %forge_name, repo = %repo_alias); let span = tracing::info_span!("start_actor", forge = %forge_name, repo = %repo_alias);
let _guard = span.enter(); let _guard = span.enter();
let addr = actor.start(); let addr = actor.start();
addr.do_send(CloneRepo); addr.do_send(repo_actor::messages::CloneRepo);
info!("Started"); info!("Started");
(repo_alias, addr) (repo_alias, addr)
} }

View file

@ -18,7 +18,7 @@ fn test_repo_config_load() -> Result<()> {
[options] [options]
"#; "#;
let config = RepoConfig::load(toml)?; let config = RepoConfig::parse(toml)?;
assert_eq!( assert_eq!(
config, config,