use crate::plan::{Selected, Unit};
use crate::workflow::{Job, Service, Step, Trigger, Workflow};
use serde::{Deserialize, Serialize};
use serde_yaml::Value as Y;
pub use crate::digest::Digested;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", content = "value", rename_all = "snake_case")]
pub enum MatrixValue {
Null,
Bool(bool),
Number(String),
String(String),
Seq(Vec<MatrixValue>),
Map(Vec<(String, MatrixValue)>),
}
impl MatrixValue {
pub fn from_yaml(v: &Y) -> Self {
match v {
Y::Null => MatrixValue::Null,
Y::Bool(b) => MatrixValue::Bool(*b),
Y::Number(n) => MatrixValue::Number(n.to_string()),
Y::String(s) => MatrixValue::String(s.clone()),
Y::Sequence(s) => MatrixValue::Seq(s.iter().map(Self::from_yaml).collect()),
Y::Mapping(m) => MatrixValue::Map(
m.iter()
.map(|(k, v)| (key_text(k), Self::from_yaml(v)))
.collect(),
),
Y::Tagged(t) => Self::from_yaml(&t.value),
}
}
pub fn to_yaml(&self) -> Y {
match self {
MatrixValue::Null => Y::Null,
MatrixValue::Bool(b) => Y::Bool(*b),
MatrixValue::Number(n) => serde_yaml::from_str::<Y>(n)
.ok()
.filter(|v| v.is_number())
.unwrap_or_else(|| Y::String(n.clone())),
MatrixValue::String(s) => Y::String(s.clone()),
MatrixValue::Seq(s) => Y::Sequence(s.iter().map(Self::to_yaml).collect()),
MatrixValue::Map(m) => {
let mut out = serde_yaml::Mapping::new();
for (k, v) in m {
out.insert(Y::String(k.clone()), v.to_yaml());
}
Y::Mapping(out)
}
}
}
pub fn duplicate_key(&self) -> Option<String> {
match self {
MatrixValue::Seq(s) => s.iter().find_map(Self::duplicate_key),
MatrixValue::Map(m) => {
let mut seen = std::collections::BTreeSet::new();
m.iter()
.find_map(|(k, _)| (!seen.insert(k.as_str())).then(|| k.clone()))
.or_else(|| m.iter().find_map(|(_, v)| v.duplicate_key()))
}
_ => None,
}
}
pub fn to_json(&self) -> serde_json::Value {
use serde_json::Value as J;
match self {
MatrixValue::Null => J::Null,
MatrixValue::Bool(b) => J::Bool(*b),
MatrixValue::Number(n) => n
.parse::<serde_json::Number>()
.map(J::Number)
.unwrap_or_else(|_| J::String(n.clone())),
MatrixValue::String(s) => J::String(s.clone()),
MatrixValue::Seq(s) => J::Array(s.iter().map(Self::to_json).collect()),
MatrixValue::Map(m) => {
J::Object(m.iter().map(|(k, v)| (k.clone(), v.to_json())).collect())
}
}
}
pub fn has_expression(&self) -> bool {
match self {
MatrixValue::String(s) => s.contains("${{"),
MatrixValue::Seq(s) => s.iter().any(Self::has_expression),
MatrixValue::Map(m) => m
.iter()
.any(|(k, v)| k.contains("${{") || v.has_expression()),
_ => false,
}
}
}
fn key_text(k: &Y) -> String {
match k {
Y::String(s) => s.clone(),
Y::Bool(b) => b.to_string(),
Y::Number(n) => n.to_string(),
Y::Null => "null".into(),
Y::Tagged(t) => key_text(&t.value),
other => serde_yaml::to_string(other)
.unwrap_or_default()
.trim()
.to_string(),
}
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct PathFilter {
pub paths: Vec<String>,
pub paths_ignore: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ServiceSpec {
pub id: String,
pub image: String,
pub env: Vec<(String, String)>,
pub ports: Vec<(Option<u16>, u16)>,
pub options: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct StepSpec {
pub id: Option<String>,
pub name: Option<String>,
pub uses: Option<String>,
pub run: Option<String>,
pub with: Vec<(String, String)>,
pub env: Vec<(String, String)>,
pub cond: Option<String>,
pub working_directory: Option<String>,
pub shell: Option<String>,
pub continue_on_error: bool,
pub timeout_minutes: Option<f64>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct JobSpec {
pub id: String,
pub name: Option<String>,
pub needs: Vec<String>,
pub cond: Option<String>,
pub env: Vec<(String, String)>,
pub working_directory: Option<String>,
pub shell: Option<String>,
pub services: Vec<ServiceSpec>,
pub container: bool,
pub reusable: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub runs_on: Option<MatrixValue>,
pub matrix: Option<MatrixValue>,
pub fail_fast: bool,
pub max_parallel: Option<usize>,
pub steps: Vec<StepSpec>,
pub timeout_minutes: Option<f64>,
pub continue_on_error: bool,
pub outputs: Vec<(String, String)>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub job_exprs: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct WorkflowSpec {
pub file: String,
pub name: String,
pub event: String,
pub path_filter: Option<PathFilter>,
pub env: Vec<(String, String)>,
pub working_directory: Option<String>,
pub shell: Option<String>,
pub jobs: Vec<JobSpec>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct UnitSpec {
pub workflow: usize,
pub jobs: Vec<String>,
pub exclusive: bool,
}
impl ServiceSpec {
pub fn from_service(s: &Service) -> Self {
ServiceSpec {
id: s.id.clone(),
image: s.image.clone(),
env: s.env.clone(),
ports: s.ports.clone(),
options: s.options.clone(),
}
}
pub fn to_service(&self) -> Service {
Service {
id: self.id.clone(),
image: self.image.clone(),
env: self.env.clone(),
ports: self.ports.clone(),
options: self.options.clone(),
}
}
}
impl StepSpec {
pub fn from_step(s: &Step) -> Self {
StepSpec {
id: s.id.clone(),
name: s.name.clone(),
uses: s.uses.clone(),
run: s.run.clone(),
with: s.with.clone(),
env: s.env.clone(),
cond: s.cond.clone(),
working_directory: s.working_directory.clone(),
shell: s.shell.clone(),
continue_on_error: s.continue_on_error,
timeout_minutes: s.timeout_minutes,
}
}
pub fn to_step(&self) -> Step {
Step {
id: self.id.clone(),
name: self.name.clone(),
uses: self.uses.clone(),
run: self.run.clone(),
with: self.with.clone(),
env: self.env.clone(),
cond: self.cond.clone(),
working_directory: self.working_directory.clone(),
shell: self.shell.clone(),
continue_on_error: self.continue_on_error,
timeout_minutes: self.timeout_minutes,
}
}
}
impl JobSpec {
pub fn from_job(j: &Job) -> Self {
JobSpec {
id: j.id.clone(),
name: j.name.clone(),
needs: j.needs.clone(),
cond: j.cond.clone(),
env: j.env.clone(),
working_directory: j.working_directory.clone(),
shell: j.shell.clone(),
services: j.services.iter().map(ServiceSpec::from_service).collect(),
container: j.container,
reusable: j.reusable.clone(),
runs_on: j.runs_on.as_ref().map(MatrixValue::from_yaml),
matrix: j.matrix.as_ref().map(MatrixValue::from_yaml),
fail_fast: j.fail_fast,
max_parallel: j.max_parallel,
steps: j.steps.iter().map(StepSpec::from_step).collect(),
timeout_minutes: j.timeout_minutes,
continue_on_error: j.continue_on_error,
outputs: j.outputs.clone(),
job_exprs: j.job_exprs.clone(),
}
}
pub fn to_job(&self) -> Job {
Job {
id: self.id.clone(),
name: self.name.clone(),
needs: self.needs.clone(),
cond: self.cond.clone(),
env: self.env.clone(),
working_directory: self.working_directory.clone(),
shell: self.shell.clone(),
services: self.services.iter().map(ServiceSpec::to_service).collect(),
container: self.container,
reusable: self.reusable.clone(),
runs_on: self.runs_on.as_ref().map(MatrixValue::to_yaml),
matrix: self.matrix.as_ref().map(MatrixValue::to_yaml),
fail_fast: self.fail_fast,
max_parallel: self.max_parallel,
steps: self.steps.iter().map(StepSpec::to_step).collect(),
timeout_minutes: self.timeout_minutes,
continue_on_error: self.continue_on_error,
outputs: self.outputs.clone(),
job_exprs: self.job_exprs.clone(),
}
}
}
impl WorkflowSpec {
pub fn from_selected(s: &Selected) -> Self {
let w = &s.wf;
let path_filter = w
.triggers
.iter()
.find(|t| {
if s.event == "push" {
t.event == "push"
} else {
t.event.starts_with("pull_request")
}
})
.map(|t| PathFilter {
paths: t.paths.clone(),
paths_ignore: t.paths_ignore.clone(),
});
WorkflowSpec {
file: w.file.clone(),
name: w.name.clone(),
event: s.event.clone(),
path_filter,
env: w.env.clone(),
working_directory: w.working_directory.clone(),
shell: w.shell.clone(),
jobs: w.jobs.iter().map(JobSpec::from_job).collect(),
}
}
pub fn to_selected(&self) -> Selected {
let triggers = self
.path_filter
.iter()
.map(|f| Trigger {
event: if self.event == "push" {
"push".into()
} else {
"pull_request".into()
},
paths: f.paths.clone(),
paths_ignore: f.paths_ignore.clone(),
..Trigger::default()
})
.collect();
Selected {
wf: Workflow {
file: self.file.clone(),
name: self.name.clone(),
triggers,
env: self.env.clone(),
working_directory: self.working_directory.clone(),
shell: self.shell.clone(),
jobs: self.jobs.iter().map(JobSpec::to_job).collect(),
},
event: self.event.clone(),
}
}
pub fn job(&self, id: &str) -> Option<&JobSpec> {
self.jobs.iter().find(|j| j.id == id)
}
}
impl UnitSpec {
pub fn from_unit(u: &Unit) -> Self {
UnitSpec {
workflow: u.wf,
jobs: u.jobs.clone(),
exclusive: u.exclusive,
}
}
pub fn to_unit(&self) -> Unit {
Unit {
wf: self.workflow,
jobs: self.jobs.clone(),
exclusive: self.exclusive,
}
}
}
pub const WIRE_SCHEMA_VERSION: u32 = 1;
pub fn wire_version() -> u32 {
WIRE_SCHEMA_VERSION
}
pub fn check_version(what: &str, version: u32) -> anyhow::Result<()> {
if version != WIRE_SCHEMA_VERSION {
anyhow::bail!(
"{what}: schema version {version} is not supported (this is {WIRE_SCHEMA_VERSION})"
);
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn job_expressions_survive_a_wire_round_trip_and_keep_legs_apart() {
let w = crate::workflow::parse(
"w.yml",
"on: push\njobs:\n t:\n runs-on: x\n continue-on-error: ${{ matrix.os == 'macos-latest' }}\n steps:\n - run: echo hi\n",
)
.unwrap();
let job = &w.jobs[0];
assert!(!job.job_exprs.is_empty());
let spec = JobSpec::from_job(job);
let text = serde_json::to_string(&spec).unwrap();
let back = serde_json::from_str::<JobSpec>(&text).unwrap().to_job();
assert_eq!(back.job_exprs, job.job_exprs);
let legs = [
crate::os_legs::Leg {
family: crate::os_legs::family_of_label("ubuntu-latest"),
matrix: serde_json::json!({"os": "ubuntu-latest"})
.as_object()
.unwrap()
.clone(),
},
crate::os_legs::Leg {
family: crate::os_legs::family_of_label("macos-latest"),
matrix: serde_json::json!({"os": "macos-latest"})
.as_object()
.unwrap()
.clone(),
},
];
assert_eq!(
crate::os_legs::twins(crate::os_legs::Family::MacOs, &back, &legs),
vec![None, None]
);
let mut v = serde_json::to_value(JobSpec::from_job(&w.jobs[0])).unwrap();
v.as_object_mut().unwrap().remove("job_exprs");
assert!(serde_json::from_value::<JobSpec>(v)
.unwrap()
.job_exprs
.is_empty());
}
#[test]
fn odd_yaml_keys_become_strings_and_survive_a_round_trip() {
let y: Y = serde_yaml::from_str(
"os: [a, b]\n1.5: [x]\nnull: [y]\ntrue: [z]\n10: [w]\ninclude:\n - os: a\n n: 1e3\n",
)
.unwrap();
let m = MatrixValue::from_yaml(&y);
let v = serde_json::to_value(&m).unwrap();
let keys: Vec<&str> = v["value"]
.as_array()
.unwrap()
.iter()
.map(|e| e[0].as_str().unwrap())
.collect();
assert_eq!(keys, ["os", "1.5", "null", "true", "10", "include"]);
assert_eq!(MatrixValue::from_yaml(&m.to_yaml()), m);
let text = serde_json::to_string(&m).unwrap();
assert_eq!(serde_json::from_str::<MatrixValue>(&text).unwrap(), m);
let j = m.to_json();
assert!(j.as_object().unwrap().contains_key("1.5"));
assert_eq!(j["include"][0]["n"], serde_json::json!(1000.0));
}
#[test]
fn null_tagged_and_composite_yaml_values_and_keys_are_kept() {
let y: Y = serde_yaml::from_str("a: null\nb: !t x\n!k c: d\n? [x, y]\n: v\n").unwrap();
let m = MatrixValue::from_yaml(&y);
let v = serde_json::to_value(&m).unwrap()["value"].clone();
assert_eq!(v[0], serde_json::json!(["a", {"type": "null"}]));
assert_eq!(
v[1],
serde_json::json!(["b", {"type": "string", "value": "x"}])
);
assert_eq!(v[2][0], "c");
assert_eq!(v[3][0], "- x\n- y");
assert_eq!(MatrixValue::Null.to_yaml(), Y::Null);
assert_eq!(MatrixValue::Null.to_json(), serde_json::Value::Null);
let n = MatrixValue::Number("x".into());
assert_eq!(n.to_yaml(), Y::String("x".into()));
assert_eq!(n.to_json(), serde_json::json!("x"));
}
#[test]
fn a_duplicate_key_is_found_below_a_sequence_too() {
let dup = MatrixValue::Map(vec![
("a".into(), MatrixValue::Null),
("a".into(), MatrixValue::Null),
]);
assert_eq!(dup.duplicate_key().as_deref(), Some("a"));
assert_eq!(
MatrixValue::Seq(vec![MatrixValue::Null, dup])
.duplicate_key()
.as_deref(),
Some("a")
);
assert_eq!(
MatrixValue::Seq(vec![MatrixValue::Null]).duplicate_key(),
None
);
}
#[test]
fn a_push_workflow_keeps_the_filter_of_its_push_trigger() {
let wf = |event: &str| Selected {
wf: Workflow {
file: "f.yml".into(),
name: "n".into(),
triggers: vec![
Trigger {
event: "pull_request".into(),
paths: vec!["pr/**".into()],
..Trigger::default()
},
Trigger {
event: "push".into(),
paths: vec!["push/**".into()],
paths_ignore: vec!["push/skip/**".into()],
..Trigger::default()
},
],
env: vec![],
working_directory: None,
shell: None,
jobs: vec![],
},
event: event.into(),
};
for (event, paths, back) in [
("push", "push/**", "push"),
("pull_request", "pr/**", "pull_request"),
] {
let spec = WorkflowSpec::from_selected(&wf(event));
assert_eq!(spec.path_filter.as_ref().unwrap().paths, [paths]);
let sel = spec.to_selected();
assert_eq!(sel.wf.triggers[0].event, back);
assert_eq!(sel.wf.triggers[0].paths, [paths]);
let ignore: &[&str] = if event == "push" {
&["push/skip/**"]
} else {
&[]
};
assert_eq!(sel.wf.triggers[0].paths_ignore, ignore);
}
}
#[test]
fn only_this_schema_version_is_read() {
assert_eq!(wire_version(), WIRE_SCHEMA_VERSION);
check_version("x", WIRE_SCHEMA_VERSION).unwrap();
for v in [0, WIRE_SCHEMA_VERSION + 1] {
let e = check_version("a recipe", v).unwrap_err().to_string();
assert!(e.starts_with("a recipe: schema version"), "{e}");
}
}
#[test]
fn expressions_are_found_anywhere() {
let y: Y =
serde_yaml::from_str("a: [1]\ninclude:\n - x: '${{ needs.a.outputs.b }}'\n").unwrap();
assert!(MatrixValue::from_yaml(&y).has_expression());
let y: Y = serde_yaml::from_str("a: [1, 2]").unwrap();
assert!(!MatrixValue::from_yaml(&y).has_expression());
}
}