Compare commits

...

2 commits

Author SHA1 Message Date
0124b8d8c0 WIP: add github crate
All checks were successful
ci/woodpecker/push/cron-docker-builder Pipeline was successful
ci/woodpecker/push/push-next Pipeline was successful
ci/woodpecker/push/tag-created Pipeline was successful
2024-05-26 08:07:12 +01:00
8a35911d00 refactor: get commit from from local repo (part 2/3)
All checks were successful
Rust / build (push) Successful in 1m10s
ci/woodpecker/push/cron-docker-builder Pipeline was successful
ci/woodpecker/push/push-next Pipeline was successful
ci/woodpecker/push/tag-created Pipeline was successful
Remove the legacy implementation
2024-05-26 08:07:12 +01:00
16 changed files with 172 additions and 217 deletions

View file

@ -7,6 +7,7 @@ members = [
"crates/git", "crates/git",
"crates/forge", "crates/forge",
"crates/forge-forgejo", "crates/forge-forgejo",
"crates/forge-github",
"crates/repo-actor", "crates/repo-actor",
] ]
@ -26,6 +27,7 @@ git-next-config = { path = "crates/config" }
git-next-git = { path = "crates/git" } git-next-git = { path = "crates/git" }
git-next-forge = { path = "crates/forge" } git-next-forge = { path = "crates/forge" }
git-next-forge-forgejo = { path = "crates/forge-forgejo" } git-next-forge-forgejo = { path = "crates/forge-forgejo" }
git-next-forge-github = { path = "crates/forge-github" }
git-next-repo-actor = { path = "crates/repo-actor" } git-next-repo-actor = { path = "crates/repo-actor" }
# CLI parsing # CLI parsing

View file

@ -4,7 +4,7 @@ version = { workspace = true }
edition = { workspace = true } edition = { workspace = true }
[features] [features]
default = ["forgejo"] default = ["forgejo", "github"]
forgejo = [] forgejo = []
github = [] github = []

View file

@ -4,24 +4,22 @@ use git::ForgeLike as _;
use git_next_config as config; use git_next_config as config;
use git_next_git as git; use git_next_git as git;
use kxio::network;
use tracing::{debug, error, info, warn}; use tracing::{debug, error, info, warn};
pub async fn validate_positions( #[allow(clippy::cognitive_complexity)] // TODO: (#83) reduce complexity
pub fn validate_positions(
forge: &forgejo::ForgeJo, forge: &forgejo::ForgeJo,
repository: &git::OpenRepository, repository: &git::OpenRepository,
repo_config: config::RepoConfig, repo_config: config::RepoConfig,
) -> git::validation::Result { ) -> git::validation::Result {
let repo_details = &forge.repo_details;
// Collect Commit Histories for `main`, `next` and `dev` branches // Collect Commit Histories for `main`, `next` and `dev` branches
repository.fetch()?; repository.fetch()?;
let commit_histories = let commit_histories = get_commit_histories(repository, &repo_config);
get_commit_histories(repository, repo_details, &repo_config, &forge.net).await;
let commit_histories = match commit_histories { let commit_histories = match commit_histories {
Ok(commit_histories) => commit_histories, Ok(commit_histories) => commit_histories,
Err(err) => { Err(err) => {
error!(?err, "Failed to get commit histories"); error!(?err, "Failed to get commit histories");
return Err(git::validation::Error::Network(Box::new(err))); return Err(git::validation::Error::CommitLog(err));
} }
}; };
// Validations // Validations
@ -145,37 +143,14 @@ pub async fn validate_positions(
}) })
} }
async fn get_commit_histories( fn get_commit_histories(
repository: &git::repository::OpenRepository, repository: &git::repository::OpenRepository,
repo_details: &git::RepoDetails,
repo_config: &config::RepoConfig, repo_config: &config::RepoConfig,
net: &network::Network, ) -> Result<git::commit::Histories, git::commit::log::Error> {
) -> Result<git::commit::Histories, network::NetworkError> { let main = (repository.commit_log(&repo_config.branches().main(), &[]))?;
let main = (get_commit_history( let main_head = [main[0].clone()];
repository, let next = repository.commit_log(&repo_config.branches().next(), &main_head)?;
repo_details, let dev = repository.commit_log(&repo_config.branches().dev(), &main_head)?;
&repo_config.branches().main(),
&[],
net,
)
.await)?;
let main_head = main[0].clone();
let next = (get_commit_history(
repository,
repo_details,
&repo_config.branches().next(),
&[main_head.clone()],
net,
)
.await)?;
let dev = (get_commit_history(
repository,
repo_details,
&repo_config.branches().dev(),
&[main_head],
net,
)
.await)?;
debug!( debug!(
main = main.len(), main = main.len(),
next = next.len(), next = next.len(),
@ -185,120 +160,3 @@ async fn get_commit_histories(
let histories = git::commit::Histories { main, next, dev }; let histories = git::commit::Histories { main, next, dev };
Ok(histories) Ok(histories)
} }
#[tracing::instrument(skip_all, fields(%branch_name, ?find_commits))]
async fn get_commit_history(
repository: &git::repository::OpenRepository,
repo_details: &git::RepoDetails,
branch_name: &config::BranchName,
find_commits: &[git::Commit],
net: &kxio::network::Network,
) -> Result<Vec<git::Commit>, network::NetworkError> {
let original = original_get_commit_history(repo_details, branch_name, find_commits, net).await;
let updated = repository.commit_log(branch_name, find_commits);
match (original, updated) {
(Ok(original), Ok(updated)) => {
if updated == original {
info!("new version matches");
Ok(updated)
} else {
error!("new version doesn't match original");
Ok(original)
}
}
(Ok(original), Err(err_updated)) => {
warn!(?err_updated, "original ok, updated error");
Ok(original)
}
(Err(err_original), Ok(updated)) => {
warn!(?err_original, "original err, updated ok");
Ok(updated)
}
(Err(err_orignal), Err(err_updated)) => {
error!(?err_orignal, ?err_updated, "original err, updated err");
Err(err_orignal)
}
}
}
#[tracing::instrument(fields(%branch_name),skip_all)]
async fn original_get_commit_history(
repo_details: &git::RepoDetails,
branch_name: &config::BranchName,
find_commits: &[git::Commit],
net: &kxio::network::Network,
) -> Result<Vec<git::Commit>, network::NetworkError> {
let hostname = &repo_details.forge.hostname();
let repo_path = &repo_details.repo_path;
let mut page = 1;
let limit = match find_commits.is_empty() {
true => 1,
false => 50,
};
let options = "stat=false&verification=false&files=false";
let mut all_commits = Vec::new();
loop {
let api_token = &repo_details.forge.token();
use secrecy::ExposeSecret;
let token = api_token.expose_secret();
let url = network::NetUrl::new(format!(
"https://{hostname}/api/v1/repos/{repo_path}/commits?sha={branch_name}&{options}&token={token}&page={page}&limit={limit}"
));
let request = network::NetRequest::new(
network::RequestMethod::Get,
url,
network::NetRequestHeaders::new(),
network::RequestBody::None,
network::ResponseType::Json,
None,
network::NetRequestLogging::None,
);
let response = net.get::<Vec<Commit>>(request).await?;
let commits = response
.response_body()
.unwrap_or_default()
.into_iter()
.map(git::Commit::from)
.collect::<Vec<_>>();
let found = find_commits.is_empty()
|| find_commits
.iter()
.any(|find_commit| commits.iter().any(|commit| commit == find_commit));
let at_end = commits.len() < limit; // i.e. less than the number of commits requested
for commit in commits {
all_commits.push(commit.clone());
if find_commits.contains(&commit) {
break;
}
}
if found || at_end {
break;
}
page += 1;
}
Ok(all_commits)
}
#[allow(dead_code)]
#[derive(Debug, Default, serde::Deserialize)]
struct Commit {
sha: String,
commit: RepoCommit,
}
#[allow(dead_code)]
#[derive(Debug, Default, serde::Deserialize)]
struct RepoCommit {
message: String,
}
impl From<Commit> for git::Commit {
fn from(value: Commit) -> Self {
Self::new(
git::commit::Sha::new(value.sha),
git::commit::Message::new(value.commit.message),
)
}
}

View file

@ -48,7 +48,7 @@ impl git::ForgeLike for ForgeJo {
repository: git::OpenRepository, repository: git::OpenRepository,
repo_config: config::RepoConfig, repo_config: config::RepoConfig,
) -> git::validation::Result { ) -> git::validation::Result {
branch::validate_positions(self, &repository, repo_config).await branch::validate_positions(self, &repository, repo_config)
} }
fn branch_reset( fn branch_reset(

View file

@ -0,0 +1,59 @@
[package]
name = "git-next-forge-github"
version = { workspace = true }
edition = { workspace = true }
[dependencies]
git-next-config = { workspace = true }
git-next-git = { workspace = true }
# logging
console-subscriber = { workspace = true }
tracing = { workspace = true }
tracing-subscriber = { workspace = true }
# base64 decoding
base64 = { workspace = true }
# git
async-trait = { workspace = true }
# fs/network
kxio = { workspace = true }
# TOML parsing
serde = { workspace = true }
serde_json = { workspace = true }
toml = { workspace = true }
# Secrets and Password
secrecy = { workspace = true }
# Conventional Commit check
git-conventional = { workspace = true }
# Webhooks
bytes = { workspace = true }
ulid = { workspace = true }
warp = { workspace = true }
# boilerplate
derive_more = { workspace = true }
# file watcher
inotify = { workspace = true }
# # Actors
# actix = { workspace = true }
# actix-rt = { workspace = true }
tokio = { workspace = true }
[dev-dependencies]
# Testing
assert2 = { workspace = true }
[lints.clippy]
nursery = { level = "warn", priority = -1 }
# pedantic = "warn"
unwrap_used = "warn"
expect_used = "warn"

View file

@ -0,0 +1,68 @@
//
#![allow(dead_code)]
use derive_more::Constructor;
use git_next_config as config;
use git_next_git as git;
use kxio::network::Network;
#[cfg(test)]
mod tests;
#[derive(Clone, Debug, Constructor)]
pub struct Github {
net: Network,
}
#[async_trait::async_trait]
impl git_next_git::ForgeLike for Github {
fn name(&self) -> String {
"github".to_string()
}
async fn branches_get_all(&self) -> Result<Vec<config::BranchName>, git::branch::Error> {
todo!();
}
/// Returns the contents of the file.
async fn file_contents_get(
&self,
_branch_name: &config::BranchName,
_file_path: &str,
) -> Result<String, git::file::Error> {
todo!();
}
/// Assesses the relative positions of the main, next and dev branch and updates their
/// positions as needed.
async fn branches_validate_positions(
&self,
_repository: git::OpenRepository,
_repo_config: config::RepoConfig,
) -> git::validation::Result {
todo!();
}
/// Moves a branch to a new commit.
fn branch_reset(
&self,
_repository: &git::OpenRepository,
_branch_name: config::BranchName,
_to_commit: git::GitRef,
_force: git::push::Force,
) -> git::push::Result {
todo!();
}
/// Checks the results of any (e.g. CI) status checks for the commit.
async fn commit_status(&self, _commit: &git::Commit) -> git::commit::Status {
todo!();
}
/// Clones a repo to disk.
fn repo_clone(
&self,
_gitdir: config::GitDir,
) -> Result<git::OpenRepository, git::repository::Error> {
todo!();
}
}

View file

@ -0,0 +1,8 @@
use git_next_git::ForgeLike as _;
#[test]
fn test_name() {
let net = kxio::network::Network::new_mock();
let forge = crate::Github::new(net);
assert_eq!(forge.name(), "github");
}

View file

@ -4,14 +4,15 @@ version = { workspace = true }
edition = { workspace = true } edition = { workspace = true }
[features] [features]
default = ["forgejo"] default = ["forgejo", "github"]
forgejo = ["git-next-forge-forgejo"] forgejo = ["git-next-forge-forgejo"]
github = [] github = ["git-next-forge-github"]
[dependencies] [dependencies]
git-next-config = { workspace = true } git-next-config = { workspace = true }
git-next-git = { workspace = true } git-next-git = { workspace = true }
git-next-forge-forgejo = { workspace = true, optional = true } git-next-forge-forgejo = { workspace = true, optional = true }
git-next-forge-github = { workspace = true, optional = true }
# logging # logging
console-subscriber = { workspace = true } console-subscriber = { workspace = true }

View file

@ -1,21 +0,0 @@
use crate::network::Network;
struct Github;
pub(super) struct GithubEnv {
net: Network,
}
impl GithubEnv {
pub(crate) const fn new(net: Network) -> GithubEnv {
Self { net }
}
}
#[async_trait::async_trait]
impl super::ForgeLike for GithubEnv {
fn name(&self) -> String {
"github".to_string()
}
async fn branches_get_all(&self) -> Vec<super::Branch> {
todo!()
}
}

View file

@ -1,27 +1,26 @@
#![allow(dead_code)] //
use git_next_forge_forgejo as forgejo; use git_next_forge_forgejo as forgejo;
use git_next_forge_github as github;
use git_next_git as git; use git_next_git as git;
use kxio::network::Network; use kxio::network::Network;
#[cfg(feature = "github")]
mod github;
mod mock_forge; mod mock_forge;
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub enum Forge { pub enum Forge {
Mock(mock_forge::MockForgeEnv), Mock(mock_forge::MockForge),
#[allow(clippy::enum_variant_names)]
#[cfg(feature = "forgejo")] #[cfg(feature = "forgejo")]
ForgeJo(forgejo::ForgeJo), ForgeJo(git_next_forge_forgejo::ForgeJo),
#[cfg(feature = "github")] #[cfg(feature = "github")]
Github(github::GithubEnv), Github(git_next_forge_github::Github),
} }
impl Forge { impl Forge {
pub const fn new_mock() -> Self { pub const fn new_mock() -> Self {
Self::Mock(mock_forge::MockForgeEnv::new()) Self::Mock(mock_forge::MockForge::new())
} }
#[cfg(feature = "forgejo")] #[cfg(feature = "forgejo")]
pub const fn new_forgejo( pub const fn new_forgejo(
repo_details: git::RepoDetails, repo_details: git::RepoDetails,
@ -30,9 +29,10 @@ impl Forge {
) -> Self { ) -> Self {
Self::ForgeJo(forgejo::ForgeJo::new(repo_details, net, repo)) Self::ForgeJo(forgejo::ForgeJo::new(repo_details, net, repo))
} }
#[cfg(feature = "github")] #[cfg(feature = "github")]
pub const fn new_github(net: Network) -> Self { pub const fn new_github(net: Network) -> Self {
Self::Github(github::GithubEnv::new(net)) Self::Github(github::Github::new(net))
} }
} }
impl std::ops::Deref for Forge { impl std::ops::Deref for Forge {
@ -43,7 +43,7 @@ impl std::ops::Deref for Forge {
#[cfg(feature = "forgejo")] #[cfg(feature = "forgejo")]
Self::ForgeJo(env) => env, Self::ForgeJo(env) => env,
#[cfg(feature = "github")] #[cfg(feature = "github")]
Forge::Github(env) => env, Self::Github(env) => env,
} }
} }
} }

View file

@ -1,20 +1,16 @@
// //
#![cfg(not(tarpaulin_include))] #![cfg(not(tarpaulin_include))]
use derive_more::Constructor;
use git::OpenRepository; use git::OpenRepository;
use git_next_config as config; use git_next_config as config;
use git_next_git as git; use git_next_git as git;
struct MockForge; #[derive(Clone, Debug, Constructor)]
#[derive(Clone, Debug)] pub struct MockForge;
pub struct MockForgeEnv;
impl MockForgeEnv {
pub(crate) const fn new() -> Self {
Self
}
}
#[async_trait::async_trait] #[async_trait::async_trait]
impl git::ForgeLike for MockForgeEnv { impl git::ForgeLike for MockForge {
fn name(&self) -> String { fn name(&self) -> String {
"mock".to_string() "mock".to_string()
} }

View file

@ -1,8 +0,0 @@
use super::*;
#[test]
fn test_name() {
let net = Network::new_mock();
let forge = Forge::new_github(net);
assert_eq!(forge.name(), "github");
}

View file

@ -4,9 +4,6 @@ use super::*;
use git_next_config as config; use git_next_config as config;
use git_next_git as git; use git_next_git as git;
#[cfg(feature = "github")]
mod github;
#[test] #[test]
fn test_mock_name() { fn test_mock_name() {
let forge = Forge::new_mock(); let forge = Forge::new_mock();

View file

@ -12,10 +12,10 @@ pub struct Positions {
#[derive(Debug, derive_more::Display)] #[derive(Debug, derive_more::Display)]
pub enum Error { pub enum Error {
Network(Box<kxio::network::NetworkError>),
Fetch(git::fetch::Error), Fetch(git::fetch::Error),
CommitLog(git::commit::log::Error),
#[display("Failed to Reset Branch {branch} to {commit}")] #[display("Failed to Reset Branch {branch} to {commit}")]
FailedToResetBranch { FailedToResetBranch {
branch: BranchName, branch: BranchName,

View file

@ -4,7 +4,7 @@ version = { workspace = true }
edition = { workspace = true } edition = { workspace = true }
[features] [features]
default = ["forgejo"] default = ["forgejo", "github"]
forgejo = [] forgejo = []
github = [] github = []

View file

@ -3,11 +3,6 @@ name = "git-next-server"
version = { workspace = true } version = { workspace = true }
edition = { workspace = true } edition = { workspace = true }
[features]
default = ["forgejo"]
forgejo = []
github = []
[dependencies] [dependencies]
git-next-config = { workspace = true } git-next-config = { workspace = true }
git-next-git = { workspace = true } git-next-git = { workspace = true }