From 6415d4658183551b234d43a73c40b3e7fb6acba6 Mon Sep 17 00:00:00 2001 From: Paul Campbell Date: Wed, 19 Jun 2024 07:03:08 +0100 Subject: [PATCH] WIP: refactor: repo-actor: rewrite tests using mockall --- .cargo/config.toml | 2 +- Cargo.toml | 1 + bacon.toml | 6 +- crates/cli/src/main.rs | 3 +- crates/config/src/repo_config.rs | 1 + crates/forge-forgejo/src/lib.rs | 3 + crates/forge-github/src/lib.rs | 3 + crates/forge/src/lib.rs | 13 + crates/forge/src/mock_forge.rs | 3 + crates/forge/src/tests.rs | 6 +- crates/git/src/forge/like.rs | 4 +- crates/git/src/lib.rs | 1 + crates/git/src/push.rs | 6 +- crates/git/src/repo_details.rs | 9 +- crates/git/src/repository/mod.rs | 13 +- crates/git/src/repository/tests.rs | 12 +- crates/git/src/validation/mod.rs | 2 +- crates/git/src/validation/positions.rs | 16 +- .../src/validation/{repo.rs => remotes.rs} | 2 +- crates/git/src/validation/tests.rs | 5 +- crates/repo-actor/Cargo.toml | 9 + crates/repo-actor/README.md | 33 + crates/repo-actor/src/branch.rs | 86 +- .../src/handlers/advance_to_main.rs | 56 + crates/repo-actor/src/handlers/clone.rs | 50 + .../handlers/dev_ahead_next_advance_next.rs | 50 + .../src/handlers/load_config_from_repo.rs | 34 + .../repo-actor/src/handlers/loaded_config.rs | 22 + crates/repo-actor/src/handlers/mod.rs | 10 + .../src/handlers/next_ahead_check_status.rs | 49 + .../src/handlers/register_webhook.rs | 37 + .../repo-actor/src/handlers/validate_repo.rs | 119 ++ .../webhook_message.rs} | 7 +- .../src/handlers/webhook_registered.rs | 17 + crates/repo-actor/src/lib.rs | 360 +--- crates/repo-actor/src/load.rs | 95 +- crates/repo-actor/src/messages.rs | 92 + crates/repo-actor/src/status.rs | 33 - crates/repo-actor/src/tests.rs | 1536 ++++++++++++++++- crates/server/src/actors/server.rs | 16 +- crates/server/src/config/tests.rs | 12 +- crates/server/src/lib.rs | 9 +- 42 files changed, 2364 insertions(+), 479 deletions(-) rename crates/git/src/validation/{repo.rs => remotes.rs} (98%) create mode 100644 crates/repo-actor/README.md create mode 100644 crates/repo-actor/src/handlers/advance_to_main.rs create mode 100644 crates/repo-actor/src/handlers/clone.rs create mode 100644 crates/repo-actor/src/handlers/dev_ahead_next_advance_next.rs create mode 100644 crates/repo-actor/src/handlers/load_config_from_repo.rs create mode 100644 crates/repo-actor/src/handlers/loaded_config.rs create mode 100644 crates/repo-actor/src/handlers/mod.rs create mode 100644 crates/repo-actor/src/handlers/next_ahead_check_status.rs create mode 100644 crates/repo-actor/src/handlers/register_webhook.rs create mode 100644 crates/repo-actor/src/handlers/validate_repo.rs rename crates/repo-actor/src/{webhook.rs => handlers/webhook_message.rs} (95%) create mode 100644 crates/repo-actor/src/handlers/webhook_registered.rs create mode 100644 crates/repo-actor/src/messages.rs delete mode 100644 crates/repo-actor/src/status.rs diff --git a/.cargo/config.toml b/.cargo/config.toml index 2082df4..8c6251c 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -13,5 +13,5 @@ debug = 0 strip = "debuginfo" [env] -RUSTLOG = "hyper=warn" +RUST_LOG = "hyper=warn,debug" RUSTFLAGS = "--cfg tokio_unstable" diff --git a/Cargo.toml b/Cargo.toml index f703b9a..d5e7c16 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -97,3 +97,4 @@ assert2 = "0.3" pretty_assertions = "1.4" rand = "0.8" mockall = "0.12" +test-log = "0.2" diff --git a/bacon.toml b/bacon.toml index 63dafe8..3d30b8b 100644 --- a/bacon.toml +++ b/bacon.toml @@ -4,7 +4,7 @@ # Complete help on configuration: https://dystroy.org/bacon/config/ default_job = "check" -reverse = true +# reverse = true [jobs.check] command = ["cargo", "check", "--color", "always"] @@ -48,7 +48,7 @@ need_stdout = false [jobs.doc-open] command = ["cargo", "doc", "--color", "always", "--no-deps", "--open"] need_stdout = false -on_success = "back" # so that we don't open the browser at each change +on_success = "back" # so that we don't open the browser at each change # You can run your application and have the result displayed in bacon, # *if* it makes sense for this crate. You can run an example the same @@ -57,7 +57,7 @@ on_success = "back" # so that we don't open the browser at each change # If you want to pass options to your program, a `--` separator # will be needed. [jobs.run] -command = [ "cargo", "run", "--color", "always" ] +command = ["cargo", "run", "--color", "always"] need_stdout = true allow_warnings = true diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs index a1023fb..c0ab962 100644 --- a/crates/cli/src/main.rs +++ b/crates/cli/src/main.rs @@ -42,7 +42,8 @@ async fn main() { git_next_server::init(fs); } 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; } }, } diff --git a/crates/config/src/repo_config.rs b/crates/config/src/repo_config.rs index d7661ca..db86a7e 100644 --- a/crates/config/src/repo_config.rs +++ b/crates/config/src/repo_config.rs @@ -16,6 +16,7 @@ use crate::RepoConfigSource; serde::Serialize, derive_more::Constructor, derive_more::Display, + derive_with::With, )] #[display("{}", branches)] pub struct RepoConfig { diff --git a/crates/forge-forgejo/src/lib.rs b/crates/forge-forgejo/src/lib.rs index 29a6f73..5241150 100644 --- a/crates/forge-forgejo/src/lib.rs +++ b/crates/forge-forgejo/src/lib.rs @@ -23,6 +23,9 @@ impl ForgeJo { } #[async_trait::async_trait] impl git::ForgeLike for ForgeJo { + fn duplicate(&self) -> Box { + Box::new(self.clone()) + } fn name(&self) -> String { "forgejo".to_string() } diff --git a/crates/forge-github/src/lib.rs b/crates/forge-github/src/lib.rs index 9fc660e..705b7a0 100644 --- a/crates/forge-github/src/lib.rs +++ b/crates/forge-github/src/lib.rs @@ -19,6 +19,9 @@ pub struct Github { } #[async_trait::async_trait] impl git::ForgeLike for Github { + fn duplicate(&self) -> Box { + Box::new(self.clone()) + } fn name(&self) -> String { "github".to_string() } diff --git a/crates/forge/src/lib.rs b/crates/forge/src/lib.rs index 8c43c25..b84aec4 100644 --- a/crates/forge/src/lib.rs +++ b/crates/forge/src/lib.rs @@ -17,6 +17,7 @@ pub enum Forge { Github(git_next_forge_github::Github), } impl Forge { + #[deprecated(note = "use Forge::create instead")] pub fn new(repo_details: git::RepoDetails, net: Network) -> Self { match repo_details.forge.forge_type() { #[cfg(feature = "forgejo")] @@ -30,6 +31,18 @@ impl Forge { git_next_config::ForgeType::MockForge => Self::Mock(mock_forge::MockForge::new()), } } + + pub fn create(repo_details: git::RepoDetails, net: Network) -> Box { + match repo_details.forge.forge_type() { + #[cfg(feature = "forgejo")] + git_next_config::ForgeType::ForgeJo => { + Box::new(forgejo::ForgeJo::new(repo_details, net)) + } + #[cfg(feature = "github")] + git_next_config::ForgeType::GitHub => Box::new(github::Github::new(repo_details, net)), + git_next_config::ForgeType::MockForge => Box::new(git::MockForgeLike::new()), + } + } } impl std::ops::Deref for Forge { type Target = dyn git::ForgeLike; diff --git a/crates/forge/src/mock_forge.rs b/crates/forge/src/mock_forge.rs index e32463d..f7afcd5 100644 --- a/crates/forge/src/mock_forge.rs +++ b/crates/forge/src/mock_forge.rs @@ -10,6 +10,9 @@ pub struct MockForge; #[async_trait::async_trait] impl git::ForgeLike for MockForge { + fn duplicate(&self) -> Box { + Box::new(self.clone()) + } fn name(&self) -> String { "mock".to_string() } diff --git a/crates/forge/src/tests.rs b/crates/forge/src/tests.rs index bf6a9cb..d1da8a0 100644 --- a/crates/forge/src/tests.rs +++ b/crates/forge/src/tests.rs @@ -8,7 +8,7 @@ use git_next_git::{self as git, RepoDetails}; 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); + let forge = Forge::create(repo_details, net); assert_eq!(forge.name(), "mock"); } @@ -16,7 +16,7 @@ fn test_mock_name() { fn test_forgejo_name() { let net = Network::new_mock(); 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"); } @@ -24,7 +24,7 @@ fn test_forgejo_name() { fn test_github_name() { let net = Network::new_mock(); 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"); } diff --git a/crates/git/src/forge/like.rs b/crates/git/src/forge/like.rs index 7ac484b..0236c34 100644 --- a/crates/git/src/forge/like.rs +++ b/crates/git/src/forge/like.rs @@ -1,8 +1,10 @@ use crate as git; use git_next_config as config; +#[mockall::automock] #[async_trait::async_trait] -pub trait ForgeLike { +pub trait ForgeLike: std::fmt::Debug + Send + Sync { + fn duplicate(&self) -> Box; fn name(&self) -> String; /// Checks that the message has a valid authorisation diff --git a/crates/git/src/lib.rs b/crates/git/src/lib.rs index db926a5..a04978e 100644 --- a/crates/git/src/lib.rs +++ b/crates/git/src/lib.rs @@ -17,6 +17,7 @@ mod tests; pub use commit::Commit; pub use forge::like::ForgeLike; +pub use forge::like::MockForgeLike; pub use generation::Generation; pub use git_ref::GitRef; pub use git_remote::GitRemote; diff --git a/crates/git/src/push.rs b/crates/git/src/push.rs index 9e3d987..adf1096 100644 --- a/crates/git/src/push.rs +++ b/crates/git/src/push.rs @@ -47,12 +47,12 @@ pub enum Error { } pub fn reset( - repository: &dyn git::repository::OpenRepositoryLike, + open_repository: &dyn git::repository::OpenRepositoryLike, repo_details: &git::RepoDetails, branch_name: &config::BranchName, to_commit: &git::GitRef, force: &git::push::Force, ) -> Result<()> { - repository.fetch()?; - repository.push(repo_details, branch_name, to_commit, force) + open_repository.fetch()?; + open_repository.push(repo_details, branch_name, to_commit, force) } diff --git a/crates/git/src/repo_details.rs b/crates/git/src/repo_details.rs index f0d761d..f5f53ac 100644 --- a/crates/git/src/repo_details.rs +++ b/crates/git/src/repo_details.rs @@ -1,7 +1,8 @@ -use git_next_config::{ +use config::{ BranchName, ForgeAlias, ForgeConfig, ForgeDetails, GitDir, RepoAlias, RepoConfig, RepoPath, ServerRepoConfig, }; +use git_next_config as config; use super::{Generation, GitRemote}; @@ -57,4 +58,10 @@ impl RepoDetails { pub fn git_remote(&self) -> GitRemote { 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 + } } diff --git a/crates/git/src/repository/mod.rs b/crates/git/src/repository/mod.rs index 42eeae9..78f7711 100644 --- a/crates/git/src/repository/mod.rs +++ b/crates/git/src/repository/mod.rs @@ -23,7 +23,7 @@ pub use real::RealRepository; use tracing::info; use crate::repository::test::TestRepository; -use crate::validation::repo::validate_repo; +use crate::validation::remotes::validate_default_remotes; use super::RepoDetails; @@ -52,19 +52,20 @@ pub const fn test(fs: kxio::fs::FileSystem) -> TestRepository { #[tracing::instrument(skip_all)] #[cfg(not(tarpaulin_include))] // requires network access to either clone new and/or fetch. pub fn open( - repository: &dyn RepositoryFactory, + repository_factory: &dyn RepositoryFactory, repo_details: &RepoDetails, gitdir: config::GitDir, ) -> Result> { let open_repository = if !gitdir.exists() { info!("Local copy not found - cloning..."); - repository.git_clone(repo_details)? + repository_factory.git_clone(repo_details)? } else { info!("Local copy found - opening..."); - repository.open(&gitdir)? + repository_factory.open(&gitdir)? }; 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) } @@ -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 { /// Push local changes to the remote. Push, diff --git a/crates/git/src/repository/tests.rs b/crates/git/src/repository/tests.rs index 695a27b..5ac458f 100644 --- a/crates/git/src/repository/tests.rs +++ b/crates/git/src/repository/tests.rs @@ -1,7 +1,7 @@ use crate as git; mod validate { - use crate::{tests::given, validation::repo::validate_repo}; + use crate::{tests::given, validation::remotes::validate_default_remotes}; use super::*; use git::repository::Direction; @@ -17,7 +17,7 @@ mod validate { .expect_find_default_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:?}"); assert!(result.is_ok()); } @@ -36,7 +36,7 @@ mod validate { 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:?}"); assert!(result.is_err()); } @@ -55,7 +55,7 @@ mod validate { Direction::Fetch => None, }); - let result = validate_repo(&*open_repository, &repo_details); + let result = validate_default_remotes(&*open_repository, &repo_details); println!("{result:?}"); assert!(result.is_err()); } @@ -74,7 +74,7 @@ mod validate { 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:?}"); assert!(result.is_err()); } @@ -93,7 +93,7 @@ mod validate { 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:?}"); assert!(result.is_err()); } diff --git a/crates/git/src/validation/mod.rs b/crates/git/src/validation/mod.rs index 628b5cf..0639673 100644 --- a/crates/git/src/validation/mod.rs +++ b/crates/git/src/validation/mod.rs @@ -1,5 +1,5 @@ pub mod positions; -pub mod repo; +pub mod remotes; #[cfg(test)] mod tests; diff --git a/crates/git/src/validation/positions.rs b/crates/git/src/validation/positions.rs index f8acd64..f0a6a62 100644 --- a/crates/git/src/validation/positions.rs +++ b/crates/git/src/validation/positions.rs @@ -45,6 +45,7 @@ pub fn validate_positions( .ok_or_else(|| Error::BranchHasNoCommits(dev_branch.clone()))?; // Validations: // Dev must be on main branch, else the USER must rebase it + tracing::debug!(dev=?commit_histories.dev, %main, "dev must be on main"); if is_not_based_on(&commit_histories.dev, &main) { warn!("Dev '{dev_branch}' not based on main '{main_branch}' - user must rebase",); return Err(Error::DevBranchNotBasedOn { @@ -53,16 +54,19 @@ 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 + tracing::debug!(next=?commit_histories.next[0..=1], %main, "next is on main, or at most one commit on top of 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",); 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 + tracing::debug!(dev=?commit_histories.dev, %next, "next is ancestor of dev"); if is_not_based_on(&commit_histories.dev, &next) { 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); } + tracing::debug!("branch positions okay"); Ok(git::validation::positions::Positions { main, next, @@ -72,14 +76,14 @@ pub fn validate_positions( } fn reset_next_to_main( - repository: &dyn crate::repository::OpenRepositoryLike, + open_repository: &dyn crate::repository::OpenRepositoryLike, repo_details: &crate::RepoDetails, main: &crate::Commit, next: &crate::Commit, next_branch: &config::BranchName, ) -> Result { git::push::reset( - repository, + open_repository, repo_details, next_branch, &main.clone().into(), @@ -100,13 +104,13 @@ fn is_not_based_on(commits: &[crate::commit::Commit], needle: &crate::Commit) -> } fn get_commit_histories( - repository: &dyn git::repository::OpenRepositoryLike, + open_repository: &dyn git::repository::OpenRepositoryLike, repo_config: &config::RepoConfig, ) -> git::commit::log::Result { - 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 next = repository.commit_log(&repo_config.branches().next(), &main_head)?; - let dev = repository.commit_log(&repo_config.branches().dev(), &main_head)?; + let next = open_repository.commit_log(&repo_config.branches().next(), &main_head)?; + let dev = open_repository.commit_log(&repo_config.branches().dev(), &main_head)?; let histories = git::commit::Histories { main, next, dev }; Ok(histories) } diff --git a/crates/git/src/validation/repo.rs b/crates/git/src/validation/remotes.rs similarity index 98% rename from crates/git/src/validation/repo.rs rename to crates/git/src/validation/remotes.rs index 46c9560..b13a71b 100644 --- a/crates/git/src/validation/repo.rs +++ b/crates/git/src/validation/remotes.rs @@ -3,7 +3,7 @@ use tracing::info; use crate as git; #[tracing::instrument(skip_all)] -pub fn validate_repo( +pub fn validate_default_remotes( open_repository: &dyn git::repository::OpenRepositoryLike, repo_details: &git::RepoDetails, ) -> Result<()> { diff --git a/crates/git/src/validation/tests.rs b/crates/git/src/validation/tests.rs index c4bc7a5..46096cb 100644 --- a/crates/git/src/validation/tests.rs +++ b/crates/git/src/validation/tests.rs @@ -33,12 +33,13 @@ mod repos { "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:?}"); let_assert!(Err(err) = result); assert!(matches!( err, - git::validation::repo::Error::NoDefaultPushRemote + git::validation::remotes::Error::NoDefaultPushRemote )); } } diff --git a/crates/repo-actor/Cargo.toml b/crates/repo-actor/Cargo.toml index 4daf772..408d52f 100644 --- a/crates/repo-actor/Cargo.toml +++ b/crates/repo-actor/Cargo.toml @@ -42,12 +42,21 @@ ulid = { workspace = true } # boilerplate derive_more = { workspace = true } +thiserror = { workspace = true } # Actors actix = { workspace = true } actix-rt = { workspace = true } tokio = { workspace = true } +[dev-dependencies] +# Testing +assert2 = { workspace = true } +rand = { workspace = true } +pretty_assertions = { workspace = true } +mockall = { workspace = true } +test-log = { workspace = true } + [lints.clippy] nursery = { level = "warn", priority = -1 } # pedantic = "warn" diff --git a/crates/repo-actor/README.md b/crates/repo-actor/README.md new file mode 100644 index 0000000..81e08a0 --- /dev/null +++ b/crates/repo-actor/README.md @@ -0,0 +1,33 @@ +```mermaid +stateDiagram-v2 +[*] --> CloneRepo :Start + +CloneRepo --> LoadConfigFromRepo +CloneRepo --> ValidateRepo + +LoadConfigFromRepo --> LoadedConfig + +ValidateRepo --> CheckCIStatus +ValidateRepo --> AdvanceNext +ValidateRepo --> ValidateRepo :invalid + +CheckCIStatus --> AdvanceMain :Pass +CheckCIStatus --> ValidateRepo :Pending +CheckCIStatus --> [*] :Fail + +AdvanceNext --> ValidateRepo + +LoadedConfig --> ValidateRepo +LoadedConfig --> RegisterWebhook + +RegisterWebhook --> WebhookRegistered + +WebhookRegistered --> [*] + +AdvanceMain --> LoadConfigFromRepo :on repo config - reload +AdvanceMain --> ValidateRepo :on server config + +[*] --> WebhookMessage :WEBHOOK + +WebhookMessage --> ValidateRepo +``` diff --git a/crates/repo-actor/src/branch.rs b/crates/repo-actor/src/branch.rs index a373f71..57c0aff 100644 --- a/crates/repo-actor/src/branch.rs +++ b/crates/repo-actor/src/branch.rs @@ -1,96 +1,100 @@ // -use actix::prelude::*; - +use crate::messages::MessageToken; use git_next_config as config; use git_next_git as git; + +use derive_more::Display; use tracing::{info, warn}; -use crate::{MessageToken, ValidateRepo}; - -use std::time::Duration; - // advance next to the next commit towards the head of the dev branch #[tracing::instrument(fields(next), skip_all)] -pub async fn advance_next( - next: git::Commit, - dev_commit_history: Vec, +pub fn advance_next( + next: &git::Commit, + dev_commit_history: &[git::Commit], repo_details: git::RepoDetails, repo_config: config::RepoConfig, open_repository: &dyn git::repository::OpenRepositoryLike, - addr: Addr, message_token: MessageToken, -) { - let next_commit = find_next_commit_on_dev(next, dev_commit_history); - let Some(commit) = next_commit else { - warn!("No commits to advance next to"); - return; - }; - if let Some(problem) = validate_commit_message(commit.message()) { - warn!("Can't advance next to commit '{}': {}", commit, problem); - return; - } +) -> Result { + let commit = + find_next_commit_on_dev(next, dev_commit_history).ok_or_else(|| Error::NextAtDev)?; + validate_commit_message(commit.message())?; info!("Advancing next to commit '{}'", commit); - if let Err(err) = git::push::reset( + git::push::reset( open_repository, &repo_details, &repo_config.branches().next(), &commit.into(), &git::push::Force::No, - ) { - warn!(?err, "Failed") - } - tokio::time::sleep(Duration::from_secs(10)).await; - addr.do_send(ValidateRepo { message_token }) + )?; + Ok(message_token) } #[tracing::instrument] -fn validate_commit_message(message: &git::commit::Message) -> Option { +fn validate_commit_message(message: &git::commit::Message) -> Result<()> { let message = &message.to_string(); if message.to_ascii_lowercase().starts_with("wip") { - return Some("Is Work-In-Progress".to_string()); + return Err(Error::IsWorkInProgress); } match git_conventional::Commit::parse(message) { Ok(commit) => { info!(?commit, "Pass"); - None + Ok(()) } Err(err) => { warn!(?err, "Fail"); - Some(err.kind().to_string()) + Err(Error::InvalidCommitMessage { + reason: err.kind().to_string(), + }) } } } pub fn find_next_commit_on_dev( - next: git::Commit, - dev_commit_history: Vec, + next: &git::Commit, + dev_commit_history: &[git::Commit], ) -> Option { - let mut next_commit: Option = None; - for commit in dev_commit_history.into_iter() { + let mut next_commit: Option<&git::Commit> = None; + for commit in dev_commit_history.iter() { if commit == next { break; }; next_commit.replace(commit); } - next_commit + next_commit.cloned() } // advance main branch to the commit 'next' #[tracing::instrument(fields(next), skip_all)] -pub async fn advance_main( +pub fn advance_main( next: git::Commit, repo_details: &git::RepoDetails, repo_config: &config::RepoConfig, open_repository: &dyn git::repository::OpenRepositoryLike, -) { +) -> Result<()> { info!("Advancing main to next"); - if let Err(err) = git::push::reset( + git::push::reset( open_repository, repo_details, &repo_config.branches().main(), &next.into(), &git::push::Force::No, - ) { - warn!(?err, "Failed") - }; + )?; + Ok(()) +} + +pub type Result = core::result::Result; +#[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 }, } diff --git a/crates/repo-actor/src/handlers/advance_to_main.rs b/crates/repo-actor/src/handlers/advance_to_main.rs new file mode 100644 index 0000000..67503d3 --- /dev/null +++ b/crates/repo-actor/src/handlers/advance_to_main.rs @@ -0,0 +1,56 @@ +// +use actix::prelude::*; +use tracing::Instrument as _; + +use crate as actor; + +impl Handler 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; + }; + self.open_repository.iter().for_each(|open_repository| { + let open_repository = open_repository.duplicate(); + let repo_details = self.repo_details.clone(); + let repo_config = repo_config.clone(); + let addr = ctx.address(); + let msg = msg.clone(); + 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(_) => { + async move { + match repo_config.source() { + git_next_config::RepoConfigSource::Repo => { + let _ = addr.send(actor::messages::LoadConfigFromRepo).await; + } + git_next_config::RepoConfigSource::Server => { + let _ = addr + .send(actor::messages::ValidateRepo::new(message_token)) + .await; + } + } + } + .in_current_span() + .into_actor(self) + .wait(ctx); + } + } + }); + } +} diff --git a/crates/repo-actor/src/handlers/clone.rs b/crates/repo-actor/src/handlers/clone.rs new file mode 100644 index 0000000..7951ce3 --- /dev/null +++ b/crates/repo-actor/src/handlers/clone.rs @@ -0,0 +1,50 @@ +// +use actix::prelude::*; + +use crate as actor; +use git_next_git as git; + +impl Handler 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) => { + #[cfg(test)] + 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"); + #[cfg(test)] + self.log("send: LoadConfigFromRepo"); + ctx.address().do_send(actor::messages::LoadConfigFromRepo); + } else { + tracing::debug!("Handler: CloneRepo: Sending: ValidateRepo"); + #[cfg(test)] + self.log("send: ValidateRepo"); + if let Err(_e) = ctx + .address() + .try_send(actor::messages::ValidateRepo::new(self.message_token)) + { + #[cfg(test)] + self.log(format!("ValidateRepo: error: {_e:?}")); + } + } + } + Err(err) => { + #[cfg(test)] + self.log("open failed"); + tracing::debug!("err: {err:?}"); + tracing::warn!("Could not open repo: {err}") + } + } + tracing::debug!("Handler: CloneRepo: finish"); + } +} diff --git a/crates/repo-actor/src/handlers/dev_ahead_next_advance_next.rs b/crates/repo-actor/src/handlers/dev_ahead_next_advance_next.rs new file mode 100644 index 0000000..1c8dfac --- /dev/null +++ b/crates/repo-actor/src/handlers/dev_ahead_next_advance_next.rs @@ -0,0 +1,50 @@ +// +use actix::prelude::*; +use tracing::Instrument as _; + +use crate as actor; + +impl Handler 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) => { + let sleep_duration = self.sleep_duration; + async move { + // pause to allow any CI checks to be started + tokio::time::sleep(sleep_duration).await; + let _ = addr + .send(actor::messages::ValidateRepo::new(message_token)) + .await; + } + .in_current_span() + .into_actor(self) + .wait(ctx); + } + Err(err) => tracing::warn!("advance next: {err}"), + } + } +} diff --git a/crates/repo-actor/src/handlers/load_config_from_repo.rs b/crates/repo-actor/src/handlers/load_config_from_repo.rs new file mode 100644 index 0000000..983f7af --- /dev/null +++ b/crates/repo-actor/src/handlers/load_config_from_repo.rs @@ -0,0 +1,34 @@ +// +use actix::prelude::*; +use tracing::Instrument as _; + +use crate as actor; + +impl Handler 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"); + self.open_repository.iter().for_each(|open_repository| { + let open_repository = open_repository.duplicate(); + let repo_details = self.repo_details.clone(); + let addr = ctx.address(); + async move { + match actor::load::config_from_repository(repo_details, &*open_repository).await { + Ok(repo_config) => { + addr.do_send(actor::messages::LoadedConfig::new(repo_config)) + } + Err(err) => tracing::warn!(?err, "Failed to load config"), + } + } + .in_current_span() + .into_actor(self) + .wait(ctx); + }); + tracing::debug!("Handler: LoadConfigFromRepo: finish"); + } +} diff --git a/crates/repo-actor/src/handlers/loaded_config.rs b/crates/repo-actor/src/handlers/loaded_config.rs new file mode 100644 index 0000000..75facc6 --- /dev/null +++ b/crates/repo-actor/src/handlers/loaded_config.rs @@ -0,0 +1,22 @@ +// +use actix::prelude::*; + +use crate as actor; + +impl Handler for actor::RepoActor { + type Result = (); + #[tracing::instrument(name = "RepoActor::LoadedConfig", skip_all, fields(repo = %self.repo_details, branches = ?msg))] + fn handle( + &mut self, + msg: actor::messages::LoadedConfig, + ctx: &mut Self::Context, + ) -> Self::Result { + let repo_config = msg.unwrap(); + self.repo_details.repo_config.replace(repo_config); + + ctx.address() + .do_send(actor::messages::ValidateRepo::new(self.message_token)); + ctx.address() + .do_send(actor::messages::RegisterWebhook::new()); + } +} diff --git a/crates/repo-actor/src/handlers/mod.rs b/crates/repo-actor/src/handlers/mod.rs new file mode 100644 index 0000000..ad3ae70 --- /dev/null +++ b/crates/repo-actor/src/handlers/mod.rs @@ -0,0 +1,10 @@ +pub mod advance_to_main; +pub mod clone; +pub mod dev_ahead_next_advance_next; +pub mod load_config_from_repo; +pub mod loaded_config; +pub mod next_ahead_check_status; +pub mod register_webhook; +pub mod validate_repo; +pub mod webhook_message; +pub mod webhook_registered; diff --git a/crates/repo-actor/src/handlers/next_ahead_check_status.rs b/crates/repo-actor/src/handlers/next_ahead_check_status.rs new file mode 100644 index 0000000..f1a71ee --- /dev/null +++ b/crates/repo-actor/src/handlers/next_ahead_check_status.rs @@ -0,0 +1,49 @@ +// +use actix::prelude::*; +use tracing::Instrument as _; + +use crate as actor; +use git_next_git as git; + +impl Handler for actor::RepoActor { + type Result = (); + + fn handle( + &mut self, + msg: actor::messages::CheckCIStatus, + ctx: &mut Self::Context, + ) -> Self::Result { + #[cfg(test)] + self.log("start: NextAheadOfMainCheckStatus"); + let addr = ctx.address(); + let forge = self.forge.duplicate(); + let next = msg.unwrap(); + let message_token = self.message_token; + let sleep_duration = self.sleep_duration; + async move { + // get the status - pass, fail, pending (all others map to fail, e.g. error) + let status = forge.commit_status(&next).await; + tracing::info!(?status, "Checking next branch"); + match status { + git::forge::commit::Status::Pass => { + let _ = addr + .send(actor::messages::AdvanceMain::new(next.clone())) + .await; + } + git::forge::commit::Status::Pending => { + tokio::time::sleep(sleep_duration).await; + let _ = addr + .send(actor::messages::ValidateRepo::new(message_token)) + .await; + } + git::forge::commit::Status::Fail => { + tracing::warn!("Checks have failed"); + // TODO: (#88) recheck after a longer than normal delay + } + } + } + .in_current_span() + .into_actor(self) + .wait(ctx); + } +} diff --git a/crates/repo-actor/src/handlers/register_webhook.rs b/crates/repo-actor/src/handlers/register_webhook.rs new file mode 100644 index 0000000..c39c774 --- /dev/null +++ b/crates/repo-actor/src/handlers/register_webhook.rs @@ -0,0 +1,37 @@ +// +use actix::prelude::*; +use tracing::Instrument as _; + +use crate as actor; +use actor::{messages::RegisterWebhook, RepoActor}; + +impl Handler 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(); + tracing::debug!("registering webhook"); + async move { + match forge.register_webhook(&webhook_url).await { + Ok(registered_webhook) => { + tracing::debug!(?registered_webhook, ""); + let _ = addr + .send(actor::messages::WebhookRegistered::from(registered_webhook)) + .await; + tracing::debug!("message sent"); + } + Err(err) => tracing::warn!(?err, "registering webhook"), + } + } + .in_current_span() + .into_actor(self) + .wait(ctx); + tracing::debug!("registering webhook done"); + } + } +} diff --git a/crates/repo-actor/src/handlers/validate_repo.rs b/crates/repo-actor/src/handlers/validate_repo.rs new file mode 100644 index 0000000..577770c --- /dev/null +++ b/crates/repo-actor/src/handlers/validate_repo.rs @@ -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 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 { + #[cfg(test)] + self.log("start: ValidateRepo"); + tracing::debug!("Handler: ValidateRepo: start"); + + // Message Token - make sure we are only triggered for the latest/current token + match self.token_status(msg.unwrap()) { + TokenStatus::Current => {} // do nothing + TokenStatus::NewTokenIsExpired => { + tracing::info!("Dropping message from previous generation"); + return; // message is expired + } + TokenStatus::New(message_token) => { + tracing::info!(%message_token, "New message token"); + self.message_token = message_token; + } + } + + // Repository positions + #[cfg(test)] + let mut messages: Vec = vec![]; + tracing::debug!(open_repo = ?self.open_repository, "Can I run?"); + #[allow(clippy::cognitive_complexity)] + self.open_repository.iter().for_each(|open_repository| { + tracing::debug!("we have an open repo"); + if let Some(repo_config) = self.repo_details.repo_config.clone() { + tracing::debug!("we have repo config"); + let repo_details = self.repo_details.clone(); + let addr = ctx.address(); + let message_token = self.message_token; + let sleep_duration = self.sleep_duration; + tracing::debug!("Duplicating open repo"); + let open_repository = open_repository.duplicate(); + tracing::debug!("Validating branch positions"); + match git::validation::positions::validate_positions( + &*open_repository, + &repo_details, + repo_config, + ) { + Ok(git::validation::positions::Positions { + main, + next, + dev, + dev_commit_history, + }) => { + tracing::debug!("Positions valid - sending StartMonitoring#"); + if next != main { + #[cfg(test)] + messages.push("next-ahead-of-main: check-status".to_string()); + addr.do_send(actor::messages::CheckCIStatus::new(next)); + } else if next != dev { + #[cfg(test)] + messages.push("dev-ahead-of-next: advance-next".to_string()); + addr.do_send(actor::messages::AdvanceNext::new(( + next, + dev_commit_history, + ))); + } else { + // do nothing + } + } + Err(err) => { + #[cfg(test)] + messages.push(format!("invalid positions: {err:?}, sleep then retry")); + tracing::warn!("Error: {err:?}"); + tracing::debug!("sleeping before retrying..."); + async move { + tokio::time::sleep(sleep_duration).await; + tracing::debug!("retrying..."); + let _ = addr + .send(actor::messages::ValidateRepo::new(message_token)) + .await; + } + .in_current_span() + .into_actor(self) + .wait(ctx); + } + } + } + }); + #[cfg(test)] + messages.into_iter().for_each(|message| self.log(message)); + + tracing::debug!("Handler: ValidateRepo: finish"); + } +} + +enum TokenStatus { + Current, + NewTokenIsExpired, + 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::NewTokenIsExpired; + } + TokenStatus::Current + } +} diff --git a/crates/repo-actor/src/webhook.rs b/crates/repo-actor/src/handlers/webhook_message.rs similarity index 95% rename from crates/repo-actor/src/webhook.rs rename to crates/repo-actor/src/handlers/webhook_message.rs index 21c808a..79bc3fa 100644 --- a/crates/repo-actor/src/webhook.rs +++ b/crates/repo-actor/src/handlers/webhook_message.rs @@ -1,13 +1,13 @@ // use actix::prelude::*; -use crate::{RepoActor, ValidateRepo}; +use crate as actor; use git_next_config as config; use git_next_git as git; use tracing::{info, warn}; -impl Handler for RepoActor { +impl Handler for actor::RepoActor { type Result = (); #[allow(clippy::cognitive_complexity)] // TODO: (#49) reduce complexity @@ -88,6 +88,7 @@ impl Handler for RepoActor { token = %message_token, "New commit" ); - ctx.address().do_send(ValidateRepo { message_token }); + ctx.address() + .do_send(actor::messages::ValidateRepo::new(message_token)); } } diff --git a/crates/repo-actor/src/handlers/webhook_registered.rs b/crates/repo-actor/src/handlers/webhook_registered.rs new file mode 100644 index 0000000..f11ff2b --- /dev/null +++ b/crates/repo-actor/src/handlers/webhook_registered.rs @@ -0,0 +1,17 @@ +// +use actix::prelude::*; + +use crate as actor; + +impl Handler 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()); + } +} diff --git a/crates/repo-actor/src/lib.rs b/crates/repo-actor/src/lib.rs index be59827..491235f 100644 --- a/crates/repo-actor/src/lib.rs +++ b/crates/repo-actor/src/lib.rs @@ -1,30 +1,60 @@ mod branch; +pub mod handlers; mod load; -pub mod status; -pub mod webhook; +pub mod messages; #[cfg(test)] mod tests; -use std::time::Duration; - 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_forge as forge; use git_next_git as git; use kxio::network::Network; -use tracing::{debug, info, warn, Instrument}; +use tracing::{info, warn, Instrument}; +#[cfg(test)] +pub type RepoActorLog = std::sync::Arc>>; + +/// 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)] #[display("{}:{}:{}", generation, repo_details.forge.forge_alias(), repo_details.repo_alias)] pub struct RepoActor { + sleep_duration: std::time::Duration, generation: git::Generation, - message_token: MessageToken, + message_token: messages::MessageToken, repo_details: git::RepoDetails, webhook: config::server::Webhook, webhook_id: Option, // INFO: if [None] then no webhook is configured @@ -32,35 +62,64 @@ pub struct RepoActor { last_main_commit: Option, last_next_commit: Option, last_dev_commit: Option, - repository: Box, + repository_factory: Box, open_repository: Option>, net: Network, - forge: forge::Forge, + forge: Box, + #[cfg(test)] + log: Option, } impl RepoActor { pub fn new( - details: git::RepoDetails, + repo_details: git::RepoDetails, + forge: Box, webhook: config::server::Webhook, generation: git::Generation, net: Network, - repository: Box, + repository_factory: Box, + sleep_duration: std::time::Duration, ) -> Self { - let forge = forge::Forge::new(details.clone(), net.clone()); - debug!(?forge, "new"); + let message_token = messages::MessageToken::default(); Self { generation, - message_token: MessageToken::new(), - repo_details: details, + message_token, + repo_details, webhook, webhook_id: None, webhook_auth: None, last_main_commit: None, last_next_commit: None, last_dev_commit: None, - repository, + repository_factory, open_repository: None, - net, forge, + net, + sleep_duration, + #[cfg(test)] + 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, + ) -> Self { + self.open_repository.replace(open_repository); + self + } + + fn log(&mut self, message: impl Into) { + let message: String = message.into(); + for log in self.log.iter() { + let _ = log.lock().map(|mut l| l.push(message.clone())); } } } @@ -68,11 +127,13 @@ impl Actor for RepoActor { type Context = Context; #[tracing::instrument(name = "RepoActor::stopping", skip_all, fields(repo = %self.repo_details))] fn stopping(&mut self, ctx: &mut Self::Context) -> Running { + tracing::debug!("stopping"); info!("Checking webhook"); match self.webhook_id.take() { Some(webhook_id) => { + tracing::warn!("stopping - unregistering webhook"); info!(%webhook_id, "Unregistring webhook"); - let forge = self.forge.clone(); + let forge = self.forge.duplicate(); async move { if let Err(err) = forge.unregister_webhook(&webhook_id).await { warn!("unregistering webhook: {err}"); @@ -87,260 +148,3 @@ impl Actor for RepoActor { } } } - -#[derive(Message)] -#[rtype(result = "()")] -pub struct CloneRepo; -impl Handler for RepoActor { - type Result = (); - #[tracing::instrument(name = "RepoActor::CloneRepo", skip_all, fields(repo = %self.repo_details /*, gitdir = %self.repo_details.gitdir */))] - fn handle(&mut self, _msg: CloneRepo, ctx: &mut Self::Context) -> Self::Result { - let gitdir = self.repo_details.gitdir.clone(); - match git::repository::open(&*self.repository, &self.repo_details, gitdir) { - Ok(repository) => { - self.open_repository.replace(repository); - if self.repo_details.repo_config.is_none() { - ctx.address().do_send(LoadConfigFromRepo); - } else { - ctx.address().do_send(ValidateRepo { - message_token: self.message_token, - }); - } - } - Err(err) => warn!("Could not open repo: {err}"), - } - } -} - -#[derive(Message)] -#[rtype(result = "()")] -pub struct LoadConfigFromRepo; -impl Handler 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 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 for RepoActor { - type Result = (); - #[tracing::instrument(name = "RepoActor::ValidateRepo", skip_all, fields(repo = %self.repo_details, token = %msg.message_token))] - fn handle(&mut self, msg: ValidateRepo, ctx: &mut Self::Context) -> Self::Result { - match msg.message_token { - message_token if self.message_token < message_token => { - info!(%message_token, "New message token"); - self.message_token = msg.message_token; - } - message_token if self.message_token > message_token => { - info!("Dropping message from previous generation"); - return; // message is expired - } - _ => { - // do nothing - } - } - if self.webhook_id.is_none() { - let forge_alias = self.repo_details.forge.forge_alias(); - let repo_alias = &self.repo_details.repo_alias; - let webhook_url = self.webhook.url(forge_alias, repo_alias); - let forge = self.forge.clone(); - let addr = ctx.address(); - async move { - if let Err(err) = - forge - .register_webhook(&webhook_url) - .await - .and_then(|registered_webhook| { - addr.try_send(WebhookRegistered::from(registered_webhook)) - .map_err(|e| { - git::forge::webhook::Error::FailedToNotifySelf(e.to_string()) - }) - }) - { - warn!("registering webhook: {err}"); - } - } - .in_current_span() - .into_actor(self) - .wait(ctx); - } - if let (Some(open_repository), Some(repo_config)) = - (&self.open_repository, self.repo_details.repo_config.clone()) - { - 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 { - 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)] -#[rtype(result = "()")] -pub struct StartMonitoring { - main: git::Commit, - next: git::Commit, - dev: git::Commit, - dev_commit_history: Vec, -} -impl Handler 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 for WebhookRegistered { - fn from(value: RegisteredWebhook) -> Self { - Self(value.id().clone(), value.auth().clone()) - } -} -impl Handler 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 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) - } -} diff --git a/crates/repo-actor/src/load.rs b/crates/repo-actor/src/load.rs index ff64e32..989bd00 100644 --- a/crates/repo-actor/src/load.rs +++ b/crates/repo-actor/src/load.rs @@ -1,75 +1,54 @@ -use std::path::PathBuf; - // -use actix::prelude::*; - -use tracing::{error, info}; +use derive_more::Display; +use std::path::PathBuf; +use tracing::info; use git_next_config as config; use git_next_git as git; -use super::{LoadedConfig, RepoActor}; - /// Loads the [RepoConfig] from the `.git-next.toml` file in the repository #[tracing::instrument(skip_all, fields(branch = %repo_details.branch))] -pub async fn load_file( +pub async fn config_from_repository( repo_details: git::RepoDetails, - addr: Addr, open_repository: &dyn git::repository::OpenRepositoryLike, -) { +) -> Result { info!("Loading .git-next.toml from repo"); - let repo_config = match load(&repo_details, open_repository).await { - Ok(repo_config) => repo_config, - 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 { - let contents = open_repository.read_file(&details.branch, &PathBuf::from(".git-next.toml"))?; + let contents = + open_repository.read_file(&repo_details.branch, &PathBuf::from(".git-next.toml"))?; 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) } -#[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 = core::result::Result; +#[derive(Debug, thiserror::Error, Display)] pub enum Error { - File(git::file::Error), - Config(config::server::Error), - Toml(toml::de::Error), - Branch(git::push::Error), + #[display("file")] + File(#[from] git::file::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), } - -pub async fn validate( - config: config::RepoConfig, - open_repository: &dyn git::repository::OpenRepositoryLike, -) -> Result { - 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) -} diff --git a/crates/repo-actor/src/messages.rs b/crates/repo-actor/src/messages.rs new file mode 100644 index 0000000..fe68af0 --- /dev/null +++ b/crates/repo-actor/src/messages.rs @@ -0,0 +1,92 @@ +// +use actix::prelude::*; +use config::newtype; +use derive_more::{Constructor, 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 Message for $name { + type Result = (); + } + }; + ($name:ident) => { + git_next_config::newtype!($name); + impl Message for $name { + type Result = (); + } + }; + ($name:ident wraps $value:ty => $result:ty) => { + git_next_config::newtype!($name is a $value); + impl Message for $name { + type Result = $result; + } + }; + ($name:ident => $result:ty) => { + git_next_config::newtype!($name); + impl Message for $name { + type Result = $result; + } + }; +} + +message!(LoadConfigFromRepo); +message!(CloneRepo); +message!(LoadedConfig wraps config::RepoConfig); +message!(ValidateRepo wraps MessageToken); + +#[derive(Clone, Debug, Constructor, Message)] +#[rtype(result = "()")] +pub struct StartMonitoring { + main: git::Commit, + next: git::Commit, + dev: git::Commit, + dev_commit_history: Vec, +} +impl StartMonitoring { + pub const fn main(&self) -> &git::Commit { + &self.main + } + pub const fn next(&self) -> &git::Commit { + &self.next + } + pub const fn dev(&self) -> &git::Commit { + &self.dev + } + pub fn dev_commit_history(&self) -> &[git::Commit] { + &self.dev_commit_history + } +} + +message!(WebhookRegistered wraps (config::WebhookId, config::WebhookAuth)); +impl WebhookRegistered { + pub const fn webhook_id(&self) -> &config::WebhookId { + &self.0 .0 + } + pub const fn webhook_auth(&self) -> &config::WebhookAuth { + &self.0 .1 + } +} +impl From 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!(AdvanceNext wraps (git::Commit, Vec)); // next commit and the dev commit history +message!(AdvanceMain wraps git::Commit); // next commit diff --git a/crates/repo-actor/src/status.rs b/crates/repo-actor/src/status.rs deleted file mode 100644 index b7b4ea4..0000000 --- a/crates/repo-actor/src/status.rs +++ /dev/null @@ -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, - 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"); - } - } -} diff --git a/crates/repo-actor/src/tests.rs b/crates/repo-actor/src/tests.rs index b9c7df4..fd78976 100644 --- a/crates/repo-actor/src/tests.rs +++ b/crates/repo-actor/src/tests.rs @@ -1,34 +1,1528 @@ // -use super::*; -mod branch { - use super::super::branch::*; +#![allow(unused_imports)] // TODO remove this + +use crate as actor; +use actix::prelude::*; +use actor::{ + messages::{CloneRepo, MessageToken, WebhookRegistered}, + RepoActor, RepoActorLog, +}; +use assert2::let_assert; +use config::{BranchName, RegisteredWebhook, RepoBranches, RepoConfig}; +use git::{ + repository::{ + open::MockOpenRepositoryLike, Direction, MockRepositoryFactory, RepositoryFactory, + }, + validation::remotes, + GitRemote, RepoDetails, +}; +use git_next_config as config; +use git_next_forge as forge; +use git_next_git as git; +use mockall::predicate::eq; +use std::{ + borrow::{Borrow, BorrowMut}, + cell::{Cell, RefCell}, + collections::HashMap, + path::PathBuf, + rc::Rc, + sync::{atomic::AtomicBool, Arc, Mutex}, +}; + +type TestResult = Result<(), Box>; + +mod repo_actor { use super::*; + use actix::prelude::*; + + mod clone_repo { + + 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()) + // log that it sent a messages to validate the repo + .map(|l| { + assert_eq!( + l.clone(), + vec!["open okay", "send: ValidateRepo", "start: ValidateRepo"] + ) + })?; + + Ok(()) + } + } + + mod validate_repo { + use crate::messages::{MessageToken, ValidateRepo}; + + use super::*; + + // TODO: (#95) test: repo with next ahead of main and failing CI should notify user + // TODO: (#95) test: repo with dev not a child of main should notify user + + #[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); + let mut validating_open_repository = MockOpenRepositoryLike::new(); + #[allow(clippy::unwrap_used)] + let repo_config = repo_details.repo_config.clone().unwrap(); + expect::fetch_ok(&mut validating_open_repository); + let branches = repo_config.branches(); + // commit_log main + let main_commit = + expect::main_commit_log(&mut validating_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 + validating_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 + validating_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 validating_open_repository); + expect::push_ok(&mut validating_open_repository); + expect::duplicate(&mut open_repository, validating_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(); + let mut validating_open_repository = MockOpenRepositoryLike::new(); + expect::fetch_ok(&mut validating_open_repository); + let branches = repo_config.branches(); + // commit_log main + let main_commit = + expect::main_commit_log(&mut validating_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 + validating_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 + validating_open_repository + .expect_commit_log() + .times(1) + .with(eq(branches.dev()), eq([main_commit])) + .return_once(|_, _| Ok(dev_branch_log)); + expect::fetch_ok(&mut validating_open_repository); + expect::push_ok(&mut validating_open_repository); + expect::duplicate(&mut open_repository, validating_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); + let mut validation_repo = MockOpenRepositoryLike::new(); + expect::fetch_ok(&mut validation_repo); + let branches = repo_config.branches(); + // commit_log main + let main_commit = expect::main_commit_log(&mut validation_repo, 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 + validation_repo + .expect_commit_log() + .times(1) + .with(eq(branches.next()), eq([main_commit.clone()])) + .return_once(move |_, _| Ok(next_branch_log)); + // commit_log dev + validation_repo + .expect_commit_log() + .times(1) + .with(eq(branches.dev()), eq([main_commit])) + .return_once(|_, _| Ok(dev_branch_log)); + expect::fetch_ok(&mut validation_repo); + expect::push_ok(&mut validation_repo); + expect::duplicate(&mut open_repository, validation_repo); + + //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 + let mut validation_repo = MockOpenRepositoryLike::new(); + expect::fetch_ok(&mut validation_repo); + let branches = repo_config.branches(); + // commit_log main + let main_commit = expect::main_commit_log(&mut validation_repo, branches.main()); + // next - ahead of main + let next_branch_log = vec![given::a_commit(), main_commit.clone()]; + // dev - on next + let dev_branch_log = next_branch_log.clone(); + // commit_log next + validation_repo + .expect_commit_log() + .times(1) + .with(eq(branches.next()), eq([main_commit.clone()])) + .return_once(move |_, _| Ok(next_branch_log)); + // commit_log dev + validation_repo + .expect_commit_log() + .times(1) + .with(eq(branches.dev()), eq([main_commit])) + .return_once(|_, _| Ok(dev_branch_log)); + expect::duplicate(&mut open_repository, validation_repo); + + //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("next-ahead-of-main: check-status"))) + })?; + Ok(()) + } + // TODO: test: repo with next ahead of main and passing CI should advance main to next + // TODO: test: repo with next on main and dev ahead of next should advance next towards dev + // TODO: test: repo with next and dev on main should recheck later + } +} +mod branch { + + use super::*; + + mod advance_next { + 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(&git::commit::Message::new( + "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(&git::commit::Message::new( + "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(&git::commit::Message::new( + "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(()) + } + } + } + } + } + mod advance_main { + 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()); + } + } #[actix_rt::test] async fn test_find_next_commit_on_dev() { - let next = git::Commit::new( - git::commit::Sha::new("current-next".to_string()), - git::commit::Message::new("foo".to_string()), - ); - let expected = git::Commit::new( - git::commit::Sha::new("dev-next".to_string()), - git::commit::Message::new("next-should-go-here".to_string()), - ); + let next = given::a_commit(); + let expected = given::a_commit(); let dev_commit_history = vec![ - git::Commit::new( - git::commit::Sha::new("dev".to_string()), - git::commit::Message::new("future".to_string()), - ), + given::a_commit(), // dev HEAD expected.clone(), - next.clone(), - git::Commit::new( - git::commit::Sha::new("current-main".to_string()), - git::commit::Message::new("history".to_string()), - ), + next.clone(), // next - advancing towards dev HEAD + given::a_commit(), // parent of next ]; - let next_commit = find_next_commit_on_dev(next, dev_commit_history); + let next_commit = actor::branch::find_next_commit_on_dev(&next, &dev_commit_history); assert_eq!(next_commit, Some(expected), "Found the wrong commit"); } } +mod load { + use std::path::PathBuf; + + use git_next_git::common::repo_details; + + use super::*; + + #[tokio::test] + async fn when_file_not_found_should_error() -> TestResult { + //given + let fs = given::a_filesystem(); + let (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(()) + } +} +pub mod given { + #![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>, + ) { + 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>>, + ) { + 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 = main_log.clone(); + next_log.extend(vec![given::a_commit()]); + let mut dev_log: Vec = 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::message::Body), + Missing, + Invalid, + } + + pub fn a_webhook_message_body() -> config::webhook::message::Body { + config::webhook::message::Body::new(a_name()) + } + + pub fn repo_branches() -> RepoBranches { + RepoBranches::new( + format!("main-{}", a_name()), + format!("next-{}", a_name()), + format!("dev-{}", a_name()), + ) + } + + pub fn a_forge_alias() -> ForgeAlias { + ForgeAlias::new(a_name()) + } + + pub fn a_repo_alias() -> RepoAlias { + RepoAlias::new(a_name()) + } + + pub fn a_network() -> kxio::network::MockNetwork { + kxio::network::MockNetwork::new() + } + + pub fn a_webhook_url( + forge_alias: &ForgeAlias, + repo_alias: &RepoAlias, + ) -> git_next_config::server::WebhookUrl { + config::server::Webhook::new(a_name()).url(forge_alias, repo_alias) + } + + pub fn any_webhook_url() -> git_next_config::server::WebhookUrl { + a_webhook_url(&a_forge_alias(), &a_repo_alias()) + } + + pub fn a_pathbuf() -> PathBuf { + PathBuf::from(given::a_name()) + } + + pub fn a_name() -> String { + use rand::Rng; + use std::iter; + + fn generate(len: usize) -> String { + const CHARSET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; + let mut rng = rand::thread_rng(); + let one_char = || CHARSET[rng.gen_range(0..CHARSET.len())] as char; + iter::repeat_with(one_char).take(len).collect() + } + generate(5) + } + + pub fn a_webhook_id() -> WebhookId { + WebhookId::new(a_name()) + } + + pub fn a_github_webhook_id() -> i64 { + rand::thread_rng().next_u32().into() + } + + pub fn a_branch_name(prefix: impl Into) -> 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_commit() -> git::Commit { + git::Commit::new(a_commit_sha(), a_commit_message()) + } + + pub fn a_commit_with_message(message: &git::commit::Message) -> git::Commit { + git::Commit::new(a_commit_sha(), message.to_owned()) + } + + pub fn a_commit_with_sha(sha: &git::commit::Sha) -> git::Commit { + git::Commit::new(sha.to_owned(), a_commit_message()) + } + + pub fn a_commit_with(sha: &git::commit::Sha, message: &git::commit::Message) -> git::Commit { + git::Commit::new(sha.to_owned(), message.to_owned()) + } + + pub fn a_commit_message() -> git::commit::Message { + git::commit::Message::new(a_name()) + } + + pub fn a_commit_sha() -> git::commit::Sha { + git::commit::Sha::new(a_name()) + } + + pub fn a_webhook_push( + sha: &git::commit::Sha, + message: &git::commit::Message, + ) -> config::webhook::Push { + let branch = a_branch_name("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 { + Box::new(MockForgeLike::new()) + } + + pub fn a_repo_actor( + repo_details: git::RepoDetails, + repository_factory: Box, + forge: Box, + 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 mod then { + #![allow(dead_code)] // TODO: remove this + #![allow(unused_imports)] // TODO: remove this + + use std::path::{Path, PathBuf}; + + type TestResult = Result<(), Box>; + + 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) -> 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> { + 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())) + } +} +mod expect { + 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 + } +} +mod when { + + use git::repository::OpenRepositoryLike; + + use super::*; + + pub fn start_actor( + repository_factory: git::repository::MockRepositoryFactory, + repo_details: git::RepoDetails, + forge: Box, + ) -> (actix::Addr, 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, + ) -> (actix::Addr, 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) + } +} diff --git a/crates/server/src/actors/server.rs b/crates/server/src/actors/server.rs index 6929c66..c41a89d 100644 --- a/crates/server/src/actors/server.rs +++ b/crates/server/src/actors/server.rs @@ -8,7 +8,8 @@ use git_next_config::{ self as config, ForgeAlias, ForgeConfig, GitDir, RepoAlias, ServerRepoConfig, }; 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 tracing::{error, info, warn}; @@ -39,6 +40,7 @@ pub struct Server { fs: FileSystem, net: Network, repository_factory: Box, + sleep_duration: std::time::Duration, } impl Actor for Server { type Context = Context; @@ -114,7 +116,12 @@ impl Handler for Server { } } impl Server { - pub fn new(fs: FileSystem, net: Network, repo: Box) -> Self { + pub fn new( + fs: FileSystem, + net: Network, + repo: Box, + sleep_duration: std::time::Duration, + ) -> Self { let generation = Generation::default(); Self { generation, @@ -122,6 +129,7 @@ impl Server { fs, net, repository_factory: repo, + sleep_duration, } } fn create_forge_data_directories( @@ -182,6 +190,7 @@ impl Server { let net = self.net.clone(); let repository_factory = self.repository_factory.duplicate(); let generation = self.generation; + let sleep_duration = self.sleep_duration; move |(repo_alias, server_repo_config)| { let span = tracing::info_span!("create_actor", alias = %repo_alias, config = %server_repo_config); let _guard = span.enter(); @@ -207,13 +216,16 @@ impl Server { &forge_config, gitdir, ); + let forge = git_next_forge::Forge::create(repo_details.clone(), net.clone()); info!("Starting Repo Actor"); let actor = RepoActor::new( repo_details, + forge, webhook.clone(), generation, net.clone(), repository_factory.duplicate(), + sleep_duration, ); (forge_name.clone(), repo_alias, actor) } diff --git a/crates/server/src/config/tests.rs b/crates/server/src/config/tests.rs index 98f60d9..86ea69d 100644 --- a/crates/server/src/config/tests.rs +++ b/crates/server/src/config/tests.rs @@ -1,6 +1,6 @@ // 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::{ self as config, ForgeType, GitDir, Hostname, RepoBranches, RepoConfig, RepoConfigSource, RepoPath, @@ -46,7 +46,7 @@ fn gitdir_should_display_as_pathbuf() { // git.kemitix.net:kemitix/git-next // If the default push remote is something else, then this test will fail 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 mut repo_details = git::common::repo_details( 1, @@ -77,7 +77,7 @@ fn repo_details_find_default_push_remote_finds_correct_remote() -> Result<()> { #[test] 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 mut repo_details = git::common::repo_details( 1, @@ -92,7 +92,7 @@ fn gitdir_validate_should_pass_a_valid_git_repo() -> Result<()> { .with_hostname(Hostname::new("git.kemitix.net")); let gitdir = &repo_details.gitdir; let repository = git::repository::real().open(gitdir)?; - validate_repo(&*repository, &repo_details)?; + validate_default_remotes(&*repository, &repo_details)?; Ok(()) } @@ -100,7 +100,7 @@ fn gitdir_validate_should_pass_a_valid_git_repo() -> Result<()> { #[test] fn gitdir_validate_should_fail_a_git_repo_with_wrong_remote() -> Result<()> { 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 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())); let gitdir = &repo_details.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(()) } diff --git a/crates/server/src/lib.rs b/crates/server/src/lib.rs index f0930b6..e4e6ea6 100644 --- a/crates/server/src/lib.rs +++ b/crates/server/src/lib.rs @@ -37,11 +37,16 @@ pub fn init(fs: FileSystem) { } } -pub async fn start(fs: FileSystem, net: Network, repo: Box) { +pub async fn start( + fs: FileSystem, + net: Network, + repo: Box, + sleep_duration: std::time::Duration, +) { init_logging(); 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); info!("Starting File Watcher...");