Skip to content

Commit

Permalink
fix: Make sure GitHub job pushes latest image on scheduled job
Browse files Browse the repository at this point in the history
  • Loading branch information
gmpinder committed Aug 24, 2024
1 parent f13b676 commit 0497241
Show file tree
Hide file tree
Showing 11 changed files with 230 additions and 178 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions process/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,10 @@ typed-builder.workspace = true
users.workspace = true
uuid.workspace = true

[dev-dependencies]
rstest.workspace = true
blue-build-utils = { version = "=0.8.13", path = "../utils", features = ["test"] }

[lints]
workspace = true

Expand Down
13 changes: 7 additions & 6 deletions process/drivers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -197,8 +197,9 @@ impl Driver {
#[cfg(test)]
{
use miette::IntoDiagnostic;
let _ = recipe; // silence lint

if std::env::var(crate::test::BB_UNIT_TEST_MOCK_GET_OS_VERSION).is_ok() {
if true {
return crate::test::create_test_recipe()
.image_version
.parse()
Expand All @@ -223,11 +224,11 @@ impl Driver {
let inspection = Self::get_metadata(&inspect_opts)?;

let os_version = inspection.get_version().ok_or_else(|| {
miette!(
help = format!("Please check with the image author about using '{IMAGE_VERSION_LABEL}' to report the os version."),
"Unable to get the OS version from the labels"
)
})?;
miette!(
help = format!("Please check with the image author about using '{IMAGE_VERSION_LABEL}' to report the os version."),
"Unable to get the OS version from the labels"
)
})?;
trace!("os_version: {os_version}");

os_version
Expand Down
106 changes: 34 additions & 72 deletions process/drivers/github_driver.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
use blue_build_utils::{
constants::{
GITHUB_EVENT_NAME, GITHUB_REF_NAME, GITHUB_SHA, GITHUB_TOKEN_ISSUER_URL,
GITHUB_WORKFLOW_REF, PR_EVENT_NUMBER,
},
get_env_var,
use blue_build_utils::constants::{
GITHUB_EVENT_NAME, GITHUB_EVENT_PATH, GITHUB_REF_NAME, GITHUB_SHA, GITHUB_TOKEN_ISSUER_URL,
GITHUB_WORKFLOW_REF, PR_EVENT_NUMBER,
};
use event::Event;
use log::trace;

#[cfg(not(test))]
use blue_build_utils::get_env_var;

#[cfg(test)]
use blue_build_utils::test_utils::get_env_var;

use super::{CiDriver, Driver};

mod event;
Expand All @@ -16,16 +19,8 @@ pub struct GithubDriver;

impl CiDriver for GithubDriver {
fn on_default_branch() -> bool {
Event::try_new().map_or_else(
|_| false,
|event| match (event.commit_ref, event.head) {
(Some(commit_ref), _) => {
commit_ref.trim_start_matches("refs/heads/") == event.repository.default_branch
}
(_, Some(head)) => event.repository.default_branch == head.commit_ref,
_ => false,
},
)
get_env_var(GITHUB_EVENT_PATH)
.is_ok_and(|path| Event::try_new(path).is_ok_and(|e| e.on_default_branch()))
}

fn keyless_cert_identity() -> miette::Result<String> {
Expand Down Expand Up @@ -74,120 +69,100 @@ impl CiDriver for GithubDriver {
}

fn get_repo_url() -> miette::Result<String> {
Ok(Event::try_new()?.repository.html_url)
Ok(Event::try_new(get_env_var(GITHUB_EVENT_PATH)?)?
.repository
.html_url)
}

fn get_registry() -> miette::Result<String> {
Ok(format!(
"ghcr.io/{}",
Event::try_new()?.repository.owner.login
Event::try_new(get_env_var(GITHUB_EVENT_PATH)?)?
.repository
.owner
.login
))
}
}

#[cfg(test)]
mod test {
use std::env;

use blue_build_utils::constants::{
GITHUB_EVENT_NAME, GITHUB_EVENT_PATH, GITHUB_REF_NAME, GITHUB_SHA, PR_EVENT_NUMBER,
use blue_build_utils::{
constants::{
GITHUB_EVENT_NAME, GITHUB_EVENT_PATH, GITHUB_REF_NAME, GITHUB_SHA, PR_EVENT_NUMBER,
},
test_utils::set_env_var,
};

use crate::{
drivers::CiDriver,
test::{create_test_recipe, BB_UNIT_TEST_MOCK_GET_OS_VERSION, ENV_LOCK},
};
use crate::{drivers::CiDriver, test::create_test_recipe};

use super::GithubDriver;

fn setup_default_branch() {
setup();
env::set_var(
set_env_var(
GITHUB_EVENT_PATH,
"../test-files/github-events/default-branch.json",
);
env::set_var(GITHUB_REF_NAME, "main");
set_env_var(GITHUB_REF_NAME, "main");
}

fn setup_pr_branch() {
setup();
env::set_var(
set_env_var(
GITHUB_EVENT_PATH,
"../test-files/github-events/pr-branch.json",
);
env::set_var(GITHUB_EVENT_NAME, "pull_request");
env::set_var(GITHUB_REF_NAME, "test");
env::set_var(PR_EVENT_NUMBER, "12");
set_env_var(GITHUB_EVENT_NAME, "pull_request");
set_env_var(GITHUB_REF_NAME, "test");
set_env_var(PR_EVENT_NUMBER, "12");
}

fn setup_branch() {
setup();
env::set_var(GITHUB_EVENT_PATH, "../test-files/github-events/branch.json");
env::set_var(GITHUB_REF_NAME, "test");
set_env_var(GITHUB_EVENT_PATH, "../test-files/github-events/branch.json");
set_env_var(GITHUB_REF_NAME, "test");
}

fn setup() {
env::set_var(GITHUB_EVENT_NAME, "push");
env::set_var(GITHUB_SHA, "1234567890");
env::set_var(BB_UNIT_TEST_MOCK_GET_OS_VERSION, "");
}

fn teardown() {
env::remove_var(GITHUB_EVENT_NAME);
env::remove_var(GITHUB_EVENT_PATH);
env::remove_var(GITHUB_REF_NAME);
env::remove_var(PR_EVENT_NUMBER);
env::remove_var(GITHUB_SHA);
env::remove_var(BB_UNIT_TEST_MOCK_GET_OS_VERSION);
set_env_var(GITHUB_EVENT_NAME, "push");
set_env_var(GITHUB_SHA, "1234567890");
}

#[test]
fn get_registry() {
let _env = ENV_LOCK.lock().unwrap();

setup_default_branch();

let registry = GithubDriver::get_registry().unwrap();

assert_eq!(registry, "ghcr.io/test-owner");
teardown();
}

#[test]
fn on_default_branch_true() {
let _env = ENV_LOCK.lock().unwrap();

setup_default_branch();

assert!(GithubDriver::on_default_branch());
teardown();
}

#[test]
fn on_default_branch_false() {
let _env = ENV_LOCK.lock().unwrap();

setup_pr_branch();

assert!(!GithubDriver::on_default_branch());
teardown();
}

#[test]
fn get_repo_url() {
let _env = ENV_LOCK.lock().unwrap();

setup_branch();

let url = GithubDriver::get_repo_url().unwrap();

assert_eq!(url, "https://example.com/");
teardown();
}

#[test]
fn generate_tags_default_branch() {
let _env = ENV_LOCK.lock().unwrap();
let timestamp = blue_build_utils::get_tag_timestamp();

setup_default_branch();
Expand All @@ -205,13 +180,10 @@ mod test {
expected_tags.sort();

assert_eq!(tags, expected_tags);

teardown();
}

#[test]
fn generate_tags_default_branch_alt_tags() {
let _env = ENV_LOCK.lock().unwrap();
let timestamp = blue_build_utils::get_tag_timestamp();

setup_default_branch();
Expand All @@ -232,14 +204,10 @@ mod test {
expected_tags.sort();

assert_eq!(tags, expected_tags);

teardown();
}

#[test]
fn generate_tags_pr_branch() {
let _env = ENV_LOCK.lock().unwrap();

setup_pr_branch();

let mut tags = GithubDriver::generate_tags(&create_test_recipe()).unwrap();
Expand All @@ -249,14 +217,10 @@ mod test {
expected_tags.sort();

assert_eq!(tags, expected_tags);

teardown();
}

#[test]
fn generate_tags_branch() {
let _env = ENV_LOCK.lock().unwrap();

setup_branch();

let mut tags = GithubDriver::generate_tags(&create_test_recipe()).unwrap();
Expand All @@ -266,7 +230,5 @@ mod test {
expected_tags.sort();

assert_eq!(tags, expected_tags);

teardown();
}
}
89 changes: 79 additions & 10 deletions process/drivers/github_driver/event.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,16 @@
use std::{fs, path::PathBuf};
use std::path::Path;

use blue_build_utils::{constants::GITHUB_EVENT_PATH, get_env_var};
use miette::{IntoDiagnostic, Result};
use blue_build_utils::constants::GITHUB_REF_NAME;
use log::debug;
use miette::{Context, IntoDiagnostic, Result};
use serde::Deserialize;

#[cfg(test)]
use blue_build_utils::test_utils::get_env_var;

#[cfg(not(test))]
use blue_build_utils::get_env_var;

#[derive(Debug, Deserialize, Clone)]
pub(super) struct Event {
pub repository: EventRepository,
Expand All @@ -14,17 +21,57 @@ pub(super) struct Event {
pub commit_ref: Option<String>,
}

impl TryFrom<&str> for Event {
type Error = miette::Report;

fn try_from(value: &str) -> std::prelude::v1::Result<Self, Self::Error> {
serde_json::from_str(value).into_diagnostic()
}
}

impl Event {
pub fn try_new() -> Result<Self> {
get_env_var(GITHUB_EVENT_PATH)
.map(PathBuf::from)
.and_then(|event_path| {
serde_json::from_str::<Self>(&fs::read_to_string(event_path).into_diagnostic()?)
.into_diagnostic()
})
pub fn try_new<P>(path: P) -> Result<Self>
where
P: AsRef<Path>,
{
fn inner(path: &Path) -> Result<Event> {
let contents = std::fs::read_to_string(path)
.into_diagnostic()
.with_context(|| format!("Path: {}", path.display()))?;
Event::try_from(contents.as_str())
}
inner(path.as_ref())
}

pub fn on_default_branch(&self) -> bool {
debug!("{self:#?}");

match (
self.commit_ref.as_ref(),
self.head.as_ref(),
get_env_var(GITHUB_REF_NAME),
) {
(Some(commit_ref), _, _) => {
commit_ref.trim_start_matches("refs/heads/") == self.repository.default_branch
}
(_, Some(head), _) => self.repository.default_branch == head.commit_ref,
(_, _, Ok(ref_name)) => self.repository.default_branch == ref_name,
_ => false,
}
}
}

// impl Event {
// pub fn try_new() -> Result<Self> {
// get_env_var(GITHUB_EVENT_PATH)
// .map(PathBuf::from)
// .and_then(|event_path| {
// serde_json::from_str::<Self>(&fs::read_to_string(event_path).into_diagnostic()?)
// .into_diagnostic()
// })
// }
// }

#[derive(Debug, Deserialize, Clone)]
pub(super) struct EventRepository {
pub default_branch: String,
Expand All @@ -42,3 +89,25 @@ pub(super) struct EventRefInfo {
#[serde(alias = "ref")]
pub commit_ref: String,
}

#[cfg(test)]
mod test {
use blue_build_utils::{constants::GITHUB_REF_NAME, test_utils::set_env_var};
use rstest::rstest;

use super::Event;

#[rstest]
#[case::scheduled_main("../test-files/github-events/scheduled.json", "main", true)]
#[case::push_main("../test-files/github-events/default-branch.json", "main", true)]
#[case::pr("../test-files/github-events/pr-branch.json", "test", false)]
#[case::branch("../test-files/github-events/branch.json", "test", false)]
fn test_on_default_branch(#[case] path: &str, #[case] ref_name: &str, #[case] expected: bool) {
set_env_var(GITHUB_REF_NAME, ref_name);

let event = Event::try_new(path).unwrap();
eprintln!("{event:?}");

assert_eq!(expected, event.on_default_branch());
}
}
Loading

0 comments on commit 0497241

Please sign in to comment.