refactor: repo-actor: rewrite tests using mockall
This commit is contained in:
parent
601e400300
commit
9c441a052c
85 changed files with 3213 additions and 691 deletions
|
@ -13,5 +13,5 @@ debug = 0
|
||||||
strip = "debuginfo"
|
strip = "debuginfo"
|
||||||
|
|
||||||
[env]
|
[env]
|
||||||
RUSTLOG = "hyper=warn"
|
RUST_LOG = "hyper=warn,debug"
|
||||||
RUSTFLAGS = "--cfg tokio_unstable"
|
RUSTFLAGS = "--cfg tokio_unstable"
|
||||||
|
|
|
@ -97,3 +97,4 @@ assert2 = "0.3"
|
||||||
pretty_assertions = "1.4"
|
pretty_assertions = "1.4"
|
||||||
rand = "0.8"
|
rand = "0.8"
|
||||||
mockall = "0.12"
|
mockall = "0.12"
|
||||||
|
test-log = "0.2"
|
||||||
|
|
|
@ -4,7 +4,7 @@
|
||||||
# Complete help on configuration: https://dystroy.org/bacon/config/
|
# Complete help on configuration: https://dystroy.org/bacon/config/
|
||||||
|
|
||||||
default_job = "check"
|
default_job = "check"
|
||||||
reverse = true
|
# reverse = true
|
||||||
|
|
||||||
[jobs.check]
|
[jobs.check]
|
||||||
command = ["cargo", "check", "--color", "always"]
|
command = ["cargo", "check", "--color", "always"]
|
||||||
|
|
|
@ -42,7 +42,8 @@ async fn main() {
|
||||||
git_next_server::init(fs);
|
git_next_server::init(fs);
|
||||||
}
|
}
|
||||||
Server::Start => {
|
Server::Start => {
|
||||||
git_next_server::start(fs, net, repo).await;
|
let sleep_duration = std::time::Duration::from_secs(10);
|
||||||
|
git_next_server::start(fs, net, repo, sleep_duration).await;
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
|
@ -10,17 +10,7 @@ github = []
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
# logging
|
# logging
|
||||||
# console-subscriber = { workspace = true }
|
|
||||||
tracing = { workspace = true }
|
tracing = { workspace = true }
|
||||||
# tracing-subscriber = { workspace = true }
|
|
||||||
|
|
||||||
# # base64 decoding
|
|
||||||
# base64 = { workspace = true }
|
|
||||||
#
|
|
||||||
# # git
|
|
||||||
# # gix = { workspace = true }
|
|
||||||
# gix = { workspace = true }
|
|
||||||
# async-trait = { workspace = true }
|
|
||||||
|
|
||||||
# fs/network
|
# fs/network
|
||||||
kxio = { workspace = true }
|
kxio = { workspace = true }
|
||||||
|
@ -33,26 +23,13 @@ toml = { workspace = true }
|
||||||
# Secrets and Password
|
# Secrets and Password
|
||||||
secrecy = { workspace = true }
|
secrecy = { workspace = true }
|
||||||
|
|
||||||
# # Conventional Commit check
|
|
||||||
# git-conventional = { workspace = true }
|
|
||||||
#
|
|
||||||
# Webhooks
|
# Webhooks
|
||||||
# bytes = { workspace = true }
|
|
||||||
ulid = { workspace = true }
|
ulid = { workspace = true }
|
||||||
# warp = { workspace = true }
|
|
||||||
|
|
||||||
# boilerplate
|
# boilerplate
|
||||||
derive_more = { workspace = true }
|
derive_more = { workspace = true }
|
||||||
derive-with = { workspace = true }
|
derive-with = { workspace = true }
|
||||||
thiserror = { workspace = true }
|
thiserror = { workspace = true }
|
||||||
#
|
|
||||||
# # file watcher
|
|
||||||
# inotify = { workspace = true }
|
|
||||||
|
|
||||||
# Actors
|
|
||||||
actix = { workspace = true }
|
|
||||||
# actix-rt = { workspace = true }
|
|
||||||
# tokio = { workspace = true }
|
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
# # Testing
|
# # Testing
|
||||||
|
|
|
@ -1,5 +1,5 @@
|
||||||
// The name of a Forge to connect to
|
// The name of a Forge to connect to
|
||||||
crate::newtype!(ForgeAlias is a String, derive_more::Display, Default);
|
crate::newtype!(ForgeAlias is a String, Hash, derive_more::Display, Default);
|
||||||
impl From<&ForgeAlias> for std::path::PathBuf {
|
impl From<&ForgeAlias> for std::path::PathBuf {
|
||||||
fn from(value: &ForgeAlias) -> Self {
|
fn from(value: &ForgeAlias) -> Self {
|
||||||
Self::from(&value.0)
|
Self::from(&value.0)
|
||||||
|
|
|
@ -5,7 +5,16 @@ use crate::{ApiToken, ForgeType, Hostname, RepoAlias, ServerRepoConfig, User};
|
||||||
/// Defines a Forge to connect to
|
/// Defines a Forge to connect to
|
||||||
/// Maps from `git-next-server.toml` at `forge.{forge}`
|
/// Maps from `git-next-server.toml` at `forge.{forge}`
|
||||||
#[derive(
|
#[derive(
|
||||||
Clone, Debug, PartialEq, Eq, serde::Deserialize, derive_more::Constructor, derive_more::Display,
|
Clone,
|
||||||
|
Debug,
|
||||||
|
derive_more::From,
|
||||||
|
PartialEq,
|
||||||
|
Eq,
|
||||||
|
PartialOrd,
|
||||||
|
Ord,
|
||||||
|
serde::Deserialize,
|
||||||
|
derive_more::Constructor,
|
||||||
|
derive_more::Display,
|
||||||
)]
|
)]
|
||||||
#[display("{}:{}@{}", forge_type.to_string().to_lowercase(), user, hostname)]
|
#[display("{}:{}@{}", forge_type.to_string().to_lowercase(), user, hostname)]
|
||||||
pub struct ForgeConfig {
|
pub struct ForgeConfig {
|
||||||
|
|
|
@ -1,5 +1,16 @@
|
||||||
/// Identifier for the type of Forge
|
/// Identifier for the type of Forge
|
||||||
#[derive(Clone, Default, Copy, Debug, PartialEq, Eq, serde::Deserialize)]
|
#[derive(
|
||||||
|
Clone,
|
||||||
|
Default,
|
||||||
|
Debug,
|
||||||
|
derive_more::From,
|
||||||
|
PartialEq,
|
||||||
|
Eq,
|
||||||
|
PartialOrd,
|
||||||
|
Ord,
|
||||||
|
serde::Deserialize,
|
||||||
|
Copy,
|
||||||
|
)]
|
||||||
pub enum ForgeType {
|
pub enum ForgeType {
|
||||||
#[cfg(feature = "forgejo")]
|
#[cfg(feature = "forgejo")]
|
||||||
ForgeJo,
|
ForgeJo,
|
||||||
|
|
|
@ -41,5 +41,6 @@ pub use repo_path::RepoPath;
|
||||||
pub use server_repo_config::ServerRepoConfig;
|
pub use server_repo_config::ServerRepoConfig;
|
||||||
pub use user::User;
|
pub use user::User;
|
||||||
pub use webhook::auth::WebhookAuth;
|
pub use webhook::auth::WebhookAuth;
|
||||||
|
pub use webhook::forge_notification::ForgeNotification;
|
||||||
pub use webhook::id::WebhookId;
|
pub use webhook::id::WebhookId;
|
||||||
pub use webhook::message::WebhookMessage;
|
|
||||||
|
|
|
@ -32,7 +32,6 @@ macro_rules! newtype {
|
||||||
Eq,
|
Eq,
|
||||||
PartialOrd,
|
PartialOrd,
|
||||||
Ord,
|
Ord,
|
||||||
Hash,
|
|
||||||
derive_more::AsRef,
|
derive_more::AsRef,
|
||||||
derive_more::Deref,
|
derive_more::Deref,
|
||||||
$($derive),*
|
$($derive),*
|
||||||
|
|
|
@ -1,9 +1,7 @@
|
||||||
/// The alias of a repo
|
use derive_more::Display;
|
||||||
/// This is the alias for the repo within `git-next-server.toml`
|
|
||||||
#[derive(Clone, Default, Debug, PartialEq, Eq, Hash, derive_more::Display)]
|
use crate::newtype;
|
||||||
pub struct RepoAlias(String);
|
|
||||||
impl RepoAlias {
|
// The alias of a repo
|
||||||
pub fn new(str: impl Into<String>) -> Self {
|
// This is the alias for the repo within `git-next-server.toml`
|
||||||
Self(str.into())
|
newtype!(RepoAlias is a String, Display, Default);
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
|
@ -16,6 +16,7 @@ use crate::RepoConfigSource;
|
||||||
serde::Serialize,
|
serde::Serialize,
|
||||||
derive_more::Constructor,
|
derive_more::Constructor,
|
||||||
derive_more::Display,
|
derive_more::Display,
|
||||||
|
derive_with::With,
|
||||||
)]
|
)]
|
||||||
#[display("{}", branches)]
|
#[display("{}", branches)]
|
||||||
pub struct RepoConfig {
|
pub struct RepoConfig {
|
||||||
|
|
|
@ -1,8 +1,7 @@
|
||||||
//
|
//
|
||||||
use actix::prelude::*;
|
|
||||||
|
|
||||||
use std::{
|
use std::{
|
||||||
collections::HashMap,
|
collections::BTreeMap,
|
||||||
net::SocketAddr,
|
net::SocketAddr,
|
||||||
path::{Path, PathBuf},
|
path::{Path, PathBuf},
|
||||||
str::FromStr,
|
str::FromStr,
|
||||||
|
@ -28,13 +27,23 @@ pub enum Error {
|
||||||
type Result<T> = core::result::Result<T, Error>;
|
type Result<T> = core::result::Result<T, Error>;
|
||||||
|
|
||||||
/// Mapped from the `git-next-server.toml` file
|
/// Mapped from the `git-next-server.toml` file
|
||||||
#[derive(Debug, PartialEq, Eq, serde::Deserialize, Message, derive_more::Constructor)]
|
#[derive(
|
||||||
#[rtype(result = "()")]
|
Clone,
|
||||||
|
Debug,
|
||||||
|
derive_more::From,
|
||||||
|
PartialEq,
|
||||||
|
Eq,
|
||||||
|
PartialOrd,
|
||||||
|
Ord,
|
||||||
|
derive_more::AsRef,
|
||||||
|
serde::Deserialize,
|
||||||
|
derive_more::Constructor,
|
||||||
|
)]
|
||||||
pub struct ServerConfig {
|
pub struct ServerConfig {
|
||||||
http: Http,
|
http: Http,
|
||||||
webhook: Webhook,
|
webhook: Webhook,
|
||||||
storage: ServerStorage,
|
storage: ServerStorage,
|
||||||
pub forge: HashMap<String, ForgeConfig>,
|
pub forge: BTreeMap<String, ForgeConfig>,
|
||||||
}
|
}
|
||||||
impl ServerConfig {
|
impl ServerConfig {
|
||||||
#[tracing::instrument(skip_all)]
|
#[tracing::instrument(skip_all)]
|
||||||
|
@ -65,7 +74,18 @@ impl ServerConfig {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Defines the port the server will listen to for incoming webhooks messages
|
/// Defines the port the server will listen to for incoming webhooks messages
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, serde::Deserialize, derive_more::Constructor)]
|
#[derive(
|
||||||
|
Clone,
|
||||||
|
Debug,
|
||||||
|
derive_more::From,
|
||||||
|
PartialEq,
|
||||||
|
Eq,
|
||||||
|
PartialOrd,
|
||||||
|
Ord,
|
||||||
|
derive_more::AsRef,
|
||||||
|
serde::Deserialize,
|
||||||
|
derive_more::Constructor,
|
||||||
|
)]
|
||||||
pub struct Http {
|
pub struct Http {
|
||||||
addr: String,
|
addr: String,
|
||||||
port: u16,
|
port: u16,
|
||||||
|
@ -81,7 +101,18 @@ impl Http {
|
||||||
|
|
||||||
/// Defines the Webhook Forges should send updates to
|
/// Defines the Webhook Forges should send updates to
|
||||||
/// Must be an address that is accessible from the remote forge
|
/// Must be an address that is accessible from the remote forge
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, serde::Deserialize, derive_more::Constructor)]
|
#[derive(
|
||||||
|
Clone,
|
||||||
|
Debug,
|
||||||
|
derive_more::From,
|
||||||
|
PartialEq,
|
||||||
|
Eq,
|
||||||
|
PartialOrd,
|
||||||
|
Ord,
|
||||||
|
derive_more::AsRef,
|
||||||
|
serde::Deserialize,
|
||||||
|
derive_more::Constructor,
|
||||||
|
)]
|
||||||
pub struct Webhook {
|
pub struct Webhook {
|
||||||
url: String,
|
url: String,
|
||||||
}
|
}
|
||||||
|
@ -99,7 +130,18 @@ impl Webhook {
|
||||||
newtype!(WebhookUrl is a String, serde::Serialize);
|
newtype!(WebhookUrl is a String, serde::Serialize);
|
||||||
|
|
||||||
/// The directory to store server data, such as cloned repos
|
/// The directory to store server data, such as cloned repos
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, serde::Deserialize, derive_more::Constructor)]
|
#[derive(
|
||||||
|
Clone,
|
||||||
|
Debug,
|
||||||
|
derive_more::From,
|
||||||
|
PartialEq,
|
||||||
|
Eq,
|
||||||
|
PartialOrd,
|
||||||
|
Ord,
|
||||||
|
derive_more::AsRef,
|
||||||
|
serde::Deserialize,
|
||||||
|
derive_more::Constructor,
|
||||||
|
)]
|
||||||
pub struct ServerStorage {
|
pub struct ServerStorage {
|
||||||
path: PathBuf,
|
path: PathBuf,
|
||||||
}
|
}
|
||||||
|
|
|
@ -5,7 +5,16 @@ use crate::{BranchName, GitDir, RepoBranches, RepoConfig, RepoConfigSource, Repo
|
||||||
/// Defines a Repo within a ForgeConfig to be monitored by the server
|
/// Defines a Repo within a ForgeConfig to be monitored by the server
|
||||||
/// Maps from `git-next-server.toml` at `forge.{forge}.repos.{name}`
|
/// Maps from `git-next-server.toml` at `forge.{forge}.repos.{name}`
|
||||||
#[derive(
|
#[derive(
|
||||||
Clone, Debug, PartialEq, Eq, serde::Deserialize, derive_more::Constructor, derive_more::Display,
|
Clone,
|
||||||
|
Debug,
|
||||||
|
derive_more::From,
|
||||||
|
PartialEq,
|
||||||
|
Eq,
|
||||||
|
PartialOrd,
|
||||||
|
Ord,
|
||||||
|
serde::Deserialize,
|
||||||
|
derive_more::Display,
|
||||||
|
derive_more::Constructor,
|
||||||
)]
|
)]
|
||||||
#[display("{}@{}", repo, branch)]
|
#[display("{}@{}", repo, branch)]
|
||||||
pub struct ServerRepoConfig {
|
pub struct ServerRepoConfig {
|
||||||
|
|
|
@ -575,12 +575,11 @@ mod webhook {
|
||||||
use super::*;
|
use super::*;
|
||||||
mod message {
|
mod message {
|
||||||
use super::*;
|
use super::*;
|
||||||
use std::collections::HashMap;
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn should_return_forge_alias() {
|
fn should_return_forge_alias() {
|
||||||
let forge_alias = given::a_forge_alias();
|
let forge_alias = given::a_forge_alias();
|
||||||
let message = WebhookMessage::new(
|
let message = ForgeNotification::new(
|
||||||
forge_alias.clone(),
|
forge_alias.clone(),
|
||||||
given::a_repo_alias(),
|
given::a_repo_alias(),
|
||||||
Default::default(),
|
Default::default(),
|
||||||
|
@ -591,7 +590,7 @@ mod webhook {
|
||||||
#[test]
|
#[test]
|
||||||
fn should_return_repo_alias() {
|
fn should_return_repo_alias() {
|
||||||
let repo_alias = given::a_repo_alias();
|
let repo_alias = given::a_repo_alias();
|
||||||
let message = WebhookMessage::new(
|
let message = ForgeNotification::new(
|
||||||
given::a_forge_alias(),
|
given::a_forge_alias(),
|
||||||
repo_alias.clone(),
|
repo_alias.clone(),
|
||||||
Default::default(),
|
Default::default(),
|
||||||
|
@ -602,7 +601,7 @@ mod webhook {
|
||||||
#[test]
|
#[test]
|
||||||
fn should_return_body() {
|
fn should_return_body() {
|
||||||
let body = given::a_webhook_message_body();
|
let body = given::a_webhook_message_body();
|
||||||
let message = WebhookMessage::new(
|
let message = ForgeNotification::new(
|
||||||
given::a_forge_alias(),
|
given::a_forge_alias(),
|
||||||
given::a_repo_alias(),
|
given::a_repo_alias(),
|
||||||
Default::default(),
|
Default::default(),
|
||||||
|
@ -614,9 +613,9 @@ mod webhook {
|
||||||
fn should_return_header() {
|
fn should_return_header() {
|
||||||
let key = given::a_name();
|
let key = given::a_name();
|
||||||
let value = given::a_name();
|
let value = given::a_name();
|
||||||
let mut headers: HashMap<String, String> = Default::default();
|
let mut headers: BTreeMap<String, String> = Default::default();
|
||||||
headers.insert(key.clone(), value.clone());
|
headers.insert(key.clone(), value.clone());
|
||||||
let message = WebhookMessage::new(
|
let message = ForgeNotification::new(
|
||||||
given::a_forge_alias(),
|
given::a_forge_alias(),
|
||||||
given::a_repo_alias(),
|
given::a_repo_alias(),
|
||||||
headers,
|
headers,
|
||||||
|
@ -704,7 +703,7 @@ mod given {
|
||||||
use super::*;
|
use super::*;
|
||||||
use rand::Rng as _;
|
use rand::Rng as _;
|
||||||
use std::{
|
use std::{
|
||||||
collections::{BTreeMap, HashMap},
|
collections::BTreeMap,
|
||||||
path::{Path, PathBuf},
|
path::{Path, PathBuf},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -750,7 +749,7 @@ mod given {
|
||||||
pub fn a_server_storage() -> ServerStorage {
|
pub fn a_server_storage() -> ServerStorage {
|
||||||
ServerStorage::new(a_name().into())
|
ServerStorage::new(a_name().into())
|
||||||
}
|
}
|
||||||
pub fn some_forge_configs() -> HashMap<String, ForgeConfig> {
|
pub fn some_forge_configs() -> BTreeMap<String, ForgeConfig> {
|
||||||
[(a_name(), a_forge_config())].into()
|
[(a_name(), a_forge_config())].into()
|
||||||
}
|
}
|
||||||
pub fn a_forge_config() -> ForgeConfig {
|
pub fn a_forge_config() -> ForgeConfig {
|
||||||
|
@ -792,8 +791,8 @@ mod given {
|
||||||
RepoAlias::new(a_name())
|
RepoAlias::new(a_name())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn a_webhook_message_body() -> crate::webhook::message::Body {
|
pub fn a_webhook_message_body() -> crate::webhook::forge_notification::Body {
|
||||||
crate::webhook::message::Body::new(a_name())
|
crate::webhook::forge_notification::Body::new(a_name())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn some_repo_branches() -> RepoBranches {
|
pub fn some_repo_branches() -> RepoBranches {
|
||||||
|
|
|
@ -1,6 +1,6 @@
|
||||||
pub mod auth;
|
pub mod auth;
|
||||||
|
pub mod forge_notification;
|
||||||
pub mod id;
|
pub mod id;
|
||||||
pub mod message;
|
|
||||||
pub mod push;
|
pub mod push;
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
|
@ -1,19 +1,17 @@
|
||||||
//
|
//
|
||||||
use actix::prelude::*;
|
|
||||||
|
|
||||||
use crate as config;
|
use crate as config;
|
||||||
|
|
||||||
use std::collections::HashMap;
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
#[derive(Message, Debug, Clone, derive_more::Constructor)]
|
/// A notification receive from a Forge, typically via a Webhook.
|
||||||
#[rtype(result = "()")]
|
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, derive_more::Constructor)]
|
||||||
pub struct WebhookMessage {
|
pub struct ForgeNotification {
|
||||||
forge_alias: config::ForgeAlias,
|
forge_alias: config::ForgeAlias,
|
||||||
repo_alias: config::RepoAlias,
|
repo_alias: config::RepoAlias,
|
||||||
headers: HashMap<String, String>,
|
headers: BTreeMap<String, String>,
|
||||||
body: Body,
|
body: Body,
|
||||||
}
|
}
|
||||||
impl WebhookMessage {
|
impl ForgeNotification {
|
||||||
pub const fn forge_alias(&self) -> &config::ForgeAlias {
|
pub const fn forge_alias(&self) -> &config::ForgeAlias {
|
||||||
&self.forge_alias
|
&self.forge_alias
|
||||||
}
|
}
|
||||||
|
@ -28,7 +26,7 @@ impl WebhookMessage {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, derive_more::Constructor)]
|
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, derive_more::Constructor)]
|
||||||
pub struct Body(String);
|
pub struct Body(String);
|
||||||
impl Body {
|
impl Body {
|
||||||
pub fn as_str(&self) -> &str {
|
pub fn as_str(&self) -> &str {
|
|
@ -23,13 +23,16 @@ impl ForgeJo {
|
||||||
}
|
}
|
||||||
#[async_trait::async_trait]
|
#[async_trait::async_trait]
|
||||||
impl git::ForgeLike for ForgeJo {
|
impl git::ForgeLike for ForgeJo {
|
||||||
|
fn duplicate(&self) -> Box<dyn git::ForgeLike> {
|
||||||
|
Box::new(self.clone())
|
||||||
|
}
|
||||||
fn name(&self) -> String {
|
fn name(&self) -> String {
|
||||||
"forgejo".to_string()
|
"forgejo".to_string()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn is_message_authorised(
|
fn is_message_authorised(
|
||||||
&self,
|
&self,
|
||||||
msg: &config::WebhookMessage,
|
msg: &config::ForgeNotification,
|
||||||
expected: &config::WebhookAuth,
|
expected: &config::WebhookAuth,
|
||||||
) -> bool {
|
) -> bool {
|
||||||
let authorization = msg.header("authorization");
|
let authorization = msg.header("authorization");
|
||||||
|
@ -43,7 +46,7 @@ impl git::ForgeLike for ForgeJo {
|
||||||
|
|
||||||
fn parse_webhook_body(
|
fn parse_webhook_body(
|
||||||
&self,
|
&self,
|
||||||
body: &config::webhook::message::Body,
|
body: &config::webhook::forge_notification::Body,
|
||||||
) -> git::forge::webhook::Result<config::webhook::Push> {
|
) -> git::forge::webhook::Result<config::webhook::Push> {
|
||||||
webhook::parse_body(body)
|
webhook::parse_body(body)
|
||||||
}
|
}
|
||||||
|
|
|
@ -77,7 +77,7 @@ mod forgejo {
|
||||||
let next = repo_branches.next();
|
let next = repo_branches.next();
|
||||||
let sha = given::a_name();
|
let sha = given::a_name();
|
||||||
let message = given::a_name();
|
let message = given::a_name();
|
||||||
let body = config::webhook::message::Body::new(
|
let body = config::webhook::forge_notification::Body::new(
|
||||||
json!({"ref":format!("refs/heads/{next}"),"after":sha,"head_commit":{"message":message}})
|
json!({"ref":format!("refs/heads/{next}"),"after":sha,"head_commit":{"message":message}})
|
||||||
.to_string(),
|
.to_string(),
|
||||||
);
|
);
|
||||||
|
@ -94,7 +94,8 @@ mod forgejo {
|
||||||
fn should_error_invalid_body() {
|
fn should_error_invalid_body() {
|
||||||
let fs = given::a_filesystem();
|
let fs = given::a_filesystem();
|
||||||
let forge = given::a_forgejo_forge(&given::repo_details(&fs), given::a_network());
|
let forge = given::a_forgejo_forge(&given::repo_details(&fs), given::a_network());
|
||||||
let body = config::webhook::message::Body::new(r#"{"type":"invalid"}"#.to_string());
|
let body =
|
||||||
|
config::webhook::forge_notification::Body::new(r#"{"type":"invalid"}"#.to_string());
|
||||||
let_assert!(Err(_) = forge.parse_webhook_body(&body));
|
let_assert!(Err(_) = forge.parse_webhook_body(&body));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -588,7 +589,7 @@ mod forgejo {
|
||||||
}
|
}
|
||||||
mod given {
|
mod given {
|
||||||
|
|
||||||
use std::collections::HashMap;
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
use kxio::network::{MockNetwork, StatusCode};
|
use kxio::network::{MockNetwork, StatusCode};
|
||||||
use serde_json::json;
|
use serde_json::json;
|
||||||
|
@ -630,8 +631,8 @@ mod forgejo {
|
||||||
WrongUlid,
|
WrongUlid,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn a_webhook_message(header: Header) -> config::WebhookMessage {
|
pub fn a_webhook_message(header: Header) -> config::ForgeNotification {
|
||||||
config::WebhookMessage::new(
|
config::ForgeNotification::new(
|
||||||
given::a_forge_alias(),
|
given::a_forge_alias(),
|
||||||
given::a_repo_alias(),
|
given::a_repo_alias(),
|
||||||
given::webhook_headers(header),
|
given::webhook_headers(header),
|
||||||
|
@ -639,8 +640,8 @@ mod forgejo {
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn webhook_headers(header: Header) -> HashMap<String, String> {
|
pub fn webhook_headers(header: Header) -> BTreeMap<String, String> {
|
||||||
let mut headers = HashMap::new();
|
let mut headers = BTreeMap::new();
|
||||||
match header {
|
match header {
|
||||||
Header::Valid(auth) => {
|
Header::Valid(auth) => {
|
||||||
headers.insert("authorization".to_string(), format!("Basic {auth}"));
|
headers.insert("authorization".to_string(), format!("Basic {auth}"));
|
||||||
|
@ -678,8 +679,8 @@ mod forgejo {
|
||||||
config::WebhookAuth::generate()
|
config::WebhookAuth::generate()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn a_webhook_message_body() -> config::webhook::message::Body {
|
pub fn a_webhook_message_body() -> config::webhook::forge_notification::Body {
|
||||||
config::webhook::message::Body::new(a_name())
|
config::webhook::forge_notification::Body::new(a_name())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn repo_branches() -> config::RepoBranches {
|
pub fn repo_branches() -> config::RepoBranches {
|
||||||
|
|
|
@ -4,7 +4,7 @@ use git_next_config as config;
|
||||||
use git_next_git as git;
|
use git_next_git as git;
|
||||||
|
|
||||||
pub fn parse_body(
|
pub fn parse_body(
|
||||||
body: &config::webhook::message::Body,
|
body: &config::webhook::forge_notification::Body,
|
||||||
) -> git::forge::webhook::Result<config::webhook::Push> {
|
) -> git::forge::webhook::Result<config::webhook::Push> {
|
||||||
serde_json::from_str::<forgejo::webhook::Push>(body.as_str())?.try_into()
|
serde_json::from_str::<forgejo::webhook::Push>(body.as_str())?.try_into()
|
||||||
}
|
}
|
||||||
|
|
|
@ -19,13 +19,16 @@ pub struct Github {
|
||||||
}
|
}
|
||||||
#[async_trait::async_trait]
|
#[async_trait::async_trait]
|
||||||
impl git::ForgeLike for Github {
|
impl git::ForgeLike for Github {
|
||||||
|
fn duplicate(&self) -> Box<dyn git::ForgeLike> {
|
||||||
|
Box::new(self.clone())
|
||||||
|
}
|
||||||
fn name(&self) -> String {
|
fn name(&self) -> String {
|
||||||
"github".to_string()
|
"github".to_string()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn is_message_authorised(
|
fn is_message_authorised(
|
||||||
&self,
|
&self,
|
||||||
msg: &config::WebhookMessage,
|
msg: &config::ForgeNotification,
|
||||||
webhook_auth: &config::WebhookAuth,
|
webhook_auth: &config::WebhookAuth,
|
||||||
) -> bool {
|
) -> bool {
|
||||||
github::webhook::is_authorised(msg, webhook_auth)
|
github::webhook::is_authorised(msg, webhook_auth)
|
||||||
|
@ -33,7 +36,7 @@ impl git::ForgeLike for Github {
|
||||||
|
|
||||||
fn parse_webhook_body(
|
fn parse_webhook_body(
|
||||||
&self,
|
&self,
|
||||||
body: &config::webhook::message::Body,
|
body: &config::webhook::forge_notification::Body,
|
||||||
) -> git::forge::webhook::Result<config::webhook::push::Push> {
|
) -> git::forge::webhook::Result<config::webhook::push::Push> {
|
||||||
github::webhook::parse_body(body)
|
github::webhook::parse_body(body)
|
||||||
}
|
}
|
||||||
|
|
|
@ -10,8 +10,8 @@ mod github {
|
||||||
|
|
||||||
use crate::Github;
|
use crate::Github;
|
||||||
use config::{
|
use config::{
|
||||||
webhook::message::Body, ForgeAlias, ForgeConfig, ForgeType, GitDir, RepoAlias,
|
webhook::forge_notification::Body, ForgeAlias, ForgeConfig, ForgeNotification, ForgeType,
|
||||||
RepoBranches, ServerRepoConfig, WebhookAuth, WebhookMessage,
|
GitDir, RepoAlias, RepoBranches, ServerRepoConfig, WebhookAuth,
|
||||||
};
|
};
|
||||||
use git::ForgeLike as _;
|
use git::ForgeLike as _;
|
||||||
|
|
||||||
|
@ -536,7 +536,6 @@ mod github {
|
||||||
}
|
}
|
||||||
|
|
||||||
mod given {
|
mod given {
|
||||||
use std::collections::HashMap;
|
|
||||||
|
|
||||||
use git_next_config::{server::Webhook, WebhookId};
|
use git_next_config::{server::Webhook, WebhookId};
|
||||||
use kxio::network::{MockNetwork, StatusCode};
|
use kxio::network::{MockNetwork, StatusCode};
|
||||||
|
@ -584,20 +583,20 @@ mod github {
|
||||||
Missing,
|
Missing,
|
||||||
Invalid,
|
Invalid,
|
||||||
}
|
}
|
||||||
pub fn a_webhook_message(header: Header) -> WebhookMessage {
|
pub fn a_webhook_message(header: Header) -> ForgeNotification {
|
||||||
let body = match &header {
|
let body = match &header {
|
||||||
Header::Valid(_, body) => body.clone(),
|
Header::Valid(_, body) => body.clone(),
|
||||||
_ => given::a_webhook_message_body(),
|
_ => given::a_webhook_message_body(),
|
||||||
};
|
};
|
||||||
WebhookMessage::new(
|
ForgeNotification::new(
|
||||||
given::a_forge_alias(),
|
given::a_forge_alias(),
|
||||||
given::a_repo_alias(),
|
given::a_repo_alias(),
|
||||||
given::webhook_headers(header),
|
given::webhook_headers(header),
|
||||||
body,
|
body,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
pub fn webhook_headers(header: Header) -> HashMap<String, String> {
|
pub fn webhook_headers(header: Header) -> BTreeMap<String, String> {
|
||||||
let mut headers = HashMap::new();
|
let mut headers = BTreeMap::new();
|
||||||
match header {
|
match header {
|
||||||
Header::Valid(auth, body) => {
|
Header::Valid(auth, body) => {
|
||||||
if let Some(sig) = crate::webhook::sign_body(&auth, &body) {
|
if let Some(sig) = crate::webhook::sign_body(&auth, &body) {
|
||||||
|
|
|
@ -1,7 +1,7 @@
|
||||||
//
|
//
|
||||||
use git_next_config as config;
|
use git_next_config as config;
|
||||||
|
|
||||||
pub fn is_authorised(msg: &config::WebhookMessage, webhook_auth: &config::WebhookAuth) -> bool {
|
pub fn is_authorised(msg: &config::ForgeNotification, webhook_auth: &config::WebhookAuth) -> bool {
|
||||||
msg.header("x-hub-signature-256")
|
msg.header("x-hub-signature-256")
|
||||||
.map(|x| x.trim_matches('"').to_string())
|
.map(|x| x.trim_matches('"').to_string())
|
||||||
.and_then(|sha| sha.strip_prefix("sha256=").map(|k| k.to_string()))
|
.and_then(|sha| sha.strip_prefix("sha256=").map(|k| k.to_string()))
|
||||||
|
@ -21,7 +21,7 @@ pub fn is_authorised(msg: &config::WebhookMessage, webhook_auth: &config::Webhoo
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
pub fn sign_body(
|
pub fn sign_body(
|
||||||
webhook_auth: &config::WebhookAuth,
|
webhook_auth: &config::WebhookAuth,
|
||||||
body: &config::webhook::message::Body,
|
body: &config::webhook::forge_notification::Body,
|
||||||
) -> std::option::Option<String> {
|
) -> std::option::Option<String> {
|
||||||
let payload = body.as_str();
|
let payload = body.as_str();
|
||||||
use hmac::Mac;
|
use hmac::Mac;
|
||||||
|
|
|
@ -4,7 +4,7 @@ use git_next_config as config;
|
||||||
use git_next_git as git;
|
use git_next_git as git;
|
||||||
|
|
||||||
pub fn parse_body(
|
pub fn parse_body(
|
||||||
body: &config::webhook::message::Body,
|
body: &config::webhook::forge_notification::Body,
|
||||||
) -> git::forge::webhook::Result<config::webhook::push::Push> {
|
) -> git::forge::webhook::Result<config::webhook::push::Push> {
|
||||||
serde_json::from_str::<github::webhook::Push>(body.as_str())?.try_into()
|
serde_json::from_str::<github::webhook::Push>(body.as_str())?.try_into()
|
||||||
}
|
}
|
||||||
|
|
|
@ -4,11 +4,9 @@ use git_next_forge_github as github;
|
||||||
use git_next_git as git;
|
use git_next_git as git;
|
||||||
use kxio::network::Network;
|
use kxio::network::Network;
|
||||||
|
|
||||||
mod mock_forge;
|
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
pub enum Forge {
|
pub enum Forge {
|
||||||
Mock(mock_forge::MockForge),
|
Mock,
|
||||||
|
|
||||||
#[cfg(feature = "forgejo")]
|
#[cfg(feature = "forgejo")]
|
||||||
ForgeJo(git_next_forge_forgejo::ForgeJo),
|
ForgeJo(git_next_forge_forgejo::ForgeJo),
|
||||||
|
@ -17,17 +15,15 @@ pub enum Forge {
|
||||||
Github(git_next_forge_github::Github),
|
Github(git_next_forge_github::Github),
|
||||||
}
|
}
|
||||||
impl Forge {
|
impl Forge {
|
||||||
pub fn new(repo_details: git::RepoDetails, net: Network) -> Self {
|
pub fn create(repo_details: git::RepoDetails, net: Network) -> Box<dyn git::ForgeLike> {
|
||||||
match repo_details.forge.forge_type() {
|
match repo_details.forge.forge_type() {
|
||||||
#[cfg(feature = "forgejo")]
|
#[cfg(feature = "forgejo")]
|
||||||
git_next_config::ForgeType::ForgeJo => {
|
git_next_config::ForgeType::ForgeJo => {
|
||||||
Self::ForgeJo(forgejo::ForgeJo::new(repo_details, net))
|
Box::new(forgejo::ForgeJo::new(repo_details, net))
|
||||||
}
|
}
|
||||||
#[cfg(feature = "github")]
|
#[cfg(feature = "github")]
|
||||||
git_next_config::ForgeType::GitHub => {
|
git_next_config::ForgeType::GitHub => Box::new(github::Github::new(repo_details, net)),
|
||||||
Self::Github(github::Github::new(repo_details, net))
|
git_next_config::ForgeType::MockForge => unreachable!(),
|
||||||
}
|
|
||||||
git_next_config::ForgeType::MockForge => Self::Mock(mock_forge::MockForge::new()),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -35,7 +31,7 @@ impl std::ops::Deref for Forge {
|
||||||
type Target = dyn git::ForgeLike;
|
type Target = dyn git::ForgeLike;
|
||||||
fn deref(&self) -> &Self::Target {
|
fn deref(&self) -> &Self::Target {
|
||||||
match self {
|
match self {
|
||||||
Self::Mock(env) => env,
|
Self::Mock => unreachable!(),
|
||||||
#[cfg(feature = "forgejo")]
|
#[cfg(feature = "forgejo")]
|
||||||
Self::ForgeJo(env) => env,
|
Self::ForgeJo(env) => env,
|
||||||
#[cfg(feature = "github")]
|
#[cfg(feature = "github")]
|
||||||
|
|
|
@ -1,59 +0,0 @@
|
||||||
//
|
|
||||||
#![cfg(not(tarpaulin_include))]
|
|
||||||
|
|
||||||
use derive_more::Constructor;
|
|
||||||
use git_next_config as config;
|
|
||||||
use git_next_git as git;
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, Constructor)]
|
|
||||||
pub struct MockForge;
|
|
||||||
|
|
||||||
#[async_trait::async_trait]
|
|
||||||
impl git::ForgeLike for MockForge {
|
|
||||||
fn name(&self) -> String {
|
|
||||||
"mock".to_string()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn is_message_authorised(
|
|
||||||
&self,
|
|
||||||
_msg: &config::WebhookMessage,
|
|
||||||
_expected: &config::WebhookAuth,
|
|
||||||
) -> bool {
|
|
||||||
todo!("MockForge::is_message_authorised")
|
|
||||||
}
|
|
||||||
|
|
||||||
fn parse_webhook_body(
|
|
||||||
&self,
|
|
||||||
_body: &config::webhook::message::Body,
|
|
||||||
) -> git::forge::webhook::Result<config::webhook::push::Push> {
|
|
||||||
todo!("MockForge::parse_webhook_body")
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn commit_status(&self, _commit: &git::Commit) -> git::forge::commit::Status {
|
|
||||||
todo!("MockForge::commit_status")
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn list_webhooks(
|
|
||||||
&self,
|
|
||||||
_webhook_url: &config::server::WebhookUrl,
|
|
||||||
) -> git::forge::webhook::Result<Vec<config::WebhookId>> {
|
|
||||||
todo!("MockForge::list_webhooks")
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn unregister_webhook(
|
|
||||||
&self,
|
|
||||||
_webhook_id: &config::WebhookId,
|
|
||||||
) -> git::forge::webhook::Result<()> {
|
|
||||||
todo!("MockForge::unregister_webhook")
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn register_webhook(
|
|
||||||
&self,
|
|
||||||
_webhook_url: &config::server::WebhookUrl,
|
|
||||||
) -> git::forge::webhook::Result<config::RegisteredWebhook> {
|
|
||||||
Ok(config::RegisteredWebhook::new(
|
|
||||||
config::WebhookId::new(""),
|
|
||||||
config::WebhookAuth::new(ulid::Ulid::new()),
|
|
||||||
))
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -4,19 +4,11 @@ use super::*;
|
||||||
use git_next_config as config;
|
use git_next_config as config;
|
||||||
use git_next_git::{self as git, RepoDetails};
|
use git_next_git::{self as git, RepoDetails};
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_mock_name() {
|
|
||||||
let net = Network::new_mock();
|
|
||||||
let repo_details = given_repo_details(config::ForgeType::MockForge);
|
|
||||||
let forge = Forge::new(repo_details, net);
|
|
||||||
assert_eq!(forge.name(), "mock");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_forgejo_name() {
|
fn test_forgejo_name() {
|
||||||
let net = Network::new_mock();
|
let net = Network::new_mock();
|
||||||
let repo_details = given_repo_details(config::ForgeType::ForgeJo);
|
let repo_details = given_repo_details(config::ForgeType::ForgeJo);
|
||||||
let forge = Forge::new(repo_details, net);
|
let forge = Forge::create(repo_details, net);
|
||||||
assert_eq!(forge.name(), "forgejo");
|
assert_eq!(forge.name(), "forgejo");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -24,7 +16,7 @@ fn test_forgejo_name() {
|
||||||
fn test_github_name() {
|
fn test_github_name() {
|
||||||
let net = Network::new_mock();
|
let net = Network::new_mock();
|
||||||
let repo_details = given_repo_details(config::ForgeType::GitHub);
|
let repo_details = given_repo_details(config::ForgeType::GitHub);
|
||||||
let forge = Forge::new(repo_details, net);
|
let forge = Forge::create(repo_details, net);
|
||||||
assert_eq!(forge.name(), "github");
|
assert_eq!(forge.name(), "github");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -37,8 +37,8 @@ impl From<config::webhook::Push> for Commit {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
newtype!(Sha is a String, Display);
|
newtype!(Sha is a String, Display, Hash);
|
||||||
newtype!(Message is a String);
|
newtype!(Message is a String, Hash);
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
pub struct Histories {
|
pub struct Histories {
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
#[derive(Debug, PartialEq, Eq)]
|
#[derive(Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
|
||||||
pub enum Status {
|
pub enum Status {
|
||||||
Pass,
|
Pass,
|
||||||
Fail,
|
Fail,
|
||||||
|
|
|
@ -1,21 +1,23 @@
|
||||||
use crate as git;
|
use crate as git;
|
||||||
use git_next_config as config;
|
use git_next_config as config;
|
||||||
|
|
||||||
|
#[mockall::automock]
|
||||||
#[async_trait::async_trait]
|
#[async_trait::async_trait]
|
||||||
pub trait ForgeLike {
|
pub trait ForgeLike: std::fmt::Debug + Send + Sync {
|
||||||
|
fn duplicate(&self) -> Box<dyn ForgeLike>;
|
||||||
fn name(&self) -> String;
|
fn name(&self) -> String;
|
||||||
|
|
||||||
/// Checks that the message has a valid authorisation
|
/// Checks that the message has a valid authorisation
|
||||||
fn is_message_authorised(
|
fn is_message_authorised(
|
||||||
&self,
|
&self,
|
||||||
message: &config::WebhookMessage,
|
message: &config::ForgeNotification,
|
||||||
expected: &config::WebhookAuth,
|
expected: &config::WebhookAuth,
|
||||||
) -> bool;
|
) -> bool;
|
||||||
|
|
||||||
/// Parses the webhook body into Some(Push) struct if appropriate, or None if not.
|
/// Parses the webhook body into Some(Push) struct if appropriate, or None if not.
|
||||||
fn parse_webhook_body(
|
fn parse_webhook_body(
|
||||||
&self,
|
&self,
|
||||||
body: &config::webhook::message::Body,
|
body: &config::webhook::forge_notification::Body,
|
||||||
) -> git::forge::webhook::Result<config::webhook::push::Push>;
|
) -> git::forge::webhook::Result<config::webhook::push::Push>;
|
||||||
|
|
||||||
/// Checks the results of any (e.g. CI) status checks for the commit.
|
/// Checks the results of any (e.g. CI) status checks for the commit.
|
||||||
|
|
|
@ -17,6 +17,7 @@ mod tests;
|
||||||
|
|
||||||
pub use commit::Commit;
|
pub use commit::Commit;
|
||||||
pub use forge::like::ForgeLike;
|
pub use forge::like::ForgeLike;
|
||||||
|
pub use forge::like::MockForgeLike;
|
||||||
pub use generation::Generation;
|
pub use generation::Generation;
|
||||||
pub use git_ref::GitRef;
|
pub use git_ref::GitRef;
|
||||||
pub use git_remote::GitRemote;
|
pub use git_remote::GitRemote;
|
||||||
|
|
|
@ -47,12 +47,12 @@ pub enum Error {
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn reset(
|
pub fn reset(
|
||||||
repository: &dyn git::repository::OpenRepositoryLike,
|
open_repository: &dyn git::repository::OpenRepositoryLike,
|
||||||
repo_details: &git::RepoDetails,
|
repo_details: &git::RepoDetails,
|
||||||
branch_name: &config::BranchName,
|
branch_name: &config::BranchName,
|
||||||
to_commit: &git::GitRef,
|
to_commit: &git::GitRef,
|
||||||
force: &git::push::Force,
|
force: &git::push::Force,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
repository.fetch()?;
|
open_repository.fetch()?;
|
||||||
repository.push(repo_details, branch_name, to_commit, force)
|
open_repository.push(repo_details, branch_name, to_commit, force)
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,7 +1,8 @@
|
||||||
use git_next_config::{
|
use config::{
|
||||||
BranchName, ForgeAlias, ForgeConfig, ForgeDetails, GitDir, RepoAlias, RepoConfig, RepoPath,
|
BranchName, ForgeAlias, ForgeConfig, ForgeDetails, GitDir, RepoAlias, RepoConfig, RepoPath,
|
||||||
ServerRepoConfig,
|
ServerRepoConfig,
|
||||||
};
|
};
|
||||||
|
use git_next_config as config;
|
||||||
|
|
||||||
use super::{Generation, GitRemote};
|
use super::{Generation, GitRemote};
|
||||||
|
|
||||||
|
@ -57,4 +58,10 @@ impl RepoDetails {
|
||||||
pub fn git_remote(&self) -> GitRemote {
|
pub fn git_remote(&self) -> GitRemote {
|
||||||
GitRemote::new(self.forge.hostname().clone(), self.repo_path.clone())
|
GitRemote::new(self.forge.hostname().clone(), self.repo_path.clone())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn with_hostname(mut self, hostname: config::Hostname) -> Self {
|
||||||
|
let forge = self.forge;
|
||||||
|
self.forge = forge.with_hostname(hostname);
|
||||||
|
self
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -23,7 +23,7 @@ pub use real::RealRepository;
|
||||||
use tracing::info;
|
use tracing::info;
|
||||||
|
|
||||||
use crate::repository::test::TestRepository;
|
use crate::repository::test::TestRepository;
|
||||||
use crate::validation::repo::validate_repo;
|
use crate::validation::remotes::validate_default_remotes;
|
||||||
|
|
||||||
use super::RepoDetails;
|
use super::RepoDetails;
|
||||||
|
|
||||||
|
@ -52,19 +52,20 @@ pub const fn test(fs: kxio::fs::FileSystem) -> TestRepository {
|
||||||
#[tracing::instrument(skip_all)]
|
#[tracing::instrument(skip_all)]
|
||||||
#[cfg(not(tarpaulin_include))] // requires network access to either clone new and/or fetch.
|
#[cfg(not(tarpaulin_include))] // requires network access to either clone new and/or fetch.
|
||||||
pub fn open(
|
pub fn open(
|
||||||
repository: &dyn RepositoryFactory,
|
repository_factory: &dyn RepositoryFactory,
|
||||||
repo_details: &RepoDetails,
|
repo_details: &RepoDetails,
|
||||||
gitdir: config::GitDir,
|
gitdir: config::GitDir,
|
||||||
) -> Result<Box<dyn OpenRepositoryLike>> {
|
) -> Result<Box<dyn OpenRepositoryLike>> {
|
||||||
let open_repository = if !gitdir.exists() {
|
let open_repository = if !gitdir.exists() {
|
||||||
info!("Local copy not found - cloning...");
|
info!("Local copy not found - cloning...");
|
||||||
repository.git_clone(repo_details)?
|
repository_factory.git_clone(repo_details)?
|
||||||
} else {
|
} else {
|
||||||
info!("Local copy found - opening...");
|
info!("Local copy found - opening...");
|
||||||
repository.open(&gitdir)?
|
repository_factory.open(&gitdir)?
|
||||||
};
|
};
|
||||||
info!("Validating...");
|
info!("Validating...");
|
||||||
validate_repo(&*open_repository, repo_details).map_err(|e| Error::Validation(e.to_string()))?;
|
validate_default_remotes(&*open_repository, repo_details)
|
||||||
|
.map_err(|e| Error::Validation(e.to_string()))?;
|
||||||
Ok(open_repository)
|
Ok(open_repository)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -125,7 +126,7 @@ impl std::ops::Deref for Repository {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
|
||||||
pub enum Direction {
|
pub enum Direction {
|
||||||
/// Push local changes to the remote.
|
/// Push local changes to the remote.
|
||||||
Push,
|
Push,
|
||||||
|
|
|
@ -1,7 +1,7 @@
|
||||||
use crate as git;
|
use crate as git;
|
||||||
|
|
||||||
mod validate {
|
mod validate {
|
||||||
use crate::{tests::given, validation::repo::validate_repo};
|
use crate::{tests::given, validation::remotes::validate_default_remotes};
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
use git::repository::Direction;
|
use git::repository::Direction;
|
||||||
|
@ -17,7 +17,7 @@ mod validate {
|
||||||
.expect_find_default_remote()
|
.expect_find_default_remote()
|
||||||
.returning(move |_direction| Some(repo_details_mock.git_remote()));
|
.returning(move |_direction| Some(repo_details_mock.git_remote()));
|
||||||
|
|
||||||
let result = validate_repo(&*open_repository, &repo_details);
|
let result = validate_default_remotes(&*open_repository, &repo_details);
|
||||||
println!("{result:?}");
|
println!("{result:?}");
|
||||||
assert!(result.is_ok());
|
assert!(result.is_ok());
|
||||||
}
|
}
|
||||||
|
@ -36,7 +36,7 @@ mod validate {
|
||||||
Direction::Fetch => Some(repo_details_mock.git_remote()),
|
Direction::Fetch => Some(repo_details_mock.git_remote()),
|
||||||
});
|
});
|
||||||
|
|
||||||
let result = validate_repo(&*open_repository, &repo_details);
|
let result = validate_default_remotes(&*open_repository, &repo_details);
|
||||||
println!("{result:?}");
|
println!("{result:?}");
|
||||||
assert!(result.is_err());
|
assert!(result.is_err());
|
||||||
}
|
}
|
||||||
|
@ -55,7 +55,7 @@ mod validate {
|
||||||
Direction::Fetch => None,
|
Direction::Fetch => None,
|
||||||
});
|
});
|
||||||
|
|
||||||
let result = validate_repo(&*open_repository, &repo_details);
|
let result = validate_default_remotes(&*open_repository, &repo_details);
|
||||||
println!("{result:?}");
|
println!("{result:?}");
|
||||||
assert!(result.is_err());
|
assert!(result.is_err());
|
||||||
}
|
}
|
||||||
|
@ -74,7 +74,7 @@ mod validate {
|
||||||
Direction::Fetch => Some(repo_details_mock.git_remote()),
|
Direction::Fetch => Some(repo_details_mock.git_remote()),
|
||||||
});
|
});
|
||||||
|
|
||||||
let result = validate_repo(&*open_repository, &repo_details);
|
let result = validate_default_remotes(&*open_repository, &repo_details);
|
||||||
println!("{result:?}");
|
println!("{result:?}");
|
||||||
assert!(result.is_err());
|
assert!(result.is_err());
|
||||||
}
|
}
|
||||||
|
@ -93,7 +93,7 @@ mod validate {
|
||||||
Direction::Fetch => Some(given::a_git_remote()),
|
Direction::Fetch => Some(given::a_git_remote()),
|
||||||
});
|
});
|
||||||
|
|
||||||
let result = validate_repo(&*open_repository, &repo_details);
|
let result = validate_default_remotes(&*open_repository, &repo_details);
|
||||||
println!("{result:?}");
|
println!("{result:?}");
|
||||||
assert!(result.is_err());
|
assert!(result.is_err());
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,5 +1,5 @@
|
||||||
pub mod positions;
|
pub mod positions;
|
||||||
pub mod repo;
|
pub mod remotes;
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests;
|
mod tests;
|
||||||
|
|
|
@ -2,8 +2,6 @@
|
||||||
use crate as git;
|
use crate as git;
|
||||||
use git_next_config as config;
|
use git_next_config as config;
|
||||||
|
|
||||||
use tracing::{error, info, warn};
|
|
||||||
|
|
||||||
pub type Result<T> = core::result::Result<T, Error>;
|
pub type Result<T> = core::result::Result<T, Error>;
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
|
@ -14,7 +12,7 @@ pub struct Positions {
|
||||||
pub dev_commit_history: Vec<git::Commit>,
|
pub dev_commit_history: Vec<git::Commit>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[allow(clippy::cognitive_complexity)] // TODO: (#83) reduce complexity
|
// #[allow(clippy::cognitive_complexity)] // TODO: (#83) reduce complexity
|
||||||
pub fn validate_positions(
|
pub fn validate_positions(
|
||||||
open_repository: &dyn git::repository::OpenRepositoryLike,
|
open_repository: &dyn git::repository::OpenRepositoryLike,
|
||||||
repo_details: &git::RepoDetails,
|
repo_details: &git::RepoDetails,
|
||||||
|
@ -46,7 +44,7 @@ pub fn validate_positions(
|
||||||
// Validations:
|
// Validations:
|
||||||
// Dev must be on main branch, else the USER must rebase it
|
// Dev must be on main branch, else the USER must rebase it
|
||||||
if is_not_based_on(&commit_histories.dev, &main) {
|
if is_not_based_on(&commit_histories.dev, &main) {
|
||||||
warn!("Dev '{dev_branch}' not based on main '{main_branch}' - user must rebase",);
|
tracing::warn!("Dev '{dev_branch}' not based on main '{main_branch}' - user must rebase",);
|
||||||
return Err(Error::DevBranchNotBasedOn {
|
return Err(Error::DevBranchNotBasedOn {
|
||||||
dev: dev_branch,
|
dev: dev_branch,
|
||||||
other: main_branch,
|
other: main_branch,
|
||||||
|
@ -54,12 +52,12 @@ pub fn validate_positions(
|
||||||
}
|
}
|
||||||
// verify that next is on main or at most one commit on top of main, else reset it back to main
|
// verify that next is on main or at most one commit on top of main, else reset it back to main
|
||||||
if is_not_based_on(&commit_histories.next[0..=1], &main) {
|
if is_not_based_on(&commit_histories.next[0..=1], &main) {
|
||||||
info!("Main not on same commit as next, or it's parent - resetting next to main",);
|
tracing::info!("Main not on same commit as next, or it's parent - resetting next to main",);
|
||||||
return reset_next_to_main(open_repository, repo_details, &main, &next, &next_branch);
|
return reset_next_to_main(open_repository, repo_details, &main, &next, &next_branch);
|
||||||
}
|
}
|
||||||
// verify that next is an ancestor of dev, else reset it back to main
|
// verify that next is an ancestor of dev, else reset it back to main
|
||||||
if is_not_based_on(&commit_histories.dev, &next) {
|
if is_not_based_on(&commit_histories.dev, &next) {
|
||||||
info!("Next is not an ancestor of dev - resetting next to main");
|
tracing::info!("Next is not an ancestor of dev - resetting next to main");
|
||||||
return reset_next_to_main(open_repository, repo_details, &main, &next, &next_branch);
|
return reset_next_to_main(open_repository, repo_details, &main, &next, &next_branch);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -72,21 +70,21 @@ pub fn validate_positions(
|
||||||
}
|
}
|
||||||
|
|
||||||
fn reset_next_to_main(
|
fn reset_next_to_main(
|
||||||
repository: &dyn crate::repository::OpenRepositoryLike,
|
open_repository: &dyn crate::repository::OpenRepositoryLike,
|
||||||
repo_details: &crate::RepoDetails,
|
repo_details: &crate::RepoDetails,
|
||||||
main: &crate::Commit,
|
main: &crate::Commit,
|
||||||
next: &crate::Commit,
|
next: &crate::Commit,
|
||||||
next_branch: &config::BranchName,
|
next_branch: &config::BranchName,
|
||||||
) -> Result<Positions> {
|
) -> Result<Positions> {
|
||||||
git::push::reset(
|
git::push::reset(
|
||||||
repository,
|
open_repository,
|
||||||
repo_details,
|
repo_details,
|
||||||
next_branch,
|
next_branch,
|
||||||
&main.clone().into(),
|
&main.clone().into(),
|
||||||
&git::push::Force::From(next.clone().into()),
|
&git::push::Force::From(next.clone().into()),
|
||||||
)
|
)
|
||||||
.map_err(|err| {
|
.map_err(|err| {
|
||||||
warn!(?err, "Failed to reset next to main");
|
tracing::warn!(?err, "Failed to reset next to main");
|
||||||
Error::FailedToResetBranch {
|
Error::FailedToResetBranch {
|
||||||
branch: next_branch.clone(),
|
branch: next_branch.clone(),
|
||||||
commit: next.clone(),
|
commit: next.clone(),
|
||||||
|
@ -100,13 +98,13 @@ fn is_not_based_on(commits: &[crate::commit::Commit], needle: &crate::Commit) ->
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_commit_histories(
|
fn get_commit_histories(
|
||||||
repository: &dyn git::repository::OpenRepositoryLike,
|
open_repository: &dyn git::repository::OpenRepositoryLike,
|
||||||
repo_config: &config::RepoConfig,
|
repo_config: &config::RepoConfig,
|
||||||
) -> git::commit::log::Result<git::commit::Histories> {
|
) -> git::commit::log::Result<git::commit::Histories> {
|
||||||
let main = (repository.commit_log(&repo_config.branches().main(), &[]))?;
|
let main = (open_repository.commit_log(&repo_config.branches().main(), &[]))?;
|
||||||
let main_head = [main[0].clone()];
|
let main_head = [main[0].clone()];
|
||||||
let next = repository.commit_log(&repo_config.branches().next(), &main_head)?;
|
let next = open_repository.commit_log(&repo_config.branches().next(), &main_head)?;
|
||||||
let dev = repository.commit_log(&repo_config.branches().dev(), &main_head)?;
|
let dev = open_repository.commit_log(&repo_config.branches().dev(), &main_head)?;
|
||||||
let histories = git::commit::Histories { main, next, dev };
|
let histories = git::commit::Histories { main, next, dev };
|
||||||
Ok(histories)
|
Ok(histories)
|
||||||
}
|
}
|
||||||
|
|
|
@ -3,7 +3,7 @@ use tracing::info;
|
||||||
use crate as git;
|
use crate as git;
|
||||||
|
|
||||||
#[tracing::instrument(skip_all)]
|
#[tracing::instrument(skip_all)]
|
||||||
pub fn validate_repo(
|
pub fn validate_default_remotes(
|
||||||
open_repository: &dyn git::repository::OpenRepositoryLike,
|
open_repository: &dyn git::repository::OpenRepositoryLike,
|
||||||
repo_details: &git::RepoDetails,
|
repo_details: &git::RepoDetails,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
|
@ -33,12 +33,13 @@ mod repos {
|
||||||
"open repo"
|
"open repo"
|
||||||
);
|
);
|
||||||
|
|
||||||
let result = git::validation::repo::validate_repo(&*open_repository, &repo_details);
|
let result =
|
||||||
|
git::validation::remotes::validate_default_remotes(&*open_repository, &repo_details);
|
||||||
print!("{result:?}");
|
print!("{result:?}");
|
||||||
let_assert!(Err(err) = result);
|
let_assert!(Err(err) = result);
|
||||||
assert!(matches!(
|
assert!(matches!(
|
||||||
err,
|
err,
|
||||||
git::validation::repo::Error::NoDefaultPushRemote
|
git::validation::remotes::Error::NoDefaultPushRemote
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -42,12 +42,21 @@ 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 }
|
||||||
|
mockall = { workspace = true }
|
||||||
|
test-log = { workspace = true }
|
||||||
|
|
||||||
[lints.clippy]
|
[lints.clippy]
|
||||||
nursery = { level = "warn", priority = -1 }
|
nursery = { level = "warn", priority = -1 }
|
||||||
# pedantic = "warn"
|
# pedantic = "warn"
|
||||||
|
|
35
crates/repo-actor/README.md
Normal file
35
crates/repo-actor/README.md
Normal file
|
@ -0,0 +1,35 @@
|
||||||
|
```mermaid
|
||||||
|
stateDiagram-v2
|
||||||
|
[*] --> CloneRepo :Start
|
||||||
|
|
||||||
|
CloneRepo --> LoadConfigFromRepo
|
||||||
|
CloneRepo --> ValidateRepo
|
||||||
|
|
||||||
|
LoadConfigFromRepo --> ReceiveRepoConfig
|
||||||
|
|
||||||
|
ValidateRepo --> CheckCIStatus
|
||||||
|
ValidateRepo --> AdvanceNext
|
||||||
|
ValidateRepo --> ValidateRepo :invalid
|
||||||
|
|
||||||
|
CheckCIStatus --> ReceiveCIStatus
|
||||||
|
|
||||||
|
ReceiveCIStatus --> AdvanceMain :Pass
|
||||||
|
ReceiveCIStatus --> ValidateRepo :Pending
|
||||||
|
ReceiveCIStatus --> [*] :Fail
|
||||||
|
|
||||||
|
AdvanceNext --> ValidateRepo
|
||||||
|
|
||||||
|
ReceiveRepoConfig --> ValidateRepo
|
||||||
|
ReceiveRepoConfig --> RegisterWebhook
|
||||||
|
|
||||||
|
RegisterWebhook --> WebhookRegistered
|
||||||
|
|
||||||
|
WebhookRegistered --> [*]
|
||||||
|
|
||||||
|
AdvanceMain --> LoadConfigFromRepo :on repo config - reload
|
||||||
|
AdvanceMain --> ValidateRepo :on server config
|
||||||
|
|
||||||
|
[*] --> WebhookNotification :WEBHOOK
|
||||||
|
|
||||||
|
WebhookNotification --> ValidateRepo
|
||||||
|
```
|
|
@ -1,96 +1,100 @@
|
||||||
//
|
//
|
||||||
use actix::prelude::*;
|
use crate::messages::MessageToken;
|
||||||
|
|
||||||
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 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,
|
||||||
open_repository: &dyn git::repository::OpenRepositoryLike,
|
open_repository: &dyn git::repository::OpenRepositoryLike,
|
||||||
addr: Addr<super::RepoActor>,
|
|
||||||
message_token: MessageToken,
|
message_token: MessageToken,
|
||||||
) {
|
) -> Result<MessageToken> {
|
||||||
let next_commit = find_next_commit_on_dev(next, dev_commit_history);
|
let commit =
|
||||||
let Some(commit) = next_commit else {
|
find_next_commit_on_dev(next, dev_commit_history).ok_or_else(|| Error::NextAtDev)?;
|
||||||
warn!("No commits to advance next to");
|
validate_commit_message(commit.message())?;
|
||||||
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(
|
||||||
open_repository,
|
open_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'
|
||||||
#[tracing::instrument(fields(next), skip_all)]
|
#[tracing::instrument(fields(next), skip_all)]
|
||||||
pub async fn advance_main(
|
pub fn advance_main(
|
||||||
next: git::Commit,
|
next: git::Commit,
|
||||||
repo_details: &git::RepoDetails,
|
repo_details: &git::RepoDetails,
|
||||||
repo_config: &config::RepoConfig,
|
repo_config: &config::RepoConfig,
|
||||||
open_repository: &dyn git::repository::OpenRepositoryLike,
|
open_repository: &dyn git::repository::OpenRepositoryLike,
|
||||||
) {
|
) -> Result<()> {
|
||||||
info!("Advancing main to next");
|
info!("Advancing main to next");
|
||||||
if let Err(err) = git::push::reset(
|
git::push::reset(
|
||||||
open_repository,
|
open_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 },
|
||||||
}
|
}
|
||||||
|
|
11
crates/repo-actor/src/handlers.rs
Normal file
11
crates/repo-actor/src/handlers.rs
Normal file
|
@ -0,0 +1,11 @@
|
||||||
|
pub mod advance_main;
|
||||||
|
pub mod advance_next;
|
||||||
|
pub mod check_ci_status;
|
||||||
|
pub mod clone_repo;
|
||||||
|
pub mod load_config_from_repo;
|
||||||
|
pub mod receive_ci_status;
|
||||||
|
pub mod receive_repo_config;
|
||||||
|
pub mod register_webhook;
|
||||||
|
pub mod validate_repo;
|
||||||
|
pub mod webhook_notification;
|
||||||
|
pub mod webhook_registered;
|
50
crates/repo-actor/src/handlers/advance_main.rs
Normal file
50
crates/repo-actor/src/handlers/advance_main.rs
Normal file
|
@ -0,0 +1,50 @@
|
||||||
|
//
|
||||||
|
use crate as actor;
|
||||||
|
use actix::prelude::*;
|
||||||
|
|
||||||
|
impl Handler<actor::messages::AdvanceMain> 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::AdvanceMain,
|
||||||
|
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(open_repository) = &self.open_repository else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let repo_details = self.repo_details.clone();
|
||||||
|
let addr = ctx.address();
|
||||||
|
let message_token = self.message_token;
|
||||||
|
|
||||||
|
match actor::branch::advance_main(
|
||||||
|
msg.unwrap(),
|
||||||
|
&repo_details,
|
||||||
|
&repo_config,
|
||||||
|
&**open_repository,
|
||||||
|
) {
|
||||||
|
Err(err) => {
|
||||||
|
tracing::warn!("advance main: {err}");
|
||||||
|
}
|
||||||
|
Ok(_) => {
|
||||||
|
let log = self.log.clone();
|
||||||
|
match repo_config.source() {
|
||||||
|
git_next_config::RepoConfigSource::Repo => {
|
||||||
|
actor::do_send(addr, actor::messages::LoadConfigFromRepo, &log);
|
||||||
|
}
|
||||||
|
git_next_config::RepoConfigSource::Server => {
|
||||||
|
actor::do_send(
|
||||||
|
addr,
|
||||||
|
actor::messages::ValidateRepo::new(message_token),
|
||||||
|
&log,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
44
crates/repo-actor/src/handlers/advance_next.rs
Normal file
44
crates/repo-actor/src/handlers/advance_next.rs
Normal file
|
@ -0,0 +1,44 @@
|
||||||
|
//
|
||||||
|
use crate as actor;
|
||||||
|
use actix::prelude::*;
|
||||||
|
|
||||||
|
impl Handler<actor::messages::AdvanceNext> for actor::RepoActor {
|
||||||
|
type Result = ();
|
||||||
|
|
||||||
|
fn handle(
|
||||||
|
&mut self,
|
||||||
|
msg: actor::messages::AdvanceNext,
|
||||||
|
ctx: &mut Self::Context,
|
||||||
|
) -> Self::Result {
|
||||||
|
let Some(repo_config) = &self.repo_details.repo_config else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let Some(open_repository) = &self.open_repository else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let (next_commit, dev_commit_history) = msg.unwrap();
|
||||||
|
let repo_details = self.repo_details.clone();
|
||||||
|
let repo_config = repo_config.clone();
|
||||||
|
let addr = ctx.address();
|
||||||
|
|
||||||
|
match actor::branch::advance_next(
|
||||||
|
&next_commit,
|
||||||
|
&dev_commit_history,
|
||||||
|
repo_details,
|
||||||
|
repo_config,
|
||||||
|
&**open_repository,
|
||||||
|
self.message_token,
|
||||||
|
) {
|
||||||
|
Ok(message_token) => {
|
||||||
|
// pause to allow any CI checks to be started
|
||||||
|
std::thread::sleep(self.sleep_duration);
|
||||||
|
actor::do_send(
|
||||||
|
addr,
|
||||||
|
actor::messages::ValidateRepo::new(message_token),
|
||||||
|
&self.log,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Err(err) => tracing::warn!("advance next: {err}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
34
crates/repo-actor/src/handlers/check_ci_status.rs
Normal file
34
crates/repo-actor/src/handlers/check_ci_status.rs
Normal file
|
@ -0,0 +1,34 @@
|
||||||
|
//
|
||||||
|
use crate as actor;
|
||||||
|
use actix::prelude::*;
|
||||||
|
use tracing::Instrument as _;
|
||||||
|
|
||||||
|
impl Handler<actor::messages::CheckCIStatus> for actor::RepoActor {
|
||||||
|
type Result = ();
|
||||||
|
|
||||||
|
fn handle(
|
||||||
|
&mut self,
|
||||||
|
msg: actor::messages::CheckCIStatus,
|
||||||
|
ctx: &mut Self::Context,
|
||||||
|
) -> Self::Result {
|
||||||
|
actor::logger(&self.log, "start: CheckCIStatus");
|
||||||
|
let addr = ctx.address();
|
||||||
|
let forge = self.forge.duplicate();
|
||||||
|
let next = msg.unwrap();
|
||||||
|
let log = self.log.clone();
|
||||||
|
|
||||||
|
// get the status - pass, fail, pending (all others map to fail, e.g. error)
|
||||||
|
async move {
|
||||||
|
let status = forge.commit_status(&next).await;
|
||||||
|
let _ = actor::send(
|
||||||
|
addr,
|
||||||
|
actor::messages::ReceiveCIStatus::new((next, status)),
|
||||||
|
&log,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
.in_current_span()
|
||||||
|
.into_actor(self)
|
||||||
|
.wait(ctx);
|
||||||
|
}
|
||||||
|
}
|
45
crates/repo-actor/src/handlers/clone_repo.rs
Normal file
45
crates/repo-actor/src/handlers/clone_repo.rs
Normal file
|
@ -0,0 +1,45 @@
|
||||||
|
//
|
||||||
|
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 {
|
||||||
|
tracing::debug!("Handler: CloneRepo: start");
|
||||||
|
let gitdir = self.repo_details.gitdir.clone();
|
||||||
|
match git::repository::open(&*self.repository_factory, &self.repo_details, gitdir) {
|
||||||
|
Ok(repository) => {
|
||||||
|
actor::logger(&self.log, "open okay");
|
||||||
|
tracing::debug!("open okay");
|
||||||
|
self.open_repository.replace(repository);
|
||||||
|
if self.repo_details.repo_config.is_none() {
|
||||||
|
tracing::debug!("Handler: CloneRepo: Sending: LoadConfigFromRepo");
|
||||||
|
actor::logger(&self.log, "send: LoadConfigFromRepo");
|
||||||
|
ctx.address().do_send(actor::messages::LoadConfigFromRepo);
|
||||||
|
} else {
|
||||||
|
tracing::debug!("Handler: CloneRepo: Sending: ValidateRepo");
|
||||||
|
actor::logger(&self.log, "send: ValidateRepo");
|
||||||
|
if let Err(_e) = ctx
|
||||||
|
.address()
|
||||||
|
.try_send(actor::messages::ValidateRepo::new(self.message_token))
|
||||||
|
{
|
||||||
|
actor::logger(&self.log, format!("ValidateRepo: error: {_e:?}"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(err) => {
|
||||||
|
actor::logger(&self.log, "open failed");
|
||||||
|
tracing::debug!("err: {err:?}");
|
||||||
|
tracing::warn!("Could not open repo: {err}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tracing::debug!("Handler: CloneRepo: finish");
|
||||||
|
}
|
||||||
|
}
|
38
crates/repo-actor/src/handlers/load_config_from_repo.rs
Normal file
38
crates/repo-actor/src/handlers/load_config_from_repo.rs
Normal file
|
@ -0,0 +1,38 @@
|
||||||
|
//
|
||||||
|
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 {
|
||||||
|
tracing::debug!("Handler: LoadConfigFromRepo: start");
|
||||||
|
let Some(open_repository) = &self.open_repository else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let open_repository = open_repository.duplicate();
|
||||||
|
let repo_details = self.repo_details.clone();
|
||||||
|
let addr = ctx.address();
|
||||||
|
let log = self.log.clone();
|
||||||
|
async move {
|
||||||
|
match actor::load::config_from_repository(repo_details, &*open_repository).await {
|
||||||
|
Ok(repo_config) => {
|
||||||
|
actor::logger(&log, "send: LoadedConfig");
|
||||||
|
addr.do_send(actor::messages::ReceiveRepoConfig::new(repo_config))
|
||||||
|
}
|
||||||
|
Err(err) => tracing::warn!(?err, "Failed to load config"),
|
||||||
|
// TODO: (#95) should notify user
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.in_current_span()
|
||||||
|
.into_actor(self)
|
||||||
|
.wait(ctx);
|
||||||
|
tracing::debug!("Handler: LoadConfigFromRepo: finish");
|
||||||
|
}
|
||||||
|
}
|
42
crates/repo-actor/src/handlers/receive_ci_status.rs
Normal file
42
crates/repo-actor/src/handlers/receive_ci_status.rs
Normal file
|
@ -0,0 +1,42 @@
|
||||||
|
//
|
||||||
|
use crate as actor;
|
||||||
|
use actix::prelude::*;
|
||||||
|
use git_next_git as git;
|
||||||
|
|
||||||
|
impl Handler<actor::messages::ReceiveCIStatus> for actor::RepoActor {
|
||||||
|
type Result = ();
|
||||||
|
|
||||||
|
fn handle(
|
||||||
|
&mut self,
|
||||||
|
msg: actor::messages::ReceiveCIStatus,
|
||||||
|
ctx: &mut Self::Context,
|
||||||
|
) -> Self::Result {
|
||||||
|
let log = self.log.clone();
|
||||||
|
actor::logger(&log, "start: ReceiveCIStatus");
|
||||||
|
let addr = ctx.address();
|
||||||
|
let (next, status) = msg.unwrap();
|
||||||
|
let message_token = self.message_token;
|
||||||
|
let sleep_duration = self.sleep_duration;
|
||||||
|
|
||||||
|
tracing::debug!(?status, "");
|
||||||
|
match status {
|
||||||
|
git::forge::commit::Status::Pass => {
|
||||||
|
actor::do_send(addr, actor::messages::AdvanceMain::new(next), &self.log);
|
||||||
|
}
|
||||||
|
git::forge::commit::Status::Pending => {
|
||||||
|
std::thread::sleep(sleep_duration);
|
||||||
|
actor::do_send(
|
||||||
|
addr,
|
||||||
|
actor::messages::ValidateRepo::new(message_token),
|
||||||
|
&self.log,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
git::forge::commit::Status::Fail => {
|
||||||
|
tracing::warn!("Checks have failed");
|
||||||
|
// TODO: (#95) test: repo with next ahead of main and failing CI should notify user
|
||||||
|
// TODO: (#88) recheck after a longer than normal delay
|
||||||
|
actor::logger(&log, "send: nothing"); // replace with messages to send notification and revalidate later
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
29
crates/repo-actor/src/handlers/receive_repo_config.rs
Normal file
29
crates/repo-actor/src/handlers/receive_repo_config.rs
Normal file
|
@ -0,0 +1,29 @@
|
||||||
|
//
|
||||||
|
use actix::prelude::*;
|
||||||
|
|
||||||
|
use crate as actor;
|
||||||
|
|
||||||
|
impl Handler<actor::messages::ReceiveRepoConfig> for actor::RepoActor {
|
||||||
|
type Result = ();
|
||||||
|
#[tracing::instrument(name = "RepoActor::ReceiveRepoConfig", skip_all, fields(repo = %self.repo_details, branches = ?msg))]
|
||||||
|
fn handle(
|
||||||
|
&mut self,
|
||||||
|
msg: actor::messages::ReceiveRepoConfig,
|
||||||
|
ctx: &mut Self::Context,
|
||||||
|
) -> Self::Result {
|
||||||
|
let repo_config = msg.unwrap();
|
||||||
|
self.repo_details.repo_config.replace(repo_config);
|
||||||
|
|
||||||
|
actor::do_send(
|
||||||
|
ctx.address(),
|
||||||
|
actor::messages::ValidateRepo::new(self.message_token),
|
||||||
|
&self.log,
|
||||||
|
);
|
||||||
|
|
||||||
|
actor::do_send(
|
||||||
|
ctx.address(),
|
||||||
|
actor::messages::RegisterWebhook::new(),
|
||||||
|
&self.log,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
39
crates/repo-actor/src/handlers/register_webhook.rs
Normal file
39
crates/repo-actor/src/handlers/register_webhook.rs
Normal file
|
@ -0,0 +1,39 @@
|
||||||
|
//
|
||||||
|
use actix::prelude::*;
|
||||||
|
use tracing::Instrument as _;
|
||||||
|
|
||||||
|
use crate as actor;
|
||||||
|
use actor::{messages::RegisterWebhook, RepoActor};
|
||||||
|
|
||||||
|
impl Handler<RegisterWebhook> for RepoActor {
|
||||||
|
type Result = ();
|
||||||
|
|
||||||
|
fn handle(&mut self, _msg: RegisterWebhook, ctx: &mut Self::Context) -> Self::Result {
|
||||||
|
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.duplicate();
|
||||||
|
let addr = ctx.address();
|
||||||
|
let log = self.log.clone();
|
||||||
|
tracing::debug!("registering webhook");
|
||||||
|
async move {
|
||||||
|
match forge.register_webhook(&webhook_url).await {
|
||||||
|
Ok(registered_webhook) => {
|
||||||
|
tracing::debug!(?registered_webhook, "");
|
||||||
|
actor::do_send(
|
||||||
|
addr,
|
||||||
|
actor::messages::WebhookRegistered::from(registered_webhook),
|
||||||
|
&log,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Err(err) => tracing::warn!(?err, "registering webhook"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.in_current_span()
|
||||||
|
.into_actor(self)
|
||||||
|
.wait(ctx);
|
||||||
|
tracing::debug!("registering webhook done");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
119
crates/repo-actor/src/handlers/validate_repo.rs
Normal file
119
crates/repo-actor/src/handlers/validate_repo.rs
Normal file
|
@ -0,0 +1,119 @@
|
||||||
|
//
|
||||||
|
use actix::prelude::*;
|
||||||
|
use derive_more::Deref as _;
|
||||||
|
use tracing::Instrument as _;
|
||||||
|
|
||||||
|
use crate::{self as actor, messages::MessageToken};
|
||||||
|
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 {
|
||||||
|
actor::logger(&self.log, "start: ValidateRepo");
|
||||||
|
|
||||||
|
// Message Token - make sure we are only triggered for the latest/current token
|
||||||
|
match self.token_status(msg.unwrap()) {
|
||||||
|
TokenStatus::Current => {} // do nothing
|
||||||
|
TokenStatus::Expired => {
|
||||||
|
actor::logger(
|
||||||
|
&self.log,
|
||||||
|
format!("discarded: old message token: {}", self.message_token),
|
||||||
|
);
|
||||||
|
return; // message is expired
|
||||||
|
}
|
||||||
|
TokenStatus::New(message_token) => {
|
||||||
|
self.message_token = message_token;
|
||||||
|
actor::logger(
|
||||||
|
&self.log,
|
||||||
|
format!("new message token: {}", self.message_token),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
actor::logger(&self.log, format!("accepted token: {}", self.message_token));
|
||||||
|
|
||||||
|
// Repository positions
|
||||||
|
let Some(ref open_repository) = self.open_repository else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let Some(repo_config) = self.repo_details.repo_config.clone() else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
|
match git::validation::positions::validate_positions(
|
||||||
|
&**open_repository,
|
||||||
|
&self.repo_details,
|
||||||
|
repo_config,
|
||||||
|
) {
|
||||||
|
Ok(git::validation::positions::Positions {
|
||||||
|
main,
|
||||||
|
next,
|
||||||
|
dev,
|
||||||
|
dev_commit_history,
|
||||||
|
}) => {
|
||||||
|
if next != main {
|
||||||
|
actor::do_send(
|
||||||
|
ctx.address(),
|
||||||
|
actor::messages::CheckCIStatus::new(next),
|
||||||
|
&self.log,
|
||||||
|
);
|
||||||
|
} else if next != dev {
|
||||||
|
actor::do_send(
|
||||||
|
ctx.address(),
|
||||||
|
actor::messages::AdvanceNext::new((next, dev_commit_history)),
|
||||||
|
&self.log,
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
// do nothing
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(err) => {
|
||||||
|
actor::logger(
|
||||||
|
&self.log,
|
||||||
|
format!("invalid positions: {err:?} will sleep then retry"),
|
||||||
|
);
|
||||||
|
tracing::warn!("Error: {err:?}");
|
||||||
|
let addr = ctx.address();
|
||||||
|
let message_token = self.message_token;
|
||||||
|
let sleep_duration = self.sleep_duration;
|
||||||
|
let log = self.log.clone();
|
||||||
|
async move {
|
||||||
|
tracing::debug!("sleeping before retrying...");
|
||||||
|
tokio::time::sleep(sleep_duration).await;
|
||||||
|
actor::do_send(
|
||||||
|
addr,
|
||||||
|
actor::messages::ValidateRepo::new(message_token),
|
||||||
|
&log,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
.in_current_span()
|
||||||
|
.into_actor(self)
|
||||||
|
.wait(ctx);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
tracing::debug!("Handler: ValidateRepo: finish");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
enum TokenStatus {
|
||||||
|
Current,
|
||||||
|
Expired,
|
||||||
|
New(MessageToken),
|
||||||
|
}
|
||||||
|
impl actor::RepoActor {
|
||||||
|
fn token_status(&self, new: MessageToken) -> TokenStatus {
|
||||||
|
let current = &self.message_token;
|
||||||
|
if &new > current {
|
||||||
|
return TokenStatus::New(new);
|
||||||
|
}
|
||||||
|
if current > &new {
|
||||||
|
return TokenStatus::Expired;
|
||||||
|
}
|
||||||
|
TokenStatus::Current
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,18 +1,18 @@
|
||||||
//
|
//
|
||||||
use actix::prelude::*;
|
use actix::prelude::*;
|
||||||
|
|
||||||
use crate::{RepoActor, ValidateRepo};
|
use crate::{self as actor, messages::WebhookNotification};
|
||||||
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<WebhookNotification> for actor::RepoActor {
|
||||||
type Result = ();
|
type Result = ();
|
||||||
|
|
||||||
#[allow(clippy::cognitive_complexity)] // TODO: (#49) reduce complexity
|
#[allow(clippy::cognitive_complexity)] // TODO: (#49) reduce complexity
|
||||||
#[tracing::instrument(name = "RepoActor::WebhookMessage", skip_all, fields(token = %self.message_token, repo = %self.repo_details))]
|
#[tracing::instrument(name = "RepoActor::WebhookMessage", skip_all, fields(token = %self.message_token, repo = %self.repo_details))]
|
||||||
fn handle(&mut self, msg: config::WebhookMessage, ctx: &mut Self::Context) -> Self::Result {
|
fn handle(&mut self, msg: WebhookNotification, ctx: &mut Self::Context) -> Self::Result {
|
||||||
let Some(expected_authorization) = &self.webhook_auth else {
|
let Some(expected_authorization) = &self.webhook_auth else {
|
||||||
warn!("Don't know what authorization to expect");
|
warn!("Don't know what authorization to expect");
|
||||||
return;
|
return;
|
||||||
|
@ -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));
|
||||||
}
|
}
|
||||||
}
|
}
|
17
crates/repo-actor/src/handlers/webhook_registered.rs
Normal file
17
crates/repo-actor/src/handlers/webhook_registered.rs
Normal 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());
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,30 +1,59 @@
|
||||||
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_git as git;
|
use git_next_git as git;
|
||||||
|
|
||||||
use kxio::network::Network;
|
use kxio::network::Network;
|
||||||
use tracing::{debug, info, warn, Instrument};
|
use tracing::{info, warn, Instrument};
|
||||||
|
|
||||||
|
pub type RepoActorLog = std::sync::Arc<std::sync::Mutex<Vec<String>>>;
|
||||||
|
|
||||||
|
/// An actor that represents a Git Repository.
|
||||||
|
///
|
||||||
|
/// When this actor is started it is sent the [CloneRepo] message.
|
||||||
|
///
|
||||||
|
/// ```mermaid
|
||||||
|
/// stateDiagram-v2
|
||||||
|
/// [*] --> CloneRepo :START
|
||||||
|
///
|
||||||
|
/// CloneRepo --> LoadConfigFromRepo
|
||||||
|
/// CloneRepo --> ValidateRepo
|
||||||
|
///
|
||||||
|
/// LoadConfigFromRepo --> LoadedConfig
|
||||||
|
///
|
||||||
|
/// ValidateRepo --> WebhookRegistered
|
||||||
|
/// ValidateRepo --> StartMonitoring
|
||||||
|
/// ValidateRepo --> ValidateRepo :SLEEP 10s
|
||||||
|
///
|
||||||
|
/// LoadedConfig --> ValidateRepo
|
||||||
|
///
|
||||||
|
/// WebhookRegistered --> [*]
|
||||||
|
///
|
||||||
|
/// StartMonitoring --> AdvanceMainTo
|
||||||
|
/// StartMonitoring --> ValidateRepo :SLEEP 10s
|
||||||
|
///
|
||||||
|
/// AdvanceMainTo --> LoadConfigFromRepo
|
||||||
|
/// AdvanceMainTo --> ValidateRepo
|
||||||
|
///
|
||||||
|
/// [*] --> WebhookMessage :WEBHOOK
|
||||||
|
///
|
||||||
|
/// WebhookMessage --> ValidateRepo
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
#[derive(Debug, derive_more::Display)]
|
#[derive(Debug, derive_more::Display)]
|
||||||
#[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 {
|
||||||
|
sleep_duration: std::time::Duration,
|
||||||
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
|
||||||
|
@ -32,47 +61,74 @@ pub struct RepoActor {
|
||||||
last_main_commit: Option<git::Commit>,
|
last_main_commit: Option<git::Commit>,
|
||||||
last_next_commit: Option<git::Commit>,
|
last_next_commit: Option<git::Commit>,
|
||||||
last_dev_commit: Option<git::Commit>,
|
last_dev_commit: Option<git::Commit>,
|
||||||
repository: Box<dyn git::repository::RepositoryFactory>,
|
repository_factory: Box<dyn git::repository::RepositoryFactory>,
|
||||||
open_repository: Option<Box<dyn git::repository::OpenRepositoryLike>>,
|
open_repository: Option<Box<dyn git::repository::OpenRepositoryLike>>,
|
||||||
net: Network,
|
net: Network,
|
||||||
forge: forge::Forge,
|
forge: Box<dyn git::ForgeLike>,
|
||||||
|
log: Option<RepoActorLog>,
|
||||||
}
|
}
|
||||||
impl RepoActor {
|
impl RepoActor {
|
||||||
pub fn new(
|
pub fn new(
|
||||||
details: git::RepoDetails,
|
repo_details: git::RepoDetails,
|
||||||
|
forge: Box<dyn git::ForgeLike>,
|
||||||
webhook: config::server::Webhook,
|
webhook: config::server::Webhook,
|
||||||
generation: git::Generation,
|
generation: git::Generation,
|
||||||
net: Network,
|
net: Network,
|
||||||
repository: Box<dyn git::repository::RepositoryFactory>,
|
repository_factory: Box<dyn git::repository::RepositoryFactory>,
|
||||||
|
sleep_duration: std::time::Duration,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
let forge = forge::Forge::new(details.clone(), net.clone());
|
let message_token = messages::MessageToken::default();
|
||||||
debug!(?forge, "new");
|
|
||||||
Self {
|
Self {
|
||||||
generation,
|
generation,
|
||||||
message_token: MessageToken::new(),
|
message_token,
|
||||||
repo_details: details,
|
repo_details,
|
||||||
webhook,
|
webhook,
|
||||||
webhook_id: None,
|
webhook_id: None,
|
||||||
webhook_auth: None,
|
webhook_auth: None,
|
||||||
last_main_commit: None,
|
last_main_commit: None,
|
||||||
last_next_commit: None,
|
last_next_commit: None,
|
||||||
last_dev_commit: None,
|
last_dev_commit: None,
|
||||||
repository,
|
repository_factory,
|
||||||
open_repository: None,
|
open_repository: None,
|
||||||
net,
|
|
||||||
forge,
|
forge,
|
||||||
|
net,
|
||||||
|
sleep_duration,
|
||||||
|
log: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
impl RepoActor {
|
||||||
|
pub fn with_log(mut self, log: RepoActorLog) -> Self {
|
||||||
|
self.log = Some(log);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn with_open_repository(
|
||||||
|
mut self,
|
||||||
|
open_repository: Box<dyn git::repository::OpenRepositoryLike>,
|
||||||
|
) -> Self {
|
||||||
|
self.open_repository.replace(open_repository);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
pub const fn with_message_token(mut self, message_token: messages::MessageToken) -> Self {
|
||||||
|
self.message_token = message_token;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
impl Actor for RepoActor {
|
impl Actor for RepoActor {
|
||||||
type Context = Context<Self>;
|
type Context = Context<Self>;
|
||||||
#[tracing::instrument(name = "RepoActor::stopping", skip_all, fields(repo = %self.repo_details))]
|
#[tracing::instrument(name = "RepoActor::stopping", skip_all, fields(repo = %self.repo_details))]
|
||||||
fn stopping(&mut self, ctx: &mut Self::Context) -> Running {
|
fn stopping(&mut self, ctx: &mut Self::Context) -> Running {
|
||||||
|
tracing::debug!("stopping");
|
||||||
info!("Checking webhook");
|
info!("Checking webhook");
|
||||||
match self.webhook_id.take() {
|
match self.webhook_id.take() {
|
||||||
Some(webhook_id) => {
|
Some(webhook_id) => {
|
||||||
|
tracing::warn!("stopping - unregistering webhook");
|
||||||
info!(%webhook_id, "Unregistring webhook");
|
info!(%webhook_id, "Unregistring webhook");
|
||||||
let forge = self.forge.clone();
|
let forge = self.forge.duplicate();
|
||||||
async move {
|
async move {
|
||||||
if let Err(err) = forge.unregister_webhook(&webhook_id).await {
|
if let Err(err) = forge.unregister_webhook(&webhook_id).await {
|
||||||
warn!("unregistering webhook: {err}");
|
warn!("unregistering webhook: {err}");
|
||||||
|
@ -88,259 +144,38 @@ impl Actor for RepoActor {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Message)]
|
pub fn do_send<M>(_addr: Addr<RepoActor>, msg: M, log: &Option<crate::RepoActorLog>)
|
||||||
#[rtype(result = "()")]
|
where
|
||||||
pub struct CloneRepo;
|
M: actix::Message + Send + 'static + std::fmt::Debug,
|
||||||
impl Handler<CloneRepo> for RepoActor {
|
RepoActor: actix::Handler<M>,
|
||||||
type Result = ();
|
<M as actix::Message>::Result: Send,
|
||||||
#[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 else {
|
|
||||||
warn!("missing open repository - can't load configuration");
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
let open_repository = open_repository.duplicate();
|
|
||||||
async move { repo_actor::load::load_file(details, addr, &*open_repository).await }
|
|
||||||
.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}");
|
let log_message = format!("send: {:?}", msg);
|
||||||
|
tracing::debug!(log_message);
|
||||||
|
logger(log, log_message);
|
||||||
|
#[cfg(not(test))]
|
||||||
|
_addr.do_send(msg)
|
||||||
}
|
}
|
||||||
}
|
|
||||||
.in_current_span()
|
pub async fn send<M>(
|
||||||
.into_actor(self)
|
addr: Addr<RepoActor>,
|
||||||
.wait(ctx);
|
msg: M,
|
||||||
}
|
log: &Option<crate::RepoActorLog>,
|
||||||
if let (Some(open_repository), Some(repo_config)) =
|
) -> std::result::Result<<M as actix::Message>::Result, actix::MailboxError>
|
||||||
(&self.open_repository, self.repo_details.repo_config.clone())
|
where
|
||||||
|
M: actix::Message + Send + 'static + std::fmt::Debug,
|
||||||
|
RepoActor: actix::Handler<M>,
|
||||||
|
<M as actix::Message>::Result: Send,
|
||||||
{
|
{
|
||||||
let repo_details = self.repo_details.clone();
|
let log_message = format!("send: {:?}", msg);
|
||||||
let addr = ctx.address();
|
logger(log, log_message);
|
||||||
let message_token = self.message_token;
|
addr.send(msg).await
|
||||||
let open_repository = open_repository.duplicate();
|
|
||||||
async move {
|
|
||||||
match validate_positions(&*open_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)]
|
pub fn logger(log: &Option<crate::RepoActorLog>, message: impl Into<String>) {
|
||||||
#[rtype(result = "()")]
|
if let Some(log) = log {
|
||||||
pub struct StartMonitoring {
|
let message: String = message.into();
|
||||||
main: git::Commit,
|
tracing::debug!(message);
|
||||||
next: git::Commit,
|
let _ = log.lock().map(|mut l| l.push(message));
|
||||||
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(open_repository) = &self.open_repository {
|
|
||||||
let open_repository = open_repository.duplicate();
|
|
||||||
let repo_details = self.repo_details.clone();
|
|
||||||
let message_token = self.message_token;
|
|
||||||
async move {
|
|
||||||
branch::advance_next(
|
|
||||||
msg.next,
|
|
||||||
msg.dev_commit_history,
|
|
||||||
repo_details,
|
|
||||||
repo_config,
|
|
||||||
&*open_repository,
|
|
||||||
addr,
|
|
||||||
message_token,
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
.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(open_repository) = &self.open_repository else {
|
|
||||||
warn!("No repository opened");
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
let repo_details = self.repo_details.clone();
|
|
||||||
let addr = ctx.address();
|
|
||||||
let message_token = self.message_token;
|
|
||||||
let open_repository = open_repository.duplicate();
|
|
||||||
async move {
|
|
||||||
branch::advance_main(msg.0, &repo_details, &repo_config, &*open_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)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -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: &dyn git::repository::OpenRepositoryLike,
|
open_repository: &dyn git::repository::OpenRepositoryLike,
|
||||||
) {
|
) -> 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) => {
|
|
||||||
error!(?err, "Failed to load config");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
info!("Loaded .git-next.toml from repo");
|
|
||||||
addr.do_send(LoadedConfig(repo_config));
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn load(
|
|
||||||
details: &git::RepoDetails,
|
|
||||||
open_repository: &dyn git::repository::OpenRepositoryLike,
|
|
||||||
) -> Result<config::RepoConfig, Error> {
|
|
||||||
let contents = open_repository.read_file(&details.branch, &PathBuf::from(".git-next.toml"))?;
|
|
||||||
let config = config::RepoConfig::parse(&contents)?;
|
let config = config::RepoConfig::parse(&contents)?;
|
||||||
let config = validate(config, open_repository).await?;
|
let branches = open_repository.remote_branches()?;
|
||||||
|
required_branch(&config.branches().main(), &branches)?;
|
||||||
|
required_branch(&config.branches().next(), &branches)?;
|
||||||
|
required_branch(&config.branches().dev(), &branches)?;
|
||||||
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: &dyn git::repository::OpenRepositoryLike,
|
|
||||||
) -> 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)
|
|
||||||
}
|
|
||||||
|
|
70
crates/repo-actor/src/messages.rs
Normal file
70
crates/repo-actor/src/messages.rs
Normal file
|
@ -0,0 +1,70 @@
|
||||||
|
//
|
||||||
|
use config::newtype;
|
||||||
|
use derive_more::Display;
|
||||||
|
|
||||||
|
use git_next_config as config;
|
||||||
|
use git_next_git as git;
|
||||||
|
|
||||||
|
#[macro_export]
|
||||||
|
macro_rules! message {
|
||||||
|
($name:ident wraps $value:ty) => {
|
||||||
|
git_next_config::newtype!($name is a $value);
|
||||||
|
impl actix::prelude::Message for $name {
|
||||||
|
type Result = ();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
($name:ident) => {
|
||||||
|
git_next_config::newtype!($name);
|
||||||
|
impl actix::prelude::Message for $name {
|
||||||
|
type Result = ();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
($name:ident wraps $value:ty => $result:ty) => {
|
||||||
|
git_next_config::newtype!($name is a $value);
|
||||||
|
impl actix::prelude::Message for $name {
|
||||||
|
type Result = $result;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
($name:ident => $result:ty) => {
|
||||||
|
git_next_config::newtype!($name);
|
||||||
|
impl actix::prelude::Message for $name {
|
||||||
|
type Result = $result;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
message!(LoadConfigFromRepo);
|
||||||
|
message!(CloneRepo);
|
||||||
|
message!(ReceiveRepoConfig wraps config::RepoConfig);
|
||||||
|
message!(ValidateRepo wraps MessageToken);
|
||||||
|
|
||||||
|
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))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
newtype!(MessageToken is a u32, Copy, Default, Display);
|
||||||
|
impl MessageToken {
|
||||||
|
pub const fn next(&self) -> Self {
|
||||||
|
Self(self.0 + 1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
message!(RegisterWebhook);
|
||||||
|
message!(CheckCIStatus wraps git::Commit); // next commit
|
||||||
|
message!(ReceiveCIStatus wraps (git::Commit, git::forge::commit::Status)); // commit and it's status
|
||||||
|
message!(AdvanceNext wraps (git::Commit, Vec<git::Commit>)); // next commit and the dev commit history
|
||||||
|
message!(AdvanceMain wraps git::Commit); // next commit
|
||||||
|
message!(WebhookNotification wraps config::webhook::forge_notification::ForgeNotification);
|
|
@ -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");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,34 +1,40 @@
|
||||||
//
|
//
|
||||||
use super::*;
|
#![allow(unused_imports)] // TODO remove this
|
||||||
mod branch {
|
|
||||||
use super::super::branch::*;
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
#[actix_rt::test]
|
use crate as actor;
|
||||||
async fn test_find_next_commit_on_dev() {
|
use actix::prelude::*;
|
||||||
let next = git::Commit::new(
|
use actor::{
|
||||||
git::commit::Sha::new("current-next".to_string()),
|
messages::{CloneRepo, MessageToken, WebhookRegistered},
|
||||||
git::commit::Message::new("foo".to_string()),
|
RepoActor, RepoActorLog,
|
||||||
);
|
};
|
||||||
let expected = git::Commit::new(
|
use assert2::let_assert;
|
||||||
git::commit::Sha::new("dev-next".to_string()),
|
use config::{BranchName, RegisteredWebhook, RepoBranches, RepoConfig};
|
||||||
git::commit::Message::new("next-should-go-here".to_string()),
|
use git::{
|
||||||
);
|
repository::{
|
||||||
let dev_commit_history = vec![
|
open::MockOpenRepositoryLike, Direction, MockRepositoryFactory, RepositoryFactory,
|
||||||
git::Commit::new(
|
},
|
||||||
git::commit::Sha::new("dev".to_string()),
|
validation::remotes,
|
||||||
git::commit::Message::new("future".to_string()),
|
GitRemote, RepoDetails,
|
||||||
),
|
};
|
||||||
expected.clone(),
|
use git_next_config as config;
|
||||||
next.clone(),
|
use git_next_forge as forge;
|
||||||
git::Commit::new(
|
use git_next_git as git;
|
||||||
git::commit::Sha::new("current-main".to_string()),
|
use mockall::predicate::eq;
|
||||||
git::commit::Message::new("history".to_string()),
|
use std::{
|
||||||
),
|
borrow::{Borrow, BorrowMut},
|
||||||
];
|
cell::{Cell, RefCell},
|
||||||
|
collections::HashMap,
|
||||||
|
path::PathBuf,
|
||||||
|
rc::Rc,
|
||||||
|
sync::{atomic::AtomicBool, Arc, Mutex},
|
||||||
|
};
|
||||||
|
|
||||||
let next_commit = find_next_commit_on_dev(next, dev_commit_history);
|
type TestResult = Result<(), Box<dyn std::error::Error>>;
|
||||||
|
|
||||||
assert_eq!(next_commit, Some(expected), "Found the wrong commit");
|
mod branch;
|
||||||
}
|
mod expect;
|
||||||
}
|
pub mod given;
|
||||||
|
mod handlers;
|
||||||
|
mod load;
|
||||||
|
pub mod then;
|
||||||
|
mod when;
|
||||||
|
|
21
crates/repo-actor/src/tests/branch.rs
Normal file
21
crates/repo-actor/src/tests/branch.rs
Normal file
|
@ -0,0 +1,21 @@
|
||||||
|
//
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
mod advance_main;
|
||||||
|
mod advance_next;
|
||||||
|
|
||||||
|
#[actix_rt::test]
|
||||||
|
async fn test_find_next_commit_on_dev() {
|
||||||
|
let next = given::a_commit();
|
||||||
|
let expected = given::a_commit();
|
||||||
|
let dev_commit_history = vec![
|
||||||
|
given::a_commit(), // dev HEAD
|
||||||
|
expected.clone(),
|
||||||
|
next.clone(), // next - advancing towards dev HEAD
|
||||||
|
given::a_commit(), // parent of next
|
||||||
|
];
|
||||||
|
|
||||||
|
let next_commit = actor::branch::find_next_commit_on_dev(&next, &dev_commit_history);
|
||||||
|
|
||||||
|
assert_eq!(next_commit, Some(expected), "Found the wrong commit");
|
||||||
|
}
|
35
crates/repo-actor/src/tests/branch/advance_main.rs
Normal file
35
crates/repo-actor/src/tests/branch/advance_main.rs
Normal file
|
@ -0,0 +1,35 @@
|
||||||
|
//
|
||||||
|
use git::repository::{OnFetch, OnPush, OpenRepositoryLike};
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn push_is_error_should_error() {
|
||||||
|
let commit = given::a_commit();
|
||||||
|
let fs = given::a_filesystem();
|
||||||
|
let repo_config = given::a_repo_config();
|
||||||
|
let (mut open_repository, repo_details) = given::an_open_repository(&fs);
|
||||||
|
expect::fetch_ok(&mut open_repository);
|
||||||
|
expect::push(&mut open_repository, Err(git::push::Error::Lock));
|
||||||
|
let_assert!(
|
||||||
|
Err(err) =
|
||||||
|
actor::branch::advance_main(commit, &repo_details, &repo_config, &open_repository)
|
||||||
|
);
|
||||||
|
assert!(matches!(
|
||||||
|
err,
|
||||||
|
actor::branch::Error::Push(git::push::Error::Lock)
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn push_is_ok_should_ok() {
|
||||||
|
let commit = given::a_commit();
|
||||||
|
let fs = given::a_filesystem();
|
||||||
|
let repo_config = given::a_repo_config();
|
||||||
|
let (mut open_repository, repo_details) = given::an_open_repository(&fs);
|
||||||
|
expect::fetch_ok(&mut open_repository);
|
||||||
|
expect::push_ok(&mut open_repository);
|
||||||
|
assert!(
|
||||||
|
actor::branch::advance_main(commit, &repo_details, &repo_config, &open_repository).is_ok()
|
||||||
|
);
|
||||||
|
}
|
165
crates/repo-actor/src/tests/branch/advance_next.rs
Normal file
165
crates/repo-actor/src/tests/branch/advance_next.rs
Normal file
|
@ -0,0 +1,165 @@
|
||||||
|
//
|
||||||
|
use super::*;
|
||||||
|
mod when_at_dev {
|
||||||
|
// next and dev branches are the same
|
||||||
|
use super::*;
|
||||||
|
#[test]
|
||||||
|
fn should_not_push() -> TestResult {
|
||||||
|
let next = given::a_commit();
|
||||||
|
let dev_commit_history = &[next.clone()];
|
||||||
|
let fs = given::a_filesystem();
|
||||||
|
let repo_config = given::a_repo_config();
|
||||||
|
let (open_repository, repo_details) = 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,
|
||||||
|
&open_repository,
|
||||||
|
message_token,
|
||||||
|
)
|
||||||
|
);
|
||||||
|
tracing::debug!("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::*;
|
||||||
|
#[test]
|
||||||
|
fn should_not_push() -> TestResult {
|
||||||
|
let next = given::a_commit();
|
||||||
|
let dev = given::a_commit_with_message("wip: test: message".to_string());
|
||||||
|
let dev_commit_history = &[dev, next.clone()];
|
||||||
|
let fs = given::a_filesystem();
|
||||||
|
let repo_config = given::a_repo_config();
|
||||||
|
let (open_repository, repo_details) = 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,
|
||||||
|
&open_repository,
|
||||||
|
message_token,
|
||||||
|
)
|
||||||
|
);
|
||||||
|
tracing::debug!("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::*;
|
||||||
|
#[test]
|
||||||
|
fn should_not_push_and_error() -> TestResult {
|
||||||
|
let next = given::a_commit();
|
||||||
|
let dev = given::a_commit();
|
||||||
|
let dev_commit_history = &[dev, next.clone()];
|
||||||
|
let fs = given::a_filesystem();
|
||||||
|
let repo_config = given::a_repo_config();
|
||||||
|
let (open_repository, repo_details) = 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,
|
||||||
|
&open_repository,
|
||||||
|
message_token,
|
||||||
|
)
|
||||||
|
);
|
||||||
|
tracing::debug!("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::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn should_error() -> TestResult {
|
||||||
|
let next = given::a_commit();
|
||||||
|
let dev = given::a_commit_with_message("test: message".to_string());
|
||||||
|
let dev_commit_history = &[dev, next.clone()];
|
||||||
|
let fs = given::a_filesystem();
|
||||||
|
let repo_config = given::a_repo_config();
|
||||||
|
let (mut open_repository, repo_details) = given::an_open_repository(&fs);
|
||||||
|
expect::fetch_ok(&mut open_repository);
|
||||||
|
expect::push(&mut open_repository, 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,
|
||||||
|
&open_repository,
|
||||||
|
message_token,
|
||||||
|
)
|
||||||
|
);
|
||||||
|
tracing::debug!("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::*;
|
||||||
|
#[test]
|
||||||
|
fn should_ok() -> TestResult {
|
||||||
|
let next = given::a_commit();
|
||||||
|
let dev = given::a_commit_with_message("test: message".to_string());
|
||||||
|
let dev_commit_history = &[dev, next.clone()];
|
||||||
|
let fs = given::a_filesystem();
|
||||||
|
let repo_config = given::a_repo_config();
|
||||||
|
let (mut open_repository, repo_details) = given::an_open_repository(&fs);
|
||||||
|
expect::fetch_ok(&mut open_repository);
|
||||||
|
expect::push_ok(&mut open_repository);
|
||||||
|
let message_token = given::a_message_token();
|
||||||
|
let_assert!(
|
||||||
|
Ok(mt) = actor::branch::advance_next(
|
||||||
|
&next,
|
||||||
|
dev_commit_history,
|
||||||
|
repo_details,
|
||||||
|
repo_config,
|
||||||
|
&open_repository,
|
||||||
|
message_token,
|
||||||
|
)
|
||||||
|
);
|
||||||
|
tracing::debug!("Got: {mt:?}");
|
||||||
|
assert_eq!(mt, message_token);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
58
crates/repo-actor/src/tests/expect.rs
Normal file
58
crates/repo-actor/src/tests/expect.rs
Normal file
|
@ -0,0 +1,58 @@
|
||||||
|
//
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
use git::repository::MockRepositoryFactory;
|
||||||
|
use git_next_git::repository::open::MockOpenRepositoryLike;
|
||||||
|
|
||||||
|
pub fn fetch_ok(open_repository: &mut MockOpenRepositoryLike) {
|
||||||
|
expect::fetch(open_repository, Ok(()));
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn fetch(open_repository: &mut MockOpenRepositoryLike, result: Result<(), git::fetch::Error>) {
|
||||||
|
open_repository
|
||||||
|
.expect_fetch()
|
||||||
|
.times(1)
|
||||||
|
.return_once(|| result);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn push_ok(open_repository: &mut MockOpenRepositoryLike) {
|
||||||
|
expect::push(open_repository, Ok(()))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn push(open_repository: &mut MockOpenRepositoryLike, result: Result<(), git::push::Error>) {
|
||||||
|
open_repository
|
||||||
|
.expect_push()
|
||||||
|
.times(1)
|
||||||
|
.return_once(move |_, _, _, _| result);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn duplicate(open_repository: &mut MockOpenRepositoryLike, result: MockOpenRepositoryLike) {
|
||||||
|
open_repository
|
||||||
|
.expect_duplicate()
|
||||||
|
.times(1)
|
||||||
|
.return_once(move || Box::new(result));
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn open_repository(
|
||||||
|
repository_factory: &mut MockRepositoryFactory,
|
||||||
|
open_repository: MockOpenRepositoryLike,
|
||||||
|
) {
|
||||||
|
repository_factory
|
||||||
|
.expect_open()
|
||||||
|
.times(1)
|
||||||
|
.return_once(move |_| Ok(Box::new(open_repository)));
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn main_commit_log(
|
||||||
|
validation_repo: &mut MockOpenRepositoryLike,
|
||||||
|
main_branch: config::BranchName,
|
||||||
|
) -> git::Commit {
|
||||||
|
let main_commit = given::a_commit();
|
||||||
|
let main_branch_log = vec![main_commit.clone()];
|
||||||
|
validation_repo
|
||||||
|
.expect_commit_log()
|
||||||
|
.times(1)
|
||||||
|
.with(eq(main_branch), eq([]))
|
||||||
|
.return_once(move |_, _| Ok(main_branch_log));
|
||||||
|
main_commit
|
||||||
|
}
|
366
crates/repo-actor/src/tests/given.rs
Normal file
366
crates/repo-actor/src/tests/given.rs
Normal file
|
@ -0,0 +1,366 @@
|
||||||
|
//
|
||||||
|
#![allow(dead_code)] // TODO: remove this
|
||||||
|
#![allow(unused_imports)] // TODO: remove this
|
||||||
|
|
||||||
|
use git_next_git::repository::RepositoryLike as _;
|
||||||
|
use mockall::predicate::eq;
|
||||||
|
use rand::RngCore;
|
||||||
|
use std::{
|
||||||
|
collections::HashMap,
|
||||||
|
path::PathBuf,
|
||||||
|
sync::{Arc, Mutex},
|
||||||
|
};
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
use config::{
|
||||||
|
server::{Webhook, WebhookUrl},
|
||||||
|
BranchName, ForgeAlias, ForgeConfig, ForgeType, GitDir, RepoAlias, RepoBranches, RepoConfig,
|
||||||
|
ServerRepoConfig, WebhookAuth, WebhookId,
|
||||||
|
};
|
||||||
|
use git::{
|
||||||
|
repository::{open::MockOpenRepositoryLike, Direction},
|
||||||
|
Generation, GitRemote, MockForgeLike, RepoDetails,
|
||||||
|
};
|
||||||
|
|
||||||
|
pub fn has_all_valid_remote_defaults(
|
||||||
|
open_repository: &mut MockOpenRepositoryLike,
|
||||||
|
repo_details: &RepoDetails,
|
||||||
|
) {
|
||||||
|
has_remote_defaults(
|
||||||
|
open_repository,
|
||||||
|
HashMap::from([
|
||||||
|
(Direction::Push, Some(repo_details.git_remote())),
|
||||||
|
(Direction::Fetch, Some(repo_details.git_remote())),
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn has_remote_defaults(
|
||||||
|
open_repository: &mut MockOpenRepositoryLike,
|
||||||
|
remotes: HashMap<Direction, Option<GitRemote>>,
|
||||||
|
) {
|
||||||
|
remotes.into_iter().for_each(|(direction, remote)| {
|
||||||
|
open_repository
|
||||||
|
.expect_find_default_remote()
|
||||||
|
.with(eq(direction))
|
||||||
|
.return_once(|_| remote);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn handles_validate_repo_message(
|
||||||
|
open_repository: &mut MockOpenRepositoryLike,
|
||||||
|
repo_branches: &RepoBranches,
|
||||||
|
) {
|
||||||
|
let validate_positions_open_repository = open_repository_for_validate_positions(repo_branches);
|
||||||
|
expect::duplicate(open_repository, validate_positions_open_repository);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(clippy::type_complexity)]
|
||||||
|
pub fn open_repository_for_loading_config_from_repo(
|
||||||
|
repo_config: &RepoConfig,
|
||||||
|
) -> (
|
||||||
|
MockOpenRepositoryLike,
|
||||||
|
Arc<Mutex<Vec<(BranchName, PathBuf)>>>,
|
||||||
|
) {
|
||||||
|
let mut load_config_from_repo_open_repository = MockOpenRepositoryLike::new();
|
||||||
|
let read_files = Arc::new(Mutex::new(vec![]));
|
||||||
|
let read_files_ref = read_files.clone();
|
||||||
|
let branches = repo_config.branches().clone();
|
||||||
|
load_config_from_repo_open_repository
|
||||||
|
.expect_read_file()
|
||||||
|
.return_once(move |branch_name, file_name| {
|
||||||
|
let branch_name = branch_name.clone();
|
||||||
|
let file_name = file_name.to_path_buf();
|
||||||
|
let _ = read_files_ref
|
||||||
|
.lock()
|
||||||
|
.map(move |mut l| l.push((branch_name, file_name)));
|
||||||
|
let contents = format!(
|
||||||
|
r#"
|
||||||
|
[branches]
|
||||||
|
main = "{}"
|
||||||
|
next = "{}"
|
||||||
|
dev = "{}"
|
||||||
|
"#,
|
||||||
|
branches.main(),
|
||||||
|
branches.next(),
|
||||||
|
branches.dev()
|
||||||
|
);
|
||||||
|
Ok(contents)
|
||||||
|
});
|
||||||
|
let branches = repo_config.branches().clone();
|
||||||
|
let remote_branches = vec![branches.main(), branches.next(), branches.dev()];
|
||||||
|
load_config_from_repo_open_repository
|
||||||
|
.expect_remote_branches()
|
||||||
|
.return_once(move || Ok(remote_branches));
|
||||||
|
(load_config_from_repo_open_repository, read_files)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn open_repository_for_validate_positions(branches: &RepoBranches) -> MockOpenRepositoryLike {
|
||||||
|
let mut open_repository = MockOpenRepositoryLike::new();
|
||||||
|
expect::fetch_ok(&mut open_repository);
|
||||||
|
let main_log = vec![given::a_commit()];
|
||||||
|
let next_commit_log_filter = main_log.clone();
|
||||||
|
let mut next_log: Vec<git::Commit> = main_log.clone();
|
||||||
|
next_log.extend(vec![given::a_commit()]);
|
||||||
|
let mut dev_log: Vec<git::Commit> = next_log.clone();
|
||||||
|
dev_log.extend(vec![given::a_commit()]);
|
||||||
|
|
||||||
|
open_repository
|
||||||
|
.expect_commit_log()
|
||||||
|
.times(1)
|
||||||
|
.with(eq(branches.main()), eq([]))
|
||||||
|
.return_once(move |_, _| Ok(main_log));
|
||||||
|
open_repository
|
||||||
|
.expect_commit_log()
|
||||||
|
.times(1)
|
||||||
|
.with(eq(branches.next()), eq(next_commit_log_filter.clone()))
|
||||||
|
.return_once(move |_, _| Ok(next_log));
|
||||||
|
open_repository
|
||||||
|
.expect_commit_log()
|
||||||
|
.times(1)
|
||||||
|
.with(eq(branches.dev()), eq(next_commit_log_filter))
|
||||||
|
.return_once(move |_, _| Ok(dev_log));
|
||||||
|
open_repository
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn a_webhook_auth() -> WebhookAuth {
|
||||||
|
WebhookAuth::generate()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub enum Header {
|
||||||
|
Valid(WebhookAuth, config::webhook::forge_notification::Body),
|
||||||
|
Missing,
|
||||||
|
Invalid,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn a_webhook_message_body() -> config::webhook::forge_notification::Body {
|
||||||
|
config::webhook::forge_notification::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(prefix: impl Into<String>) -> BranchName {
|
||||||
|
BranchName::new(format!("{}-{}", prefix.into(), 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("main").to_string();
|
||||||
|
let next = a_branch_name("next").to_string();
|
||||||
|
let dev = a_branch_name("dev").to_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_named_commit(name: impl Into<String>) -> git::Commit {
|
||||||
|
git::Commit::new(a_named_commit_sha(name), a_commit_message())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn a_commit() -> git::Commit {
|
||||||
|
git::Commit::new(a_commit_sha(), a_commit_message())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn a_commit_with_message(message: impl Into<git::commit::Message>) -> git::Commit {
|
||||||
|
git::Commit::new(a_commit_sha(), message.into())
|
||||||
|
}
|
||||||
|
|
||||||
|
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_named_commit_sha(name: impl Into<String>) -> git::commit::Sha {
|
||||||
|
git::commit::Sha::new(format!("{}-{}", name.into(), 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("webhook");
|
||||||
|
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::default();
|
||||||
|
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::open::MockOpenRepositoryLike,
|
||||||
|
git::RepoDetails,
|
||||||
|
) {
|
||||||
|
let open_repository = MockOpenRepositoryLike::new();
|
||||||
|
let gitdir = given::a_git_dir(fs);
|
||||||
|
let hostname = given::a_hostname();
|
||||||
|
let repo_details = given::repo_details(fs)
|
||||||
|
.with_gitdir(gitdir)
|
||||||
|
.with_hostname(hostname);
|
||||||
|
(open_repository, repo_details)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn a_message_token() -> MessageToken {
|
||||||
|
MessageToken::default()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn a_webhook(url: &WebhookUrl) -> Webhook {
|
||||||
|
Webhook::new(url.clone().into())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn a_forge() -> Box<MockForgeLike> {
|
||||||
|
Box::new(MockForgeLike::new())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn a_repo_actor(
|
||||||
|
repo_details: git::RepoDetails,
|
||||||
|
repository_factory: Box<dyn git::repository::RepositoryFactory>,
|
||||||
|
forge: Box<dyn git::ForgeLike>,
|
||||||
|
net: kxio::network::Network,
|
||||||
|
) -> (actor::RepoActor, RepoActorLog) {
|
||||||
|
let forge_alias = repo_details.forge.forge_alias();
|
||||||
|
let repo_alias = &repo_details.repo_alias;
|
||||||
|
let webhook_url = given::a_webhook_url(forge_alias, repo_alias);
|
||||||
|
let webhook = given::a_webhook(&webhook_url);
|
||||||
|
let generation = Generation::default();
|
||||||
|
let log = Arc::new(Mutex::new(vec![]));
|
||||||
|
let actors_log = log.clone();
|
||||||
|
(
|
||||||
|
actor::RepoActor::new(
|
||||||
|
repo_details,
|
||||||
|
forge,
|
||||||
|
webhook,
|
||||||
|
generation,
|
||||||
|
net,
|
||||||
|
repository_factory,
|
||||||
|
std::time::Duration::from_nanos(1),
|
||||||
|
)
|
||||||
|
.with_log(actors_log),
|
||||||
|
log,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn a_git_remote(repo_details: &git::RepoDetails) -> git::GitRemote {
|
||||||
|
let hostname = repo_details.forge.hostname().clone();
|
||||||
|
let repo_path = repo_details.repo_path.clone();
|
||||||
|
git::GitRemote::new(hostname, repo_path)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn a_hostname() -> config::Hostname {
|
||||||
|
config::Hostname::new(given::a_name())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn a_repo_path() -> config::RepoPath {
|
||||||
|
config::RepoPath::new(given::a_name())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn a_registered_webhook() -> RegisteredWebhook {
|
||||||
|
RegisteredWebhook::new(given::a_webhook_id(), given::a_webhook_auth())
|
||||||
|
}
|
13
crates/repo-actor/src/tests/handlers.rs
Normal file
13
crates/repo-actor/src/tests/handlers.rs
Normal file
|
@ -0,0 +1,13 @@
|
||||||
|
//
|
||||||
|
use super::*;
|
||||||
|
use actix::prelude::*;
|
||||||
|
|
||||||
|
mod advance_main;
|
||||||
|
mod advance_next;
|
||||||
|
mod check_ci_status;
|
||||||
|
mod clone_repo;
|
||||||
|
mod load_config_from_repo;
|
||||||
|
mod loaded_config;
|
||||||
|
mod receive_ci_status;
|
||||||
|
mod register_webhook;
|
||||||
|
mod validate_repo;
|
86
crates/repo-actor/src/tests/handlers/advance_main.rs
Normal file
86
crates/repo-actor/src/tests/handlers/advance_main.rs
Normal file
|
@ -0,0 +1,86 @@
|
||||||
|
//
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[actix::test]
|
||||||
|
async fn when_repo_config_should_fetch_then_push_then_revalidate() -> TestResult {
|
||||||
|
//given
|
||||||
|
let fs = given::a_filesystem();
|
||||||
|
let (mut open_repository, mut repo_details) = given::an_open_repository(&fs);
|
||||||
|
|
||||||
|
// config from repo
|
||||||
|
#[allow(clippy::unwrap_used)]
|
||||||
|
let repo_config = repo_details.repo_config.take().unwrap();
|
||||||
|
repo_details.repo_config = Some(repo_config.with_source(config::RepoConfigSource::Repo));
|
||||||
|
|
||||||
|
let next_commit = given::a_commit_with_message("feat: next".to_string());
|
||||||
|
|
||||||
|
let mut seq = mockall::Sequence::new();
|
||||||
|
open_repository
|
||||||
|
.expect_fetch()
|
||||||
|
.times(1)
|
||||||
|
.in_sequence(&mut seq)
|
||||||
|
.return_once(|| Ok(()));
|
||||||
|
open_repository
|
||||||
|
.expect_push()
|
||||||
|
.times(1)
|
||||||
|
.in_sequence(&mut seq)
|
||||||
|
.return_once(|_, _, _, _| Ok(()));
|
||||||
|
|
||||||
|
//when
|
||||||
|
let (addr, log) =
|
||||||
|
when::start_actor_with_open_repository(open_repository, repo_details, given::a_forge());
|
||||||
|
addr.send(actor::messages::AdvanceMain::new(next_commit.clone()))
|
||||||
|
.await?;
|
||||||
|
System::current().stop();
|
||||||
|
|
||||||
|
//then
|
||||||
|
tracing::debug!(?log, "");
|
||||||
|
log.lock().map_err(|e| e.to_string()).map(|l| {
|
||||||
|
assert!(l
|
||||||
|
.iter()
|
||||||
|
.any(|message| message.contains("send: LoadConfigFromRepo")))
|
||||||
|
})?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[actix::test]
|
||||||
|
async fn when_server_config_should_fetch_then_push_then_revalidate() -> TestResult {
|
||||||
|
//given
|
||||||
|
let fs = given::a_filesystem();
|
||||||
|
let (mut open_repository, mut repo_details) = given::an_open_repository(&fs);
|
||||||
|
|
||||||
|
// config from server
|
||||||
|
#[allow(clippy::unwrap_used)]
|
||||||
|
let repo_config = repo_details.repo_config.take().unwrap();
|
||||||
|
repo_details.repo_config = Some(repo_config.with_source(config::RepoConfigSource::Server));
|
||||||
|
|
||||||
|
let next_commit = given::a_commit_with_message("feat: next".to_string());
|
||||||
|
|
||||||
|
let mut seq = mockall::Sequence::new();
|
||||||
|
open_repository
|
||||||
|
.expect_fetch()
|
||||||
|
.times(1)
|
||||||
|
.in_sequence(&mut seq)
|
||||||
|
.return_once(|| Ok(()));
|
||||||
|
open_repository
|
||||||
|
.expect_push()
|
||||||
|
.times(1)
|
||||||
|
.in_sequence(&mut seq)
|
||||||
|
.return_once(|_, _, _, _| Ok(()));
|
||||||
|
|
||||||
|
//when
|
||||||
|
let (addr, log) =
|
||||||
|
when::start_actor_with_open_repository(open_repository, repo_details, given::a_forge());
|
||||||
|
addr.send(actor::messages::AdvanceMain::new(next_commit.clone()))
|
||||||
|
.await?;
|
||||||
|
System::current().stop();
|
||||||
|
|
||||||
|
//then
|
||||||
|
tracing::debug!(?log, "");
|
||||||
|
log.lock().map_err(|e| e.to_string()).map(|l| {
|
||||||
|
assert!(l
|
||||||
|
.iter()
|
||||||
|
.any(|message| message.contains("send: ValidateRepo")))
|
||||||
|
})?;
|
||||||
|
Ok(())
|
||||||
|
}
|
46
crates/repo-actor/src/tests/handlers/advance_next.rs
Normal file
46
crates/repo-actor/src/tests/handlers/advance_next.rs
Normal file
|
@ -0,0 +1,46 @@
|
||||||
|
//
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[actix::test]
|
||||||
|
async fn should_fetch_then_push_then_revalidate() -> TestResult {
|
||||||
|
//given
|
||||||
|
let fs = given::a_filesystem();
|
||||||
|
let (mut open_repository, repo_details) = given::an_open_repository(&fs);
|
||||||
|
let next_commit = given::a_commit_with_message("feat: next".to_string());
|
||||||
|
let dev_commit_log = vec![
|
||||||
|
given::a_commit_with_message("feat: dev".to_string()),
|
||||||
|
given::a_commit_with_message("feat: target".to_string()),
|
||||||
|
next_commit.clone(),
|
||||||
|
];
|
||||||
|
|
||||||
|
let mut seq = mockall::Sequence::new();
|
||||||
|
open_repository
|
||||||
|
.expect_fetch()
|
||||||
|
.times(1)
|
||||||
|
.in_sequence(&mut seq)
|
||||||
|
.return_once(|| Ok(()));
|
||||||
|
open_repository
|
||||||
|
.expect_push()
|
||||||
|
.times(1)
|
||||||
|
.in_sequence(&mut seq)
|
||||||
|
.return_once(|_, _, _, _| Ok(()));
|
||||||
|
|
||||||
|
//when
|
||||||
|
let (addr, log) =
|
||||||
|
when::start_actor_with_open_repository(open_repository, repo_details, given::a_forge());
|
||||||
|
addr.send(actor::messages::AdvanceNext::new((
|
||||||
|
next_commit.clone(),
|
||||||
|
dev_commit_log,
|
||||||
|
)))
|
||||||
|
.await?;
|
||||||
|
System::current().stop();
|
||||||
|
|
||||||
|
//then
|
||||||
|
tracing::debug!(?log, "");
|
||||||
|
log.lock().map_err(|e| e.to_string()).map(|l| {
|
||||||
|
assert!(l
|
||||||
|
.iter()
|
||||||
|
.any(|message| message.contains("send: ValidateRepo")))
|
||||||
|
})?;
|
||||||
|
Ok(())
|
||||||
|
}
|
32
crates/repo-actor/src/tests/handlers/check_ci_status.rs
Normal file
32
crates/repo-actor/src/tests/handlers/check_ci_status.rs
Normal file
|
@ -0,0 +1,32 @@
|
||||||
|
//
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[actix::test]
|
||||||
|
async fn should_passthrough_to_receive_ci_status() -> TestResult {
|
||||||
|
//given
|
||||||
|
let fs = given::a_filesystem();
|
||||||
|
let (open_repository, repo_details) = given::an_open_repository(&fs);
|
||||||
|
let next_commit = given::a_named_commit("next");
|
||||||
|
let mut forge = git::MockForgeLike::new();
|
||||||
|
when::commit_status(
|
||||||
|
&mut forge,
|
||||||
|
next_commit.clone(),
|
||||||
|
git::forge::commit::Status::Pass,
|
||||||
|
);
|
||||||
|
|
||||||
|
//when
|
||||||
|
let (addr, log) =
|
||||||
|
when::start_actor_with_open_repository(open_repository, repo_details, Box::new(forge));
|
||||||
|
addr.send(actor::messages::CheckCIStatus::new(next_commit.clone()))
|
||||||
|
.await?;
|
||||||
|
System::current().stop();
|
||||||
|
|
||||||
|
//then
|
||||||
|
tracing::debug!(?log, "");
|
||||||
|
log.lock().map_err(|e| e.to_string()).map(|l| {
|
||||||
|
assert!(l
|
||||||
|
.iter()
|
||||||
|
.any(|message| message.contains("send: ReceiveCIStatus")))
|
||||||
|
})?;
|
||||||
|
Ok(())
|
||||||
|
}
|
208
crates/repo-actor/src/tests/handlers/clone_repo.rs
Normal file
208
crates/repo-actor/src/tests/handlers/clone_repo.rs
Normal file
|
@ -0,0 +1,208 @@
|
||||||
|
//
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[actix::test]
|
||||||
|
async fn should_clone() -> TestResult {
|
||||||
|
//given
|
||||||
|
let fs = given::a_filesystem();
|
||||||
|
let (mut open_repository, /* mut */ repo_details) = given::an_open_repository(&fs);
|
||||||
|
// #[allow(clippy::unwrap_used)]
|
||||||
|
// let repo_config = repo_details.repo_config.take().unwrap();
|
||||||
|
|
||||||
|
given::has_all_valid_remote_defaults(&mut open_repository, &repo_details);
|
||||||
|
// handles_validate_repo_message(&mut open_repository, repo_config.branches());
|
||||||
|
|
||||||
|
// factory clones an open repository
|
||||||
|
let mut repository_factory = MockRepositoryFactory::new();
|
||||||
|
let cloned = Arc::new(Mutex::new(vec![]));
|
||||||
|
let cloned_ref = cloned.clone();
|
||||||
|
repository_factory
|
||||||
|
.expect_git_clone()
|
||||||
|
.times(2)
|
||||||
|
.return_once(move |_| {
|
||||||
|
let _ = cloned_ref.lock().map(|mut l| l.push(()));
|
||||||
|
Ok(Box::new(open_repository))
|
||||||
|
});
|
||||||
|
|
||||||
|
//when
|
||||||
|
let (addr, _log) = when::start_actor(repository_factory, repo_details, given::a_forge());
|
||||||
|
addr.send(CloneRepo::new()).await?;
|
||||||
|
System::current().stop();
|
||||||
|
|
||||||
|
//then
|
||||||
|
cloned
|
||||||
|
.lock()
|
||||||
|
.map_err(|e| e.to_string())
|
||||||
|
.map(|o| assert_eq!(o.len(), 1))?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[actix::test]
|
||||||
|
async fn should_open() -> TestResult {
|
||||||
|
//given
|
||||||
|
let fs = given::a_filesystem();
|
||||||
|
let (mut open_repository, /* mut */ repo_details) = given::an_open_repository(&fs);
|
||||||
|
// #[allow(clippy::unwrap_used)]
|
||||||
|
// let repo_config = repo_details.repo_config.take().unwrap();
|
||||||
|
|
||||||
|
given::has_all_valid_remote_defaults(&mut open_repository, &repo_details);
|
||||||
|
// handles_validate_repo_message(&mut open_repository, repo_config.branches());
|
||||||
|
|
||||||
|
// factory opens a repository
|
||||||
|
let mut repository_factory = MockRepositoryFactory::new();
|
||||||
|
let opened = Arc::new(Mutex::new(vec![]));
|
||||||
|
let opened_ref = opened.clone();
|
||||||
|
repository_factory
|
||||||
|
.expect_open()
|
||||||
|
.times(1)
|
||||||
|
.return_once(move |_| {
|
||||||
|
let _ = opened_ref.lock().map(|mut l| l.push(()));
|
||||||
|
Ok(Box::new(open_repository))
|
||||||
|
});
|
||||||
|
fs.dir_create(&repo_details.gitdir)?;
|
||||||
|
|
||||||
|
//when
|
||||||
|
let (addr, _log) = when::start_actor(repository_factory, repo_details, given::a_forge());
|
||||||
|
addr.send(CloneRepo::new()).await?;
|
||||||
|
System::current().stop();
|
||||||
|
|
||||||
|
//then
|
||||||
|
opened
|
||||||
|
.lock()
|
||||||
|
.map_err(|e| e.to_string())
|
||||||
|
.map(|o| assert_eq!(o.len(), 1))?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The server config can optionally include the names of the main, next and dev
|
||||||
|
/// branches. When it doesn't we should load the .git-next.yaml from from the
|
||||||
|
/// repo and get the branch names from there.
|
||||||
|
#[actix::test]
|
||||||
|
async fn when_server_has_no_repo_config_load_from_repo_and_validate() -> TestResult {
|
||||||
|
//given
|
||||||
|
let fs = given::a_filesystem();
|
||||||
|
let (mut open_repository, mut repo_details) = given::an_open_repository(&fs);
|
||||||
|
#[allow(clippy::unwrap_used)]
|
||||||
|
let repo_config = repo_details.repo_config.take().unwrap();
|
||||||
|
|
||||||
|
given::has_all_valid_remote_defaults(&mut open_repository, &repo_details);
|
||||||
|
|
||||||
|
// load config from repo
|
||||||
|
let (load_config_from_repo_open_repository, read_files) =
|
||||||
|
given::open_repository_for_loading_config_from_repo(&repo_config);
|
||||||
|
expect::duplicate(&mut open_repository, load_config_from_repo_open_repository);
|
||||||
|
|
||||||
|
// handles_validate_repo_message(&mut open_repository, repo_config.branches());
|
||||||
|
|
||||||
|
let mut repository_factory = MockRepositoryFactory::new();
|
||||||
|
expect::open_repository(&mut repository_factory, open_repository);
|
||||||
|
fs.dir_create(&repo_details.gitdir)?;
|
||||||
|
let branch = repo_details.branch.clone();
|
||||||
|
|
||||||
|
//when
|
||||||
|
let (addr, _log) = when::start_actor(repository_factory, repo_details, given::a_forge());
|
||||||
|
addr.send(CloneRepo::new()).await?;
|
||||||
|
System::current().stop();
|
||||||
|
|
||||||
|
//then
|
||||||
|
tracing::debug!("{read_files:#?}");
|
||||||
|
let file_name = PathBuf::from(".git-next.toml".to_string());
|
||||||
|
read_files
|
||||||
|
.lock()
|
||||||
|
.map_err(|e| e.to_string())
|
||||||
|
.map(|files| assert_eq!(files.clone(), vec![(branch, file_name)]))?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test_log::test(actix::test)]
|
||||||
|
async fn opened_repo_with_no_default_push_should_not_proceed() -> TestResult {
|
||||||
|
//given
|
||||||
|
let fs = given::a_filesystem();
|
||||||
|
let (mut open_repository, repo_details) = given::an_open_repository(&fs);
|
||||||
|
|
||||||
|
given::has_remote_defaults(
|
||||||
|
&mut open_repository,
|
||||||
|
HashMap::from([
|
||||||
|
(Direction::Push, None),
|
||||||
|
(Direction::Fetch, Some(repo_details.git_remote())),
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
|
||||||
|
let mut repository_factory = MockRepositoryFactory::new();
|
||||||
|
expect::open_repository(&mut repository_factory, open_repository);
|
||||||
|
fs.dir_create(&repo_details.gitdir)?;
|
||||||
|
|
||||||
|
//when
|
||||||
|
let (addr, log) = when::start_actor(repository_factory, repo_details, given::a_forge());
|
||||||
|
addr.send(CloneRepo::new()).await?;
|
||||||
|
System::current().stop();
|
||||||
|
|
||||||
|
//then
|
||||||
|
log.lock()
|
||||||
|
.map_err(|e| e.to_string())
|
||||||
|
// doesn't log that it sent any messages to load config or validate the repo
|
||||||
|
.map(|l| assert_eq!(l.clone(), vec!["open failed"]))?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test_log::test(actix::test)]
|
||||||
|
async fn opened_repo_with_no_default_fetch_should_not_proceed() -> TestResult {
|
||||||
|
//given
|
||||||
|
let fs = given::a_filesystem();
|
||||||
|
let (mut open_repository, repo_details) = given::an_open_repository(&fs);
|
||||||
|
|
||||||
|
given::has_remote_defaults(
|
||||||
|
&mut open_repository,
|
||||||
|
HashMap::from([
|
||||||
|
(Direction::Push, Some(repo_details.git_remote())),
|
||||||
|
(Direction::Fetch, None),
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
|
||||||
|
let mut repository_factory = MockRepositoryFactory::new();
|
||||||
|
expect::open_repository(&mut repository_factory, open_repository);
|
||||||
|
fs.dir_create(&repo_details.gitdir)?;
|
||||||
|
|
||||||
|
//when
|
||||||
|
let (addr, log) = when::start_actor(repository_factory, repo_details, given::a_forge());
|
||||||
|
addr.send(CloneRepo::new()).await?;
|
||||||
|
System::current().stop();
|
||||||
|
|
||||||
|
//then
|
||||||
|
log.lock()
|
||||||
|
.map_err(|e| e.to_string())
|
||||||
|
// doesn't log that it sent any messages to load config or validate the repo
|
||||||
|
.map(|l| assert_eq!(l.clone(), vec!["open failed"]))?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test_log::test(actix::test)]
|
||||||
|
async fn valid_repo_with_default_remotes_should_assess_branch_positions() -> TestResult {
|
||||||
|
//given
|
||||||
|
let fs = given::a_filesystem();
|
||||||
|
let (mut open_repository, repo_details) = given::an_open_repository(&fs);
|
||||||
|
|
||||||
|
given::has_all_valid_remote_defaults(&mut open_repository, &repo_details);
|
||||||
|
|
||||||
|
let mut repository_factory = MockRepositoryFactory::new();
|
||||||
|
expect::open_repository(&mut repository_factory, open_repository);
|
||||||
|
fs.dir_create(&repo_details.gitdir)?;
|
||||||
|
|
||||||
|
//when
|
||||||
|
let (addr, log) = when::start_actor(repository_factory, repo_details, given::a_forge());
|
||||||
|
addr.send(CloneRepo::new()).await?;
|
||||||
|
System::current().stop();
|
||||||
|
|
||||||
|
//then
|
||||||
|
log.lock()
|
||||||
|
.map_err(|e| e.to_string())
|
||||||
|
.map(|l| assert!(l.iter().any(|l| l.contains("send: ValidateRepo"))))?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
|
@ -0,0 +1,86 @@
|
||||||
|
//
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[actix::test]
|
||||||
|
async fn when_read_file_ok_should_send_config_loaded() -> TestResult {
|
||||||
|
//given
|
||||||
|
let fs = given::a_filesystem();
|
||||||
|
let (mut open_repository, repo_details) = given::an_open_repository(&fs);
|
||||||
|
let mut load_config_open_repo = MockOpenRepositoryLike::new();
|
||||||
|
let branches = given::repo_branches();
|
||||||
|
let remote_branches = vec![branches.main(), branches.next(), branches.dev()];
|
||||||
|
load_config_open_repo
|
||||||
|
.expect_read_file()
|
||||||
|
.return_once(move |_, _| {
|
||||||
|
Ok(format!(
|
||||||
|
r#"
|
||||||
|
[branches]
|
||||||
|
main = "{}"
|
||||||
|
next = "{}"
|
||||||
|
dev = "{}"
|
||||||
|
"#,
|
||||||
|
branches.main(),
|
||||||
|
branches.next(),
|
||||||
|
branches.dev()
|
||||||
|
))
|
||||||
|
});
|
||||||
|
|
||||||
|
load_config_open_repo
|
||||||
|
.expect_remote_branches()
|
||||||
|
.return_once(|| Ok(remote_branches));
|
||||||
|
|
||||||
|
open_repository
|
||||||
|
.expect_duplicate()
|
||||||
|
.return_once(|| Box::new(load_config_open_repo));
|
||||||
|
|
||||||
|
//when
|
||||||
|
let (addr, log) =
|
||||||
|
when::start_actor_with_open_repository(open_repository, repo_details, given::a_forge());
|
||||||
|
addr.send(actor::messages::LoadConfigFromRepo::new())
|
||||||
|
.await?;
|
||||||
|
System::current().stop();
|
||||||
|
|
||||||
|
//then
|
||||||
|
tracing::debug!(?log, "");
|
||||||
|
log.lock().map_err(|e| e.to_string()).map(|l| {
|
||||||
|
assert!(l
|
||||||
|
.iter()
|
||||||
|
.any(|message| message.contains("send: LoadedConfig")))
|
||||||
|
})?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[actix::test]
|
||||||
|
#[ignore] //TODO: (#95) should notify user
|
||||||
|
async fn when_read_file_err_should_notify_user() -> TestResult {
|
||||||
|
//given
|
||||||
|
let fs = given::a_filesystem();
|
||||||
|
let (mut open_repository, repo_details) = given::an_open_repository(&fs);
|
||||||
|
let mut load_config_open_repo = MockOpenRepositoryLike::new();
|
||||||
|
load_config_open_repo
|
||||||
|
.expect_read_file()
|
||||||
|
.return_once(move |_, _| Err(git::file::Error::FileNotFound));
|
||||||
|
|
||||||
|
open_repository
|
||||||
|
.expect_duplicate()
|
||||||
|
.return_once(|| Box::new(load_config_open_repo));
|
||||||
|
|
||||||
|
//when
|
||||||
|
let (addr, log) =
|
||||||
|
when::start_actor_with_open_repository(open_repository, repo_details, given::a_forge());
|
||||||
|
addr.send(actor::messages::LoadConfigFromRepo::new())
|
||||||
|
.await?;
|
||||||
|
System::current().stop();
|
||||||
|
|
||||||
|
//then
|
||||||
|
tracing::debug!(?log, "");
|
||||||
|
log.lock().map_err(|e| e.to_string()).map(|l| {
|
||||||
|
assert!(l.iter().any(|message| message.contains("send: NotifyUser")));
|
||||||
|
assert!(
|
||||||
|
!l.iter()
|
||||||
|
.any(|message| message.contains("send: LoadedConfig")),
|
||||||
|
"not send LoadedConfig"
|
||||||
|
);
|
||||||
|
})?;
|
||||||
|
Ok(())
|
||||||
|
}
|
95
crates/repo-actor/src/tests/handlers/loaded_config.rs
Normal file
95
crates/repo-actor/src/tests/handlers/loaded_config.rs
Normal file
|
@ -0,0 +1,95 @@
|
||||||
|
//
|
||||||
|
use super::*;
|
||||||
|
use actix::prelude::*;
|
||||||
|
|
||||||
|
#[actix::test]
|
||||||
|
async fn should_store_repo_config_in_actor() -> TestResult {
|
||||||
|
//given
|
||||||
|
let fs = given::a_filesystem();
|
||||||
|
let (open_repository, repo_details) = given::an_open_repository(&fs);
|
||||||
|
|
||||||
|
let new_repo_config = given::a_repo_config();
|
||||||
|
|
||||||
|
//when
|
||||||
|
let (addr, log) =
|
||||||
|
when::start_actor_with_open_repository(open_repository, repo_details, given::a_forge());
|
||||||
|
addr.send(actor::messages::ReceiveRepoConfig::new(
|
||||||
|
new_repo_config.clone(),
|
||||||
|
))
|
||||||
|
.await?;
|
||||||
|
System::current().stop();
|
||||||
|
|
||||||
|
//then
|
||||||
|
tracing::debug!(?log, "");
|
||||||
|
|
||||||
|
let repo_config = addr.send(TakeRepoConfig).await?;
|
||||||
|
assert_eq!(repo_config, Some(new_repo_config));
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[actix::test]
|
||||||
|
async fn should_validate_repo() -> TestResult {
|
||||||
|
//given
|
||||||
|
let fs = given::a_filesystem();
|
||||||
|
let (open_repository, repo_details) = given::an_open_repository(&fs);
|
||||||
|
|
||||||
|
let new_repo_config = given::a_repo_config();
|
||||||
|
|
||||||
|
//when
|
||||||
|
let (addr, log) =
|
||||||
|
when::start_actor_with_open_repository(open_repository, repo_details, given::a_forge());
|
||||||
|
addr.send(actor::messages::ReceiveRepoConfig::new(
|
||||||
|
new_repo_config.clone(),
|
||||||
|
))
|
||||||
|
.await?;
|
||||||
|
System::current().stop();
|
||||||
|
|
||||||
|
//then
|
||||||
|
tracing::debug!(?log, "");
|
||||||
|
log.lock().map_err(|e| e.to_string()).map(|l| {
|
||||||
|
assert!(l
|
||||||
|
.iter()
|
||||||
|
.any(|message| message.contains("send: ValidateRepo")))
|
||||||
|
})?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[actix::test]
|
||||||
|
async fn should_register_webhook() -> TestResult {
|
||||||
|
//given
|
||||||
|
let fs = given::a_filesystem();
|
||||||
|
let (open_repository, repo_details) = given::an_open_repository(&fs);
|
||||||
|
|
||||||
|
let new_repo_config = given::a_repo_config();
|
||||||
|
|
||||||
|
//when
|
||||||
|
let (addr, log) =
|
||||||
|
when::start_actor_with_open_repository(open_repository, repo_details, given::a_forge());
|
||||||
|
addr.send(actor::messages::ReceiveRepoConfig::new(
|
||||||
|
new_repo_config.clone(),
|
||||||
|
))
|
||||||
|
.await?;
|
||||||
|
System::current().stop();
|
||||||
|
|
||||||
|
//then
|
||||||
|
tracing::debug!(?log, "");
|
||||||
|
log.lock().map_err(|e| e.to_string()).map(|l| {
|
||||||
|
assert!(l
|
||||||
|
.iter()
|
||||||
|
.any(|message| message.contains("send: RegisterWebhook")))
|
||||||
|
})?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
actor::message!(TakeRepoConfig => Option<RepoConfig>);
|
||||||
|
|
||||||
|
impl Handler<TakeRepoConfig> for actor::RepoActor {
|
||||||
|
type Result = Option<RepoConfig>;
|
||||||
|
|
||||||
|
fn handle(&mut self, _msg: TakeRepoConfig, _ctx: &mut Self::Context) -> Self::Result {
|
||||||
|
tracing::debug!("TakeRepoConfig >>");
|
||||||
|
let repo_config = self.repo_details.repo_config.take();
|
||||||
|
tracing::debug!(?repo_config, "TakeRepoConfig <<");
|
||||||
|
repo_config
|
||||||
|
}
|
||||||
|
}
|
82
crates/repo-actor/src/tests/handlers/receive_ci_status.rs
Normal file
82
crates/repo-actor/src/tests/handlers/receive_ci_status.rs
Normal file
|
@ -0,0 +1,82 @@
|
||||||
|
//
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[actix::test]
|
||||||
|
async fn when_pass_should_advance_main_to_next() -> TestResult {
|
||||||
|
//given
|
||||||
|
let fs = given::a_filesystem();
|
||||||
|
let (open_repository, repo_details) = given::an_open_repository(&fs);
|
||||||
|
let next_commit = given::a_named_commit("next");
|
||||||
|
|
||||||
|
//when
|
||||||
|
let (addr, log) =
|
||||||
|
when::start_actor_with_open_repository(open_repository, repo_details, given::a_forge());
|
||||||
|
addr.send(actor::messages::ReceiveCIStatus::new((
|
||||||
|
next_commit.clone(),
|
||||||
|
git::forge::commit::Status::Pass,
|
||||||
|
)))
|
||||||
|
.await?;
|
||||||
|
System::current().stop();
|
||||||
|
|
||||||
|
//then
|
||||||
|
tracing::debug!(?log, "");
|
||||||
|
log.lock().map_err(|e| e.to_string()).map(|l| {
|
||||||
|
let expected = format!("send: AdvanceMain({:?})", next_commit);
|
||||||
|
tracing::debug!(%expected,"");
|
||||||
|
assert!(l.iter().any(|message| message.contains(&expected)))
|
||||||
|
})?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[actix::test]
|
||||||
|
async fn when_pending_should_recheck_ci_status() -> TestResult {
|
||||||
|
//given
|
||||||
|
let fs = given::a_filesystem();
|
||||||
|
let (open_repository, repo_details) = given::an_open_repository(&fs);
|
||||||
|
let next_commit = given::a_named_commit("next");
|
||||||
|
|
||||||
|
//when
|
||||||
|
let (addr, log) =
|
||||||
|
when::start_actor_with_open_repository(open_repository, repo_details, given::a_forge());
|
||||||
|
addr.send(actor::messages::ReceiveCIStatus::new((
|
||||||
|
next_commit.clone(),
|
||||||
|
git::forge::commit::Status::Pending,
|
||||||
|
)))
|
||||||
|
.await?;
|
||||||
|
System::current().stop();
|
||||||
|
|
||||||
|
//then
|
||||||
|
tracing::debug!(?log, "");
|
||||||
|
log.lock().map_err(|e| e.to_string()).map(|l| {
|
||||||
|
assert!(l
|
||||||
|
.iter()
|
||||||
|
.any(|message| message.contains("send: ValidateRepo")))
|
||||||
|
})?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[actix::test]
|
||||||
|
#[ignore] //TODO: (#95) should notify user
|
||||||
|
async fn when_fail_should_notify_user() -> TestResult {
|
||||||
|
//given
|
||||||
|
let fs = given::a_filesystem();
|
||||||
|
let (open_repository, repo_details) = given::an_open_repository(&fs);
|
||||||
|
let next_commit = given::a_named_commit("next");
|
||||||
|
|
||||||
|
//when
|
||||||
|
let (addr, log) =
|
||||||
|
when::start_actor_with_open_repository(open_repository, repo_details, given::a_forge());
|
||||||
|
addr.send(actor::messages::ReceiveCIStatus::new((
|
||||||
|
next_commit.clone(),
|
||||||
|
git::forge::commit::Status::Fail,
|
||||||
|
)))
|
||||||
|
.await?;
|
||||||
|
System::current().stop();
|
||||||
|
|
||||||
|
//then
|
||||||
|
tracing::debug!(?log, "");
|
||||||
|
log.lock()
|
||||||
|
.map_err(|e| e.to_string())
|
||||||
|
.map(|l| assert!(l.iter().any(|message| message.contains("send: NotifyUser"))))?;
|
||||||
|
Ok(())
|
||||||
|
}
|
64
crates/repo-actor/src/tests/handlers/register_webhook.rs
Normal file
64
crates/repo-actor/src/tests/handlers/register_webhook.rs
Normal file
|
@ -0,0 +1,64 @@
|
||||||
|
//
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[actix::test]
|
||||||
|
async fn when_registered_ok_should_send_webhook_registered() -> TestResult {
|
||||||
|
//given
|
||||||
|
let fs = given::a_filesystem();
|
||||||
|
let (open_repository, repo_details) = given::an_open_repository(&fs);
|
||||||
|
|
||||||
|
let registered_webhook = given::a_registered_webhook();
|
||||||
|
let mut my_forge = git::MockForgeLike::new();
|
||||||
|
my_forge
|
||||||
|
.expect_register_webhook()
|
||||||
|
.return_once(move |_| Ok(registered_webhook));
|
||||||
|
|
||||||
|
let mut forge = git::MockForgeLike::new();
|
||||||
|
forge.expect_duplicate().return_once(|| Box::new(my_forge));
|
||||||
|
|
||||||
|
//when
|
||||||
|
let (addr, log) =
|
||||||
|
when::start_actor_with_open_repository(open_repository, repo_details, Box::new(forge));
|
||||||
|
addr.send(actor::messages::RegisterWebhook::new()).await?;
|
||||||
|
System::current().stop();
|
||||||
|
|
||||||
|
//then
|
||||||
|
tracing::debug!(?log, "");
|
||||||
|
log.lock().map_err(|e| e.to_string()).map(|l| {
|
||||||
|
assert!(l
|
||||||
|
.iter()
|
||||||
|
.any(|message| message.contains("send: WebhookRegistered")))
|
||||||
|
})?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[actix::test]
|
||||||
|
#[ignore] //TODO: (#95) should notify user
|
||||||
|
async fn when_registered_error_should_send_notify_user() -> TestResult {
|
||||||
|
//given
|
||||||
|
let fs = given::a_filesystem();
|
||||||
|
let (open_repository, repo_details) = given::an_open_repository(&fs);
|
||||||
|
|
||||||
|
let mut my_forge = git::MockForgeLike::new();
|
||||||
|
my_forge.expect_register_webhook().return_once(move |_| {
|
||||||
|
Err(git::forge::webhook::Error::FailedToRegister(
|
||||||
|
"foo".to_string(),
|
||||||
|
))
|
||||||
|
});
|
||||||
|
|
||||||
|
let mut forge = git::MockForgeLike::new();
|
||||||
|
forge.expect_duplicate().return_once(|| Box::new(my_forge));
|
||||||
|
|
||||||
|
//when
|
||||||
|
let (addr, log) =
|
||||||
|
when::start_actor_with_open_repository(open_repository, repo_details, Box::new(forge));
|
||||||
|
addr.send(actor::messages::RegisterWebhook::new()).await?;
|
||||||
|
System::current().stop();
|
||||||
|
|
||||||
|
//then
|
||||||
|
tracing::debug!(?log, "");
|
||||||
|
log.lock()
|
||||||
|
.map_err(|e| e.to_string())
|
||||||
|
.map(|l| assert!(l.iter().any(|message| message.contains("send: NotifyUser"))))?;
|
||||||
|
Ok(())
|
||||||
|
}
|
375
crates/repo-actor/src/tests/handlers/validate_repo.rs
Normal file
375
crates/repo-actor/src/tests/handlers/validate_repo.rs
Normal file
|
@ -0,0 +1,375 @@
|
||||||
|
//
|
||||||
|
use crate::messages::{MessageToken, ValidateRepo};
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test_log::test(actix::test)]
|
||||||
|
async fn repo_with_next_not_an_ancestor_of_dev_should_be_reset() -> TestResult {
|
||||||
|
//given
|
||||||
|
let fs = given::a_filesystem();
|
||||||
|
let (mut open_repository, repo_details) = given::an_open_repository(&fs);
|
||||||
|
#[allow(clippy::unwrap_used)]
|
||||||
|
let repo_config = repo_details.repo_config.clone().unwrap();
|
||||||
|
expect::fetch_ok(&mut open_repository);
|
||||||
|
let branches = repo_config.branches();
|
||||||
|
// commit_log main
|
||||||
|
let main_commit = expect::main_commit_log(&mut open_repository, branches.main());
|
||||||
|
// next - based on main
|
||||||
|
let next_branch_log = vec![given::a_commit(), main_commit.clone()];
|
||||||
|
// dev - based on main, but not on next
|
||||||
|
let dev_branch_log = vec![given::a_commit(), main_commit.clone()];
|
||||||
|
// commit_log next - based on main, but not a parent of dev
|
||||||
|
open_repository
|
||||||
|
.expect_commit_log()
|
||||||
|
.times(1)
|
||||||
|
.with(eq(branches.next()), eq([main_commit.clone()]))
|
||||||
|
.return_once(move |_, _| Ok(next_branch_log));
|
||||||
|
// commit_log dev
|
||||||
|
open_repository
|
||||||
|
.expect_commit_log()
|
||||||
|
.times(1)
|
||||||
|
.with(eq(branches.dev()), eq([main_commit]))
|
||||||
|
.return_once(|_, _| Ok(dev_branch_log));
|
||||||
|
// expect to reset the branch
|
||||||
|
expect::fetch_ok(&mut open_repository);
|
||||||
|
expect::push_ok(&mut open_repository);
|
||||||
|
|
||||||
|
//when
|
||||||
|
let (addr, log) =
|
||||||
|
when::start_actor_with_open_repository(open_repository, repo_details, given::a_forge());
|
||||||
|
addr.send(crate::messages::ValidateRepo::new(MessageToken::default()))
|
||||||
|
.await?;
|
||||||
|
System::current().stop();
|
||||||
|
|
||||||
|
//then
|
||||||
|
tracing::debug!(?log, "");
|
||||||
|
log.lock().map_err(|e| e.to_string()).map(|l| {
|
||||||
|
assert!(l
|
||||||
|
.iter()
|
||||||
|
.any(|message| message.contains("NextBranchResetRequired")))
|
||||||
|
})?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test_log::test(actix::test)]
|
||||||
|
async fn repo_with_next_not_on_or_near_main_should_be_reset() -> TestResult {
|
||||||
|
//given
|
||||||
|
let fs = given::a_filesystem();
|
||||||
|
let (mut open_repository, repo_details) = given::an_open_repository(&fs);
|
||||||
|
#[allow(clippy::unwrap_used)]
|
||||||
|
let repo_config = repo_details.repo_config.clone().unwrap();
|
||||||
|
expect::fetch_ok(&mut open_repository);
|
||||||
|
let branches = repo_config.branches();
|
||||||
|
// commit_log main
|
||||||
|
let main_commit = expect::main_commit_log(&mut open_repository, branches.main());
|
||||||
|
// next - based on main, but too far in advance
|
||||||
|
let next_branch_log = vec![given::a_commit(), given::a_commit(), main_commit.clone()];
|
||||||
|
// dev - based on next
|
||||||
|
let mut dev_branch_log = vec![given::a_commit()];
|
||||||
|
dev_branch_log.extend(next_branch_log.clone());
|
||||||
|
// commit_log next
|
||||||
|
open_repository
|
||||||
|
.expect_commit_log()
|
||||||
|
.times(1)
|
||||||
|
.with(eq(branches.next()), eq([main_commit.clone()]))
|
||||||
|
.return_once(move |_, _| Ok(next_branch_log));
|
||||||
|
// commit_log dev
|
||||||
|
open_repository
|
||||||
|
.expect_commit_log()
|
||||||
|
.times(1)
|
||||||
|
.with(eq(branches.dev()), eq([main_commit]))
|
||||||
|
.return_once(|_, _| Ok(dev_branch_log));
|
||||||
|
expect::fetch_ok(&mut open_repository);
|
||||||
|
expect::push_ok(&mut open_repository);
|
||||||
|
|
||||||
|
//when
|
||||||
|
let (addr, log) =
|
||||||
|
when::start_actor_with_open_repository(open_repository, repo_details, given::a_forge());
|
||||||
|
addr.send(crate::messages::ValidateRepo::new(MessageToken::default()))
|
||||||
|
.await?;
|
||||||
|
System::current().stop();
|
||||||
|
|
||||||
|
//then
|
||||||
|
tracing::debug!(?log, "");
|
||||||
|
log.lock().map_err(|e| e.to_string()).map(|l| {
|
||||||
|
assert!(l
|
||||||
|
.iter()
|
||||||
|
.any(|message| message.contains("NextBranchResetRequired")))
|
||||||
|
})?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test_log::test(actix::test)]
|
||||||
|
async fn repo_with_next_not_based_on_main_should_be_reset() -> TestResult {
|
||||||
|
//given
|
||||||
|
let fs = given::a_filesystem();
|
||||||
|
let (mut open_repository, repo_details) = given::an_open_repository(&fs);
|
||||||
|
#[allow(clippy::unwrap_used)]
|
||||||
|
let repo_config = repo_details.repo_config.clone().unwrap();
|
||||||
|
// given::has_all_valid_remote_defaults(&mut open_repository, &repo_details);
|
||||||
|
expect::fetch_ok(&mut open_repository);
|
||||||
|
let branches = repo_config.branches();
|
||||||
|
// commit_log main
|
||||||
|
let main_commit = expect::main_commit_log(&mut open_repository, branches.main());
|
||||||
|
// next - not based on main
|
||||||
|
let next_branch_log = vec![given::a_commit(), given::a_commit(), given::a_commit()];
|
||||||
|
// dev - based on main
|
||||||
|
let dev_branch_log = vec![given::a_commit(), main_commit.clone()];
|
||||||
|
// commit_log next
|
||||||
|
open_repository
|
||||||
|
.expect_commit_log()
|
||||||
|
.times(1)
|
||||||
|
.with(eq(branches.next()), eq([main_commit.clone()]))
|
||||||
|
.return_once(move |_, _| Ok(next_branch_log));
|
||||||
|
// commit_log dev
|
||||||
|
open_repository
|
||||||
|
.expect_commit_log()
|
||||||
|
.times(1)
|
||||||
|
.with(eq(branches.dev()), eq([main_commit]))
|
||||||
|
.return_once(|_, _| Ok(dev_branch_log));
|
||||||
|
expect::fetch_ok(&mut open_repository);
|
||||||
|
expect::push_ok(&mut open_repository);
|
||||||
|
|
||||||
|
//when
|
||||||
|
let (addr, log) =
|
||||||
|
when::start_actor_with_open_repository(open_repository, repo_details, given::a_forge());
|
||||||
|
addr.send(crate::messages::ValidateRepo::new(MessageToken::default()))
|
||||||
|
.await?;
|
||||||
|
System::current().stop();
|
||||||
|
|
||||||
|
//then
|
||||||
|
tracing::debug!(?log, "");
|
||||||
|
log.lock().map_err(|e| e.to_string()).map(|l| {
|
||||||
|
assert!(l
|
||||||
|
.iter()
|
||||||
|
.any(|message| message.contains("NextBranchResetRequired")))
|
||||||
|
})?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test_log::test(actix::test)]
|
||||||
|
async fn repo_with_next_ahead_of_main_should_check_ci_status() -> TestResult {
|
||||||
|
//given
|
||||||
|
let fs = given::a_filesystem();
|
||||||
|
let (mut open_repository, repo_details) = given::an_open_repository(&fs);
|
||||||
|
#[allow(clippy::unwrap_used)]
|
||||||
|
let repo_config = repo_details.repo_config.clone().unwrap();
|
||||||
|
// Validate repo branches
|
||||||
|
expect::fetch_ok(&mut open_repository);
|
||||||
|
let branches = repo_config.branches();
|
||||||
|
// commit_log main
|
||||||
|
let main_commit = expect::main_commit_log(&mut open_repository, branches.main());
|
||||||
|
// next - ahead of main
|
||||||
|
let next_commit = given::a_named_commit("next");
|
||||||
|
let next_branch_log = vec![next_commit.clone(), main_commit.clone()];
|
||||||
|
// dev - on next
|
||||||
|
let dev_branch_log = next_branch_log.clone();
|
||||||
|
// commit_log next
|
||||||
|
open_repository
|
||||||
|
.expect_commit_log()
|
||||||
|
.times(1)
|
||||||
|
.with(eq(branches.next()), eq([main_commit.clone()]))
|
||||||
|
.return_once(move |_, _| Ok(next_branch_log));
|
||||||
|
// commit_log dev
|
||||||
|
open_repository
|
||||||
|
.expect_commit_log()
|
||||||
|
.times(1)
|
||||||
|
.with(eq(branches.dev()), eq([main_commit]))
|
||||||
|
.return_once(|_, _| Ok(dev_branch_log));
|
||||||
|
|
||||||
|
//when
|
||||||
|
let (addr, log) =
|
||||||
|
when::start_actor_with_open_repository(open_repository, repo_details, given::a_forge());
|
||||||
|
addr.send(crate::messages::ValidateRepo::new(MessageToken::default()))
|
||||||
|
.await?;
|
||||||
|
System::current().stop();
|
||||||
|
|
||||||
|
//then
|
||||||
|
tracing::debug!(?log, "");
|
||||||
|
log.lock().map_err(|e| e.to_string()).map(|l| {
|
||||||
|
let expected = format!("send: CheckCIStatus({next_commit:?})");
|
||||||
|
assert!(l.iter().any(|message| message.contains(&expected)))
|
||||||
|
})?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test_log::test(actix::test)]
|
||||||
|
async fn repo_with_dev_and_next_on_main_should_do_nothing() -> TestResult {
|
||||||
|
// Do nothing, when the situation changes we will hear about it via a webhook
|
||||||
|
//given
|
||||||
|
let fs = given::a_filesystem();
|
||||||
|
let (mut open_repository, repo_details) = given::an_open_repository(&fs);
|
||||||
|
#[allow(clippy::unwrap_used)]
|
||||||
|
let repo_config = repo_details.repo_config.clone().unwrap();
|
||||||
|
// Validate repo branches
|
||||||
|
expect::fetch_ok(&mut open_repository);
|
||||||
|
let branches = repo_config.branches();
|
||||||
|
// commit_log main
|
||||||
|
let main_commit = expect::main_commit_log(&mut open_repository, branches.main());
|
||||||
|
// next - on main
|
||||||
|
let next_branch_log = vec![main_commit.clone(), given::a_commit()];
|
||||||
|
// dev - on next
|
||||||
|
let dev_branch_log = next_branch_log.clone();
|
||||||
|
// commit_log next
|
||||||
|
open_repository
|
||||||
|
.expect_commit_log()
|
||||||
|
.times(1)
|
||||||
|
.with(eq(branches.next()), eq([main_commit.clone()]))
|
||||||
|
.return_once(move |_, _| Ok(next_branch_log));
|
||||||
|
// commit_log dev
|
||||||
|
let dev_commit_log = dev_branch_log.clone();
|
||||||
|
open_repository
|
||||||
|
.expect_commit_log()
|
||||||
|
.times(1)
|
||||||
|
.with(eq(branches.dev()), eq([main_commit]))
|
||||||
|
.return_once(move |_, _| Ok(dev_commit_log));
|
||||||
|
|
||||||
|
//when
|
||||||
|
let (addr, log) =
|
||||||
|
when::start_actor_with_open_repository(open_repository, repo_details, given::a_forge());
|
||||||
|
addr.send(crate::messages::ValidateRepo::new(MessageToken::default()))
|
||||||
|
.await?;
|
||||||
|
System::current().stop();
|
||||||
|
|
||||||
|
//then
|
||||||
|
tracing::debug!(?log, "");
|
||||||
|
log.lock()
|
||||||
|
.map_err(|e| e.to_string())
|
||||||
|
.map(|l| assert!(!l.iter().any(|message| message.contains("send:"))))?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test_log::test(actix::test)]
|
||||||
|
async fn repo_with_dev_ahead_of_next_should_advance_next() -> TestResult {
|
||||||
|
//given
|
||||||
|
let fs = given::a_filesystem();
|
||||||
|
let (mut open_repository, repo_details) = given::an_open_repository(&fs);
|
||||||
|
#[allow(clippy::unwrap_used)]
|
||||||
|
let repo_config = repo_details.repo_config.clone().unwrap();
|
||||||
|
// Validate repo branches
|
||||||
|
expect::fetch_ok(&mut open_repository);
|
||||||
|
let branches = repo_config.branches();
|
||||||
|
// commit_log main
|
||||||
|
let main_commit = expect::main_commit_log(&mut open_repository, branches.main());
|
||||||
|
// next - on main
|
||||||
|
let next_commit = main_commit.clone();
|
||||||
|
let next_branch_log = vec![main_commit.clone(), given::a_commit()];
|
||||||
|
// dev - ahead of next
|
||||||
|
let dev_commit = given::a_named_commit("dev");
|
||||||
|
let dev_branch_log = vec![dev_commit, main_commit.clone()];
|
||||||
|
// commit_log next
|
||||||
|
open_repository
|
||||||
|
.expect_commit_log()
|
||||||
|
.times(1)
|
||||||
|
.with(eq(branches.next()), eq([main_commit.clone()]))
|
||||||
|
.return_once(move |_, _| Ok(next_branch_log));
|
||||||
|
// commit_log dev
|
||||||
|
let dev_commit_log = dev_branch_log.clone();
|
||||||
|
open_repository
|
||||||
|
.expect_commit_log()
|
||||||
|
.times(1)
|
||||||
|
.with(eq(branches.dev()), eq([main_commit]))
|
||||||
|
.return_once(move |_, _| Ok(dev_commit_log));
|
||||||
|
|
||||||
|
//when
|
||||||
|
let (addr, log) =
|
||||||
|
when::start_actor_with_open_repository(open_repository, repo_details, given::a_forge());
|
||||||
|
addr.send(crate::messages::ValidateRepo::new(MessageToken::default()))
|
||||||
|
.await?;
|
||||||
|
System::current().stop();
|
||||||
|
|
||||||
|
//then
|
||||||
|
tracing::debug!(?log, "");
|
||||||
|
log.lock().map_err(|e| e.to_string()).map(|l| {
|
||||||
|
let expected = format!("send: AdvanceNext(({next_commit:?}, {dev_branch_log:?}))");
|
||||||
|
assert!(l.iter().any(|message| message.contains(&expected)))
|
||||||
|
})?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO: (#95) test: repo with dev not a child of main should notify user
|
||||||
|
|
||||||
|
#[test_log::test(actix::test)]
|
||||||
|
async fn should_accept_message_with_current_token() -> TestResult {
|
||||||
|
//given
|
||||||
|
let fs = given::a_filesystem();
|
||||||
|
let repo_details = given::repo_details(&fs);
|
||||||
|
|
||||||
|
//when
|
||||||
|
let (actor, log) = given::a_repo_actor(
|
||||||
|
repo_details,
|
||||||
|
git::repository::mock(),
|
||||||
|
given::a_forge(),
|
||||||
|
given::a_network().into(),
|
||||||
|
);
|
||||||
|
let actor = actor.with_message_token(MessageToken::new(2_u32));
|
||||||
|
let addr = actor.start();
|
||||||
|
addr.send(crate::messages::ValidateRepo::new(MessageToken::new(2_u32)))
|
||||||
|
.await?;
|
||||||
|
System::current().stop();
|
||||||
|
|
||||||
|
//then
|
||||||
|
tracing::debug!(?log, "");
|
||||||
|
log.lock().map_err(|e| e.to_string()).map(|l| {
|
||||||
|
assert!(l
|
||||||
|
.iter()
|
||||||
|
.any(|message| message.contains("accepted token: 2")))
|
||||||
|
})?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test_log::test(actix::test)]
|
||||||
|
async fn should_accept_message_with_new_token() -> TestResult {
|
||||||
|
//given
|
||||||
|
let fs = given::a_filesystem();
|
||||||
|
let repo_details = given::repo_details(&fs);
|
||||||
|
|
||||||
|
//when
|
||||||
|
let (actor, log) = given::a_repo_actor(
|
||||||
|
repo_details,
|
||||||
|
git::repository::mock(),
|
||||||
|
given::a_forge(),
|
||||||
|
given::a_network().into(),
|
||||||
|
);
|
||||||
|
let actor = actor.with_message_token(MessageToken::new(2_u32));
|
||||||
|
let addr = actor.start();
|
||||||
|
addr.send(crate::messages::ValidateRepo::new(MessageToken::new(3_u32)))
|
||||||
|
.await?;
|
||||||
|
System::current().stop();
|
||||||
|
|
||||||
|
//then
|
||||||
|
tracing::debug!(?log, "");
|
||||||
|
log.lock().map_err(|e| e.to_string()).map(|l| {
|
||||||
|
assert!(l
|
||||||
|
.iter()
|
||||||
|
.any(|message| message.contains("accepted token: 3")))
|
||||||
|
})?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test_log::test(actix::test)]
|
||||||
|
async fn should_reject_message_with_expired_token() -> TestResult {
|
||||||
|
//given
|
||||||
|
let fs = given::a_filesystem();
|
||||||
|
let repo_details = given::repo_details(&fs);
|
||||||
|
|
||||||
|
//when
|
||||||
|
let (actor, log) = given::a_repo_actor(
|
||||||
|
repo_details,
|
||||||
|
git::repository::mock(),
|
||||||
|
given::a_forge(),
|
||||||
|
given::a_network().into(),
|
||||||
|
);
|
||||||
|
let actor = actor.with_message_token(MessageToken::new(4_u32));
|
||||||
|
let addr = actor.start();
|
||||||
|
addr.send(crate::messages::ValidateRepo::new(MessageToken::new(3_u32)))
|
||||||
|
.await?;
|
||||||
|
System::current().stop();
|
||||||
|
|
||||||
|
//then
|
||||||
|
tracing::debug!(?log, "");
|
||||||
|
log.lock()
|
||||||
|
.map_err(|e| e.to_string())
|
||||||
|
.map(|l| assert!(!l.iter().any(|message| message.contains("accepted token"))))?;
|
||||||
|
Ok(())
|
||||||
|
}
|
183
crates/repo-actor/src/tests/load.rs
Normal file
183
crates/repo-actor/src/tests/load.rs
Normal file
|
@ -0,0 +1,183 @@
|
||||||
|
//
|
||||||
|
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 (mut open_repository, repo_details) = given::an_open_repository(&fs);
|
||||||
|
open_repository
|
||||||
|
.expect_read_file()
|
||||||
|
.returning(|_, _| Err(git::file::Error::FileNotFound));
|
||||||
|
//when
|
||||||
|
let_assert!(
|
||||||
|
Err(err) = actor::load::config_from_repository(repo_details, &open_repository).await
|
||||||
|
);
|
||||||
|
//then
|
||||||
|
tracing::debug!("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 (mut open_repository, repo_details) = given::an_open_repository(&fs);
|
||||||
|
let contents = given::a_name(); // not a valid file content
|
||||||
|
open_repository
|
||||||
|
.expect_read_file()
|
||||||
|
.return_once(move |_, _| Ok(contents));
|
||||||
|
//when
|
||||||
|
let_assert!(
|
||||||
|
Err(err) = actor::load::config_from_repository(repo_details, &open_repository).await
|
||||||
|
);
|
||||||
|
//then
|
||||||
|
tracing::debug!("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 (mut open_repository, repo_details) = given::an_open_repository(&fs);
|
||||||
|
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}"
|
||||||
|
"#
|
||||||
|
);
|
||||||
|
open_repository
|
||||||
|
.expect_read_file()
|
||||||
|
.return_once(|_, _| Ok(contents));
|
||||||
|
let branches = vec![next, dev];
|
||||||
|
open_repository
|
||||||
|
.expect_remote_branches()
|
||||||
|
.return_once(move || Ok(branches));
|
||||||
|
//when
|
||||||
|
let_assert!(
|
||||||
|
Err(err) = actor::load::config_from_repository(repo_details, &open_repository).await
|
||||||
|
);
|
||||||
|
//then
|
||||||
|
tracing::debug!("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 (mut open_repository, repo_details) = given::an_open_repository(&fs);
|
||||||
|
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}"
|
||||||
|
"#
|
||||||
|
);
|
||||||
|
open_repository
|
||||||
|
.expect_read_file()
|
||||||
|
.return_once(|_, _| Ok(contents));
|
||||||
|
let branches = vec![main, dev];
|
||||||
|
open_repository
|
||||||
|
.expect_remote_branches()
|
||||||
|
.return_once(move || Ok(branches));
|
||||||
|
//when
|
||||||
|
let_assert!(
|
||||||
|
Err(err) = actor::load::config_from_repository(repo_details, &open_repository).await
|
||||||
|
);
|
||||||
|
//then
|
||||||
|
tracing::debug!("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 (mut open_repository, repo_details) = given::an_open_repository(&fs);
|
||||||
|
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}"
|
||||||
|
"#
|
||||||
|
);
|
||||||
|
open_repository
|
||||||
|
.expect_read_file()
|
||||||
|
.return_once(move |_, _| Ok(contents));
|
||||||
|
let branches = vec![main, next];
|
||||||
|
open_repository
|
||||||
|
.expect_remote_branches()
|
||||||
|
.return_once(move || Ok(branches));
|
||||||
|
//when
|
||||||
|
let_assert!(
|
||||||
|
Err(err) = actor::load::config_from_repository(repo_details, &open_repository).await
|
||||||
|
);
|
||||||
|
//then
|
||||||
|
tracing::debug!("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 (mut open_repository, repo_details) = given::an_open_repository(&fs);
|
||||||
|
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}"
|
||||||
|
"#
|
||||||
|
);
|
||||||
|
open_repository
|
||||||
|
.expect_read_file()
|
||||||
|
.return_once(move |_, _| Ok(contents));
|
||||||
|
let branches = vec![main, next, dev];
|
||||||
|
open_repository
|
||||||
|
.expect_remote_branches()
|
||||||
|
.return_once(move || Ok(branches));
|
||||||
|
//when
|
||||||
|
let_assert!(
|
||||||
|
Ok(result) = actor::load::config_from_repository(repo_details, &open_repository).await
|
||||||
|
);
|
||||||
|
//then
|
||||||
|
tracing::debug!("Got: {result:?}");
|
||||||
|
assert_eq!(result, repo_config);
|
||||||
|
Ok(())
|
||||||
|
}
|
168
crates/repo-actor/src/tests/then.rs
Normal file
168
crates/repo-actor/src/tests/then.rs
Normal file
|
@ -0,0 +1,168 @@
|
||||||
|
//
|
||||||
|
#![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 {
|
||||||
|
tracing::debug!("== {label}");
|
||||||
|
match output {
|
||||||
|
Ok(output) => {
|
||||||
|
tracing::debug!(
|
||||||
|
"\nstdout:\n{}\nstderr:\n{}",
|
||||||
|
String::from_utf8_lossy(output.stdout.as_slice()),
|
||||||
|
String::from_utf8_lossy(output.stderr.as_slice())
|
||||||
|
);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
Err(err) => {
|
||||||
|
tracing::debug!("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()))
|
||||||
|
}
|
48
crates/repo-actor/src/tests/when.rs
Normal file
48
crates/repo-actor/src/tests/when.rs
Normal file
|
@ -0,0 +1,48 @@
|
||||||
|
//
|
||||||
|
use git::repository::OpenRepositoryLike;
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
pub fn start_actor(
|
||||||
|
repository_factory: git::repository::MockRepositoryFactory,
|
||||||
|
repo_details: git::RepoDetails,
|
||||||
|
forge: Box<dyn git::ForgeLike>,
|
||||||
|
) -> (actix::Addr<RepoActor>, RepoActorLog) {
|
||||||
|
let (actor, log) = given::a_repo_actor(
|
||||||
|
repo_details,
|
||||||
|
Box::new(repository_factory),
|
||||||
|
forge,
|
||||||
|
given::a_network().into(),
|
||||||
|
);
|
||||||
|
(actor.start(), log)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn start_actor_with_open_repository(
|
||||||
|
open_repository: MockOpenRepositoryLike,
|
||||||
|
repo_details: git::RepoDetails,
|
||||||
|
forge: Box<dyn git::ForgeLike>,
|
||||||
|
) -> (actix::Addr<RepoActor>, RepoActorLog) {
|
||||||
|
let (actor, log) = given::a_repo_actor(
|
||||||
|
repo_details,
|
||||||
|
git::repository::mock(),
|
||||||
|
forge,
|
||||||
|
given::a_network().into(),
|
||||||
|
);
|
||||||
|
let actor = actor.with_open_repository(Box::new(open_repository));
|
||||||
|
(actor.start(), log)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn commit_status(
|
||||||
|
forge: &mut git::MockForgeLike,
|
||||||
|
commit: git::Commit,
|
||||||
|
status: git::forge::commit::Status,
|
||||||
|
) {
|
||||||
|
let mut commit_status_forge = git::MockForgeLike::new();
|
||||||
|
commit_status_forge
|
||||||
|
.expect_commit_status()
|
||||||
|
.with(mockall::predicate::eq(commit))
|
||||||
|
.return_once(|_| status);
|
||||||
|
forge
|
||||||
|
.expect_duplicate()
|
||||||
|
.return_once(move || Box::new(commit_status_forge));
|
||||||
|
}
|
4
crates/server/src/actors/messages.rs
Normal file
4
crates/server/src/actors/messages.rs
Normal file
|
@ -0,0 +1,4 @@
|
||||||
|
use git_next_config::server::ServerConfig;
|
||||||
|
use git_next_repo_actor::message;
|
||||||
|
|
||||||
|
message!(ReceiveServerConfig wraps ServerConfig);
|
|
@ -1,3 +1,4 @@
|
||||||
pub mod file_watcher;
|
pub mod file_watcher;
|
||||||
|
pub mod messages;
|
||||||
pub mod server;
|
pub mod server;
|
||||||
pub mod webhook;
|
pub mod webhook;
|
||||||
|
|
|
@ -8,12 +8,14 @@ use git_next_config::{
|
||||||
self as config, ForgeAlias, ForgeConfig, GitDir, RepoAlias, ServerRepoConfig,
|
self as config, ForgeAlias, ForgeConfig, GitDir, RepoAlias, ServerRepoConfig,
|
||||||
};
|
};
|
||||||
use git_next_git::{repository::RepositoryFactory, Generation, RepoDetails};
|
use git_next_git::{repository::RepositoryFactory, Generation, RepoDetails};
|
||||||
use git_next_repo_actor::{CloneRepo, RepoActor};
|
use git_next_repo_actor::messages::CloneRepo;
|
||||||
|
use git_next_repo_actor::RepoActor;
|
||||||
use kxio::{fs::FileSystem, network::Network};
|
use kxio::{fs::FileSystem, network::Network};
|
||||||
use tracing::{error, info, warn};
|
use tracing::{error, info, warn};
|
||||||
|
|
||||||
use crate::actors::{
|
use crate::actors::{
|
||||||
file_watcher::FileUpdated,
|
file_watcher::FileUpdated,
|
||||||
|
messages::ReceiveServerConfig,
|
||||||
webhook::{AddWebhookRecipient, ShutdownWebhook, WebhookActor, WebhookRouter},
|
webhook::{AddWebhookRecipient, ShutdownWebhook, WebhookActor, WebhookRouter},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -39,6 +41,7 @@ pub struct Server {
|
||||||
fs: FileSystem,
|
fs: FileSystem,
|
||||||
net: Network,
|
net: Network,
|
||||||
repository_factory: Box<dyn RepositoryFactory>,
|
repository_factory: Box<dyn RepositoryFactory>,
|
||||||
|
sleep_duration: std::time::Duration,
|
||||||
}
|
}
|
||||||
impl Actor for Server {
|
impl Actor for Server {
|
||||||
type Context = Context<Self>;
|
type Context = Context<Self>;
|
||||||
|
@ -54,14 +57,14 @@ impl Handler<FileUpdated> for Server {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
ctx.notify(server_config);
|
ctx.notify(ReceiveServerConfig::new(server_config));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
impl Handler<ServerConfig> for Server {
|
impl Handler<ReceiveServerConfig> for Server {
|
||||||
type Result = ();
|
type Result = ();
|
||||||
|
|
||||||
#[allow(clippy::cognitive_complexity)] // TODO: (#75) reduce complexity
|
#[allow(clippy::cognitive_complexity)] // TODO: (#75) reduce complexity
|
||||||
fn handle(&mut self, msg: ServerConfig, _ctx: &mut Self::Context) -> Self::Result {
|
fn handle(&mut self, msg: ReceiveServerConfig, _ctx: &mut Self::Context) -> Self::Result {
|
||||||
let Ok(socket_addr) = msg.http() else {
|
let Ok(socket_addr) = msg.http() else {
|
||||||
warn!("Unable to parse http.addr");
|
warn!("Unable to parse http.addr");
|
||||||
return;
|
return;
|
||||||
|
@ -114,7 +117,12 @@ impl Handler<ServerConfig> for Server {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
impl Server {
|
impl Server {
|
||||||
pub fn new(fs: FileSystem, net: Network, repo: Box<dyn RepositoryFactory>) -> Self {
|
pub fn new(
|
||||||
|
fs: FileSystem,
|
||||||
|
net: Network,
|
||||||
|
repo: Box<dyn RepositoryFactory>,
|
||||||
|
sleep_duration: std::time::Duration,
|
||||||
|
) -> Self {
|
||||||
let generation = Generation::default();
|
let generation = Generation::default();
|
||||||
Self {
|
Self {
|
||||||
generation,
|
generation,
|
||||||
|
@ -122,6 +130,7 @@ impl Server {
|
||||||
fs,
|
fs,
|
||||||
net,
|
net,
|
||||||
repository_factory: repo,
|
repository_factory: repo,
|
||||||
|
sleep_duration,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
fn create_forge_data_directories(
|
fn create_forge_data_directories(
|
||||||
|
@ -182,6 +191,7 @@ impl Server {
|
||||||
let net = self.net.clone();
|
let net = self.net.clone();
|
||||||
let repository_factory = self.repository_factory.duplicate();
|
let repository_factory = self.repository_factory.duplicate();
|
||||||
let generation = self.generation;
|
let generation = self.generation;
|
||||||
|
let sleep_duration = self.sleep_duration;
|
||||||
move |(repo_alias, server_repo_config)| {
|
move |(repo_alias, server_repo_config)| {
|
||||||
let span = tracing::info_span!("create_actor", alias = %repo_alias, config = %server_repo_config);
|
let span = tracing::info_span!("create_actor", alias = %repo_alias, config = %server_repo_config);
|
||||||
let _guard = span.enter();
|
let _guard = span.enter();
|
||||||
|
@ -207,13 +217,16 @@ impl Server {
|
||||||
&forge_config,
|
&forge_config,
|
||||||
gitdir,
|
gitdir,
|
||||||
);
|
);
|
||||||
|
let forge = git_next_forge::Forge::create(repo_details.clone(), net.clone());
|
||||||
info!("Starting Repo Actor");
|
info!("Starting Repo Actor");
|
||||||
let actor = RepoActor::new(
|
let actor = RepoActor::new(
|
||||||
repo_details,
|
repo_details,
|
||||||
|
forge,
|
||||||
webhook.clone(),
|
webhook.clone(),
|
||||||
generation,
|
generation,
|
||||||
net.clone(),
|
net.clone(),
|
||||||
repository_factory.duplicate(),
|
repository_factory.duplicate(),
|
||||||
|
sleep_duration,
|
||||||
);
|
);
|
||||||
(forge_name.clone(), repo_alias, actor)
|
(forge_name.clone(), repo_alias, actor)
|
||||||
}
|
}
|
||||||
|
|
|
@ -4,7 +4,7 @@ use actix::prelude::*;
|
||||||
mod router;
|
mod router;
|
||||||
mod server;
|
mod server;
|
||||||
|
|
||||||
use git_next_config as config;
|
use git_next_repo_actor::messages::WebhookNotification;
|
||||||
|
|
||||||
use std::net::SocketAddr;
|
use std::net::SocketAddr;
|
||||||
|
|
||||||
|
@ -17,13 +17,10 @@ pub struct WebhookActor {
|
||||||
socket_addr: SocketAddr,
|
socket_addr: SocketAddr,
|
||||||
span: tracing::Span,
|
span: tracing::Span,
|
||||||
spawn_handle: Option<actix::SpawnHandle>,
|
spawn_handle: Option<actix::SpawnHandle>,
|
||||||
message_receiver: Recipient<config::WebhookMessage>,
|
message_receiver: Recipient<WebhookNotification>,
|
||||||
}
|
}
|
||||||
impl WebhookActor {
|
impl WebhookActor {
|
||||||
pub fn new(
|
pub fn new(socket_addr: SocketAddr, message_receiver: Recipient<WebhookNotification>) -> Self {
|
||||||
socket_addr: SocketAddr,
|
|
||||||
message_receiver: Recipient<config::WebhookMessage>,
|
|
||||||
) -> Self {
|
|
||||||
let span = tracing::info_span!("WebhookActor");
|
let span = tracing::info_span!("WebhookActor");
|
||||||
Self {
|
Self {
|
||||||
socket_addr,
|
socket_addr,
|
||||||
|
@ -37,7 +34,7 @@ impl Actor for WebhookActor {
|
||||||
type Context = actix::Context<Self>;
|
type Context = actix::Context<Self>;
|
||||||
fn started(&mut self, ctx: &mut Self::Context) {
|
fn started(&mut self, ctx: &mut Self::Context) {
|
||||||
let _gaurd = self.span.enter();
|
let _gaurd = self.span.enter();
|
||||||
let address: Recipient<config::WebhookMessage> = self.message_receiver.clone();
|
let address: Recipient<WebhookNotification> = self.message_receiver.clone();
|
||||||
let server = server::start(self.socket_addr, address);
|
let server = server::start(self.socket_addr, address);
|
||||||
let spawn_handle = ctx.spawn(server.in_current_span().into_actor(self));
|
let spawn_handle = ctx.spawn(server.in_current_span().into_actor(self));
|
||||||
self.spawn_handle.replace(spawn_handle);
|
self.spawn_handle.replace(spawn_handle);
|
||||||
|
|
|
@ -1,15 +1,15 @@
|
||||||
//
|
//
|
||||||
use std::collections::HashMap;
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
use actix::prelude::*;
|
use actix::prelude::*;
|
||||||
use derive_more::Constructor;
|
use derive_more::Constructor;
|
||||||
use git_next_config::WebhookMessage;
|
|
||||||
use git_next_config::{ForgeAlias, RepoAlias};
|
use git_next_config::{ForgeAlias, RepoAlias};
|
||||||
|
use git_next_repo_actor::messages::WebhookNotification;
|
||||||
use tracing::{debug, info};
|
use tracing::{debug, info};
|
||||||
|
|
||||||
pub struct WebhookRouter {
|
pub struct WebhookRouter {
|
||||||
span: tracing::Span,
|
span: tracing::Span,
|
||||||
recipients: HashMap<ForgeAlias, HashMap<RepoAlias, Recipient<WebhookMessage>>>,
|
recipients: BTreeMap<ForgeAlias, BTreeMap<RepoAlias, Recipient<WebhookNotification>>>,
|
||||||
}
|
}
|
||||||
impl WebhookRouter {
|
impl WebhookRouter {
|
||||||
pub fn new() -> Self {
|
pub fn new() -> Self {
|
||||||
|
@ -24,10 +24,10 @@ impl Actor for WebhookRouter {
|
||||||
type Context = Context<Self>;
|
type Context = Context<Self>;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Handler<WebhookMessage> for WebhookRouter {
|
impl Handler<WebhookNotification> for WebhookRouter {
|
||||||
type Result = ();
|
type Result = ();
|
||||||
|
|
||||||
fn handle(&mut self, msg: WebhookMessage, _ctx: &mut Self::Context) -> Self::Result {
|
fn handle(&mut self, msg: WebhookNotification, _ctx: &mut Self::Context) -> Self::Result {
|
||||||
let _gaurd = self.span.enter();
|
let _gaurd = self.span.enter();
|
||||||
let forge_alias = msg.forge_alias();
|
let forge_alias = msg.forge_alias();
|
||||||
let repo_alias = msg.repo_alias();
|
let repo_alias = msg.repo_alias();
|
||||||
|
@ -48,7 +48,7 @@ impl Handler<WebhookMessage> for WebhookRouter {
|
||||||
pub struct AddWebhookRecipient {
|
pub struct AddWebhookRecipient {
|
||||||
pub forge_alias: ForgeAlias,
|
pub forge_alias: ForgeAlias,
|
||||||
pub repo_alias: RepoAlias,
|
pub repo_alias: RepoAlias,
|
||||||
pub recipient: Recipient<WebhookMessage>,
|
pub recipient: Recipient<WebhookNotification>,
|
||||||
}
|
}
|
||||||
impl Handler<AddWebhookRecipient> for WebhookRouter {
|
impl Handler<AddWebhookRecipient> for WebhookRouter {
|
||||||
type Result = ();
|
type Result = ();
|
||||||
|
@ -58,7 +58,7 @@ impl Handler<AddWebhookRecipient> for WebhookRouter {
|
||||||
info!(forge = %msg.forge_alias, repo = %msg.repo_alias, "Register Recipient");
|
info!(forge = %msg.forge_alias, repo = %msg.repo_alias, "Register Recipient");
|
||||||
if !self.recipients.contains_key(&msg.forge_alias) {
|
if !self.recipients.contains_key(&msg.forge_alias) {
|
||||||
self.recipients
|
self.recipients
|
||||||
.insert(msg.forge_alias.clone(), HashMap::new());
|
.insert(msg.forge_alias.clone(), BTreeMap::new());
|
||||||
}
|
}
|
||||||
self.recipients
|
self.recipients
|
||||||
.get_mut(&msg.forge_alias)
|
.get_mut(&msg.forge_alias)
|
||||||
|
|
|
@ -1,16 +1,17 @@
|
||||||
//
|
//
|
||||||
use std::{collections::HashMap, net::SocketAddr};
|
use std::{collections::BTreeMap, net::SocketAddr};
|
||||||
|
|
||||||
use actix::prelude::*;
|
use actix::prelude::*;
|
||||||
|
|
||||||
use config::{ForgeAlias, RepoAlias};
|
use config::{ForgeAlias, RepoAlias};
|
||||||
use git_next_config as config;
|
use git_next_config as config;
|
||||||
|
|
||||||
|
use git_next_repo_actor::messages::WebhookNotification;
|
||||||
use tracing::{info, warn};
|
use tracing::{info, warn};
|
||||||
|
|
||||||
pub async fn start(
|
pub async fn start(
|
||||||
socket_addr: SocketAddr,
|
socket_addr: SocketAddr,
|
||||||
address: actix::prelude::Recipient<config::WebhookMessage>,
|
address: actix::prelude::Recipient<WebhookNotification>,
|
||||||
) {
|
) {
|
||||||
// start webhook server
|
// start webhook server
|
||||||
use warp::Filter;
|
use warp::Filter;
|
||||||
|
@ -22,7 +23,7 @@ pub async fn start(
|
||||||
.and(warp::header::headers_cloned())
|
.and(warp::header::headers_cloned())
|
||||||
.and(warp::body::bytes())
|
.and(warp::body::bytes())
|
||||||
.and_then(
|
.and_then(
|
||||||
|recipient: Recipient<config::WebhookMessage>,
|
|recipient: Recipient<WebhookNotification>,
|
||||||
forge_alias: String,
|
forge_alias: String,
|
||||||
repo_alias: String,
|
repo_alias: String,
|
||||||
// query: String,
|
// query: String,
|
||||||
|
@ -32,7 +33,7 @@ pub async fn start(
|
||||||
let forge_alias = ForgeAlias::new(forge_alias);
|
let forge_alias = ForgeAlias::new(forge_alias);
|
||||||
let repo_alias = RepoAlias::new(repo_alias);
|
let repo_alias = RepoAlias::new(repo_alias);
|
||||||
let bytes = body.to_vec();
|
let bytes = body.to_vec();
|
||||||
let body = config::webhook::message::Body::new(
|
let body = config::webhook::forge_notification::Body::new(
|
||||||
String::from_utf8_lossy(&bytes).to_string(),
|
String::from_utf8_lossy(&bytes).to_string(),
|
||||||
);
|
);
|
||||||
let headers = headers
|
let headers = headers
|
||||||
|
@ -40,8 +41,13 @@ pub async fn start(
|
||||||
.filter_map(|(k, v)| {
|
.filter_map(|(k, v)| {
|
||||||
k.map(|k| (k.to_string(), v.to_str().unwrap_or_default().to_string()))
|
k.map(|k| (k.to_string(), v.to_str().unwrap_or_default().to_string()))
|
||||||
})
|
})
|
||||||
.collect::<HashMap<String, String>>();
|
.collect::<BTreeMap<String, String>>();
|
||||||
let message = config::WebhookMessage::new(forge_alias, repo_alias, headers, body);
|
let message = WebhookNotification::new(config::ForgeNotification::new(
|
||||||
|
forge_alias,
|
||||||
|
repo_alias,
|
||||||
|
headers,
|
||||||
|
body,
|
||||||
|
));
|
||||||
recipient
|
recipient
|
||||||
.try_send(message)
|
.try_send(message)
|
||||||
.map(|_| {
|
.map(|_| {
|
||||||
|
|
|
@ -1,6 +1,6 @@
|
||||||
//
|
//
|
||||||
use assert2::let_assert;
|
use assert2::let_assert;
|
||||||
use git::{repository::Direction, validation::repo::validate_repo};
|
use git::{repository::Direction, validation::remotes::validate_default_remotes};
|
||||||
use git_next_config::{
|
use git_next_config::{
|
||||||
self as config, ForgeType, GitDir, Hostname, RepoBranches, RepoConfig, RepoConfigSource,
|
self as config, ForgeType, GitDir, Hostname, RepoBranches, RepoConfig, RepoConfigSource,
|
||||||
RepoPath,
|
RepoPath,
|
||||||
|
@ -46,7 +46,7 @@ fn gitdir_should_display_as_pathbuf() {
|
||||||
// git.kemitix.net:kemitix/git-next
|
// git.kemitix.net:kemitix/git-next
|
||||||
// If the default push remote is something else, then this test will fail
|
// If the default push remote is something else, then this test will fail
|
||||||
fn repo_details_find_default_push_remote_finds_correct_remote() -> Result<()> {
|
fn repo_details_find_default_push_remote_finds_correct_remote() -> Result<()> {
|
||||||
let cli_crate_dir = std::env::current_dir().map_err(git::validation::repo::Error::Io)?;
|
let cli_crate_dir = std::env::current_dir().map_err(git::validation::remotes::Error::Io)?;
|
||||||
let_assert!(Some(Some(root)) = cli_crate_dir.parent().map(|p| p.parent()));
|
let_assert!(Some(Some(root)) = cli_crate_dir.parent().map(|p| p.parent()));
|
||||||
let mut repo_details = git::common::repo_details(
|
let mut repo_details = git::common::repo_details(
|
||||||
1,
|
1,
|
||||||
|
@ -77,7 +77,7 @@ fn repo_details_find_default_push_remote_finds_correct_remote() -> Result<()> {
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn gitdir_validate_should_pass_a_valid_git_repo() -> Result<()> {
|
fn gitdir_validate_should_pass_a_valid_git_repo() -> Result<()> {
|
||||||
let cli_crate_dir = std::env::current_dir().map_err(git::validation::repo::Error::Io)?;
|
let cli_crate_dir = std::env::current_dir().map_err(git::validation::remotes::Error::Io)?;
|
||||||
let_assert!(Some(Some(root)) = cli_crate_dir.parent().map(|p| p.parent()));
|
let_assert!(Some(Some(root)) = cli_crate_dir.parent().map(|p| p.parent()));
|
||||||
let mut repo_details = git::common::repo_details(
|
let mut repo_details = git::common::repo_details(
|
||||||
1,
|
1,
|
||||||
|
@ -92,7 +92,7 @@ fn gitdir_validate_should_pass_a_valid_git_repo() -> Result<()> {
|
||||||
.with_hostname(Hostname::new("git.kemitix.net"));
|
.with_hostname(Hostname::new("git.kemitix.net"));
|
||||||
let gitdir = &repo_details.gitdir;
|
let gitdir = &repo_details.gitdir;
|
||||||
let repository = git::repository::real().open(gitdir)?;
|
let repository = git::repository::real().open(gitdir)?;
|
||||||
validate_repo(&*repository, &repo_details)?;
|
validate_default_remotes(&*repository, &repo_details)?;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
@ -100,7 +100,7 @@ fn gitdir_validate_should_pass_a_valid_git_repo() -> Result<()> {
|
||||||
#[test]
|
#[test]
|
||||||
fn gitdir_validate_should_fail_a_git_repo_with_wrong_remote() -> Result<()> {
|
fn gitdir_validate_should_fail_a_git_repo_with_wrong_remote() -> Result<()> {
|
||||||
let_assert!(
|
let_assert!(
|
||||||
Ok(cli_crate_dir) = std::env::current_dir().map_err(git::validation::repo::Error::Io)
|
Ok(cli_crate_dir) = std::env::current_dir().map_err(git::validation::remotes::Error::Io)
|
||||||
);
|
);
|
||||||
let_assert!(Some(Some(root)) = cli_crate_dir.parent().map(|p| p.parent()));
|
let_assert!(Some(Some(root)) = cli_crate_dir.parent().map(|p| p.parent()));
|
||||||
let repo_details = git::common::repo_details(
|
let repo_details = git::common::repo_details(
|
||||||
|
@ -113,7 +113,7 @@ fn gitdir_validate_should_fail_a_git_repo_with_wrong_remote() -> Result<()> {
|
||||||
.with_repo_path(RepoPath::new("hello/world".to_string()));
|
.with_repo_path(RepoPath::new("hello/world".to_string()));
|
||||||
let gitdir = &repo_details.gitdir;
|
let gitdir = &repo_details.gitdir;
|
||||||
let repository = git::repository::real().open(gitdir)?;
|
let repository = git::repository::real().open(gitdir)?;
|
||||||
let_assert!(Err(_) = validate_repo(&*repository, &repo_details));
|
let_assert!(Err(_) = validate_default_remotes(&*repository, &repo_details));
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
|
@ -37,11 +37,16 @@ pub fn init(fs: FileSystem) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn start(fs: FileSystem, net: Network, repo: Box<dyn RepositoryFactory>) {
|
pub async fn start(
|
||||||
|
fs: FileSystem,
|
||||||
|
net: Network,
|
||||||
|
repo: Box<dyn RepositoryFactory>,
|
||||||
|
sleep_duration: std::time::Duration,
|
||||||
|
) {
|
||||||
init_logging();
|
init_logging();
|
||||||
|
|
||||||
info!("Starting Server...");
|
info!("Starting Server...");
|
||||||
let server = Server::new(fs.clone(), net.clone(), repo).start();
|
let server = Server::new(fs.clone(), net.clone(), repo, sleep_duration).start();
|
||||||
server.do_send(FileUpdated);
|
server.do_send(FileUpdated);
|
||||||
|
|
||||||
info!("Starting File Watcher...");
|
info!("Starting File Watcher...");
|
||||||
|
|
Loading…
Reference in a new issue