Skip to content

Commit

Permalink
update workflow
Browse files Browse the repository at this point in the history
  • Loading branch information
tusharmath committed Nov 4, 2024
1 parent 552538e commit b0c50ae
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 17 deletions.
57 changes: 43 additions & 14 deletions workspace/gh-workflow-gen/build.rs
Original file line number Diff line number Diff line change
@@ -1,39 +1,68 @@
use indexmap::IndexMap;
use serde_json::Value;
use gh_workflow::{Expression, Job, OneOrManyOrObject, PermissionLevel, Permissions, Step, WorkflowOn};
use gh_workflow::{
Expression,
Job,
OneOrManyOrObject,
PermissionLevel,
Permissions,
Step,
WorkflowOn,
};

fn main() {
// TODO: replace `with` with RustToolchain struct.

let mut with = IndexMap::new();
with.insert("toolchain".to_string(), Value::String("stable".to_string()));
let steps = vec![
Step::new("Checkout code").uses("actions/checkout@v4".to_string()),
Step::new("Setup rust").uses("actions-rust-lang/setup-rust-toolchain@v1".to_string()).with(with),
Step::new("Run tests").run("RUSTFLAGS=\"-Awarnings\" cargo test --all-features --workspace".to_string()),
];

let job = Job::new("Run tests")
.runs_on(OneOrManyOrObject::Single("ubuntu-latest".to_string()))
.timeout_minutes(10)
.steps(steps);
.add_step(Step::new("Checkout code").uses("actions/checkout@v4".to_string()))
.add_step(
Step::new("Setup rust")
.uses("actions-rust-lang/setup-rust-toolchain@v1".to_string())
.with(("toolchain", "stable"))
)
.add_step(
Step::new("Run tests").run(
"RUSTFLAGS=\"-Awarnings\" cargo test --all-features --workspace".to_string()
)
);

let mut on = IndexMap::new();
let mut branches = IndexMap::new();
branches.insert("branches".to_string(), WorkflowOn::Multiple(vec!["main".to_string()]));

let mut on_pr = IndexMap::new();
on_pr.insert("types".to_string(), WorkflowOn::Multiple(vec!["opened", "synchronize", "reopened"].into_iter().map(|x| x.to_string()).collect()));
on_pr.insert("branches".to_string(), WorkflowOn::Multiple(vec!["main"].into_iter().map(|x| x.to_string()).collect()));
on_pr.insert(
"types".to_string(),
WorkflowOn::Multiple(
vec!["opened", "synchronize", "reopened"]
.into_iter()
.map(|x| x.to_string())
.collect()
)
);
on_pr.insert(
"branches".to_string(),
WorkflowOn::Multiple(
vec!["main"]
.into_iter()
.map(|x| x.to_string())
.collect()
)
);

on.insert("push".to_string(), WorkflowOn::Map(branches));
on.insert("pull_request".to_string(), WorkflowOn::Map(on_pr));

let workflow = gh_workflow::Workflow::new("CI")
let workflow = gh_workflow::Workflow
::new("CI")
.permissions(Permissions::default().contents(PermissionLevel::Read))
.on(WorkflowOn::Map(on))
.add_job("test", job)
.unwrap();

workflow.write(format!("{}/../../.github/workflows/ci.yml",env!("CARGO_MANIFEST_DIR"))).unwrap();
workflow
.write(format!("{}/../../.github/workflows/ci.yml", env!("CARGO_MANIFEST_DIR")))
.unwrap();
}
42 changes: 39 additions & 3 deletions workspace/gh-workflow/src/workflow.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
use std::path::Path;
use derive_setters::Setters;
use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
use serde::{ Deserialize, Serialize };
use serde_json::Value;

use crate::error::{Error, Result};
use crate::error::{ Error, Result };

#[derive(Default, Debug, Serialize, Deserialize, Clone, PartialEq, Eq, Hash)]
#[serde(rename_all = "kebab-case")]
Expand Down Expand Up @@ -126,7 +126,10 @@ impl Workflow {
}
pub fn write<T: AsRef<str>>(self, path: T) -> Result<()> {
let path = Path::new(path.as_ref());
path.parent().map_or(Ok(()), |parent| std::fs::create_dir_all(parent)).map_err(Error::Io)?;
path
.parent()
.map_or(Ok(()), |parent| std::fs::create_dir_all(parent))
.map_err(Error::Io)?;

std::fs::write(path, self.to_string()?).map_err(Error::Io)?;
Ok(())
Expand Down Expand Up @@ -212,6 +215,13 @@ impl Job {
pub fn new<T: AsRef<str>>(name: T) -> Self {
Self { name: Some(name.as_ref().to_string()), ..Default::default() }
}

pub fn add_step(mut self, step: Step) -> Self {
let mut steps = self.steps.unwrap_or_default();
steps.push(step);
self.steps = Some(steps);
self
}
}

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
Expand Down Expand Up @@ -244,6 +254,7 @@ pub struct Step {
#[serde(skip_serializing_if = "Option::is_none")]
pub uses: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
#[setters(skip)]
pub with: Option<IndexMap<String, Value>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub run: Option<String>,
Expand All @@ -265,6 +276,31 @@ impl Step {
pub fn new<T: AsRef<str>>(name: T) -> Self {
Self { name: Some(name.as_ref().to_string()), ..Default::default() }
}

pub fn with<K: IsWith>(self, item: K) -> Self {
item.apply(self)
}
}

pub trait IsWith {
fn apply(self, step: Step) -> Step;
}

impl IsWith for IndexMap<String, Value> {
fn apply(self, mut step: Step) -> Step {
// TODO: extend the existing map instead of replacing it
step.with = Some(self);
step
}
}

impl<S: AsRef<str>> IsWith for (S, S) {
fn apply(self, mut step: Step) -> Step {
let mut index_map: IndexMap<String, Value> = step.with.unwrap_or_default();
index_map.insert(self.0.as_ref().to_string(), Value::String(self.1.as_ref().to_string()));
step.with = Some(index_map);
step
}
}

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, Default)]
Expand Down

0 comments on commit b0c50ae

Please sign in to comment.