use std::collections::BTreeMap;
use std::path::Path;
use serde::Deserialize;
use serde::Serialize;
pub fn pick<T>(flag: Option<T>, configured: Option<T>, builtin: T) -> T {
flag.or(configured).unwrap_or(builtin)
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct RunConfig {
pub discovery: Discovery,
pub execution: Execution,
pub output: Output,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Discovery {
pub roots: Vec<String>,
pub repo_marker: Option<String>,
pub select: Option<Selection>,
pub exclude: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(
tag = "mode",
content = "value",
rename_all = "snake_case",
deny_unknown_fields
)]
pub enum Selection {
All,
Priority(String),
Names(Vec<String>),
ChangedFiles(String),
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Execution {
pub transport: Option<String>,
pub renderer: Option<String>,
pub model: Option<String>,
pub effort: Option<String>,
pub binary: Option<BinarySource>,
pub env: BTreeMap<String, String>,
pub timeout_scale: Option<f64>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(
tag = "source",
content = "change",
rename_all = "snake_case",
deny_unknown_fields
)]
pub enum BinarySource {
Installed,
Build(String),
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Output {
pub artifact_dir: Option<String>,
pub report_path: Option<String>,
pub result_json_path: Option<String>,
pub publishers: Vec<Publisher>,
pub require: Requirements,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Publisher {
pub name: String,
pub settings: BTreeMap<String, String>,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Requirements {
pub uploaded_media: bool,
pub media_publisher: Option<String>,
}
impl RunConfig {
pub fn parse(text: &str) -> Result<Self, String> {
if text.trim().is_empty() {
return Ok(Self::default());
}
serde_yaml::from_str(text).map_err(|e| format!("invalid config: {e}"))
}
pub fn from_path(path: &Path) -> Result<Self, String> {
let text = std::fs::read_to_string(path)
.map_err(|e| format!("cannot read config {}: {e}", path.display()))?;
Self::parse(&text).map_err(|e| format!("{}: {e}", path.display()))
}
pub fn publisher(&self, name: &str) -> Option<&Publisher> {
self.output.publishers.iter().find(|p| p.name == name)
}
}
impl Discovery {
pub fn excludes(&self, recipe_name: &str) -> bool {
self.exclude.iter().any(|pattern| {
globset::Glob::new(pattern)
.map(|g| g.compile_matcher().is_match(recipe_name))
.unwrap_or(false)
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn an_absent_config_asks_for_nothing() {
let c = RunConfig::default();
assert_eq!(c.discovery.select, None);
assert_eq!(c.execution.renderer, None);
assert_eq!(c.output.artifact_dir, None);
assert!(c.output.publishers.is_empty());
assert!(!c.output.require.uploaded_media);
}
#[test]
fn an_empty_file_is_an_empty_config_not_an_error() {
for text in ["", " ", "\n\n", "# nothing here\n"] {
assert_eq!(RunConfig::parse(text).unwrap(), RunConfig::default());
}
}
#[test]
fn a_flag_beats_the_config_which_beats_the_default() {
assert_eq!(pick(Some("flag"), Some("cfg"), "builtin"), "flag");
assert_eq!(pick(None, Some("cfg"), "builtin"), "cfg");
assert_eq!(pick(None, None, "builtin"), "builtin");
}
#[test]
fn the_ci_workflows_flags_are_all_expressible() {
let text = r#"
discovery:
roots: ["some/framework/root/"]
repo_marker: "/repo/"
select: {mode: names, value: [smoke, prompt-response, plugins]}
execution:
transport: pty
renderer: some-renderer
binary: {source: installed}
output:
artifact_dir: /tmp/evidence
report_path: /tmp/report.md
result_json_path: /tmp/results.json
publishers:
- name: object-store
settings:
bucket: some-bucket
media_path: run/evidence
report_path: run/report
require:
uploaded_media: true
media_publisher: image-host
"#;
let c = RunConfig::parse(text).unwrap();
assert_eq!(
c.discovery.select,
Some(Selection::Names(vec![
"smoke".to_string(),
"prompt-response".to_string(),
"plugins".to_string(),
]))
);
assert_eq!(c.execution.binary, Some(BinarySource::Installed));
assert_eq!(c.output.report_path.as_deref(), Some("/tmp/report.md"));
assert_eq!(
c.publisher("object-store").unwrap().settings["bucket"],
"some-bucket"
);
assert_eq!(
c.output.require.media_publisher.as_deref(),
Some("image-host")
);
}
#[test]
fn every_way_of_selecting_recipes_round_trips() {
for (text, expected) in [
("select: {mode: all}", Selection::All),
(
"select: {mode: priority, value: P0}",
Selection::Priority("P0".into()),
),
(
"select: {mode: names, value: [a]}",
Selection::Names(vec!["a".to_string()]),
),
(
"select: {mode: changed_files, value: /tmp/c.txt}",
Selection::ChangedFiles("/tmp/c.txt".into()),
),
] {
let d: Discovery = serde_yaml::from_str(text).unwrap();
assert_eq!(d.select, Some(expected));
}
}
#[test]
fn a_second_selection_has_nowhere_to_go() {
let e = RunConfig::parse("discovery:\n select: {mode: priority, value: P0, names: [a]}\n")
.unwrap_err();
assert!(e.contains("names"), "{e}");
}
#[test]
fn a_misspelled_selection_mode_lists_the_real_ones() {
let e = RunConfig::parse("discovery:\n select: {mode: prioritie}\n").unwrap_err();
assert!(e.contains("prioritie") && e.contains("priority"), "{e}");
}
#[test]
fn json_parses_too() {
let c = RunConfig::parse(r#"{"execution": {"renderer": "alternate"}}"#).unwrap();
assert_eq!(c.execution.renderer.as_deref(), Some("alternate"));
}
#[test]
fn a_misspelled_key_is_an_error_not_a_shrug() {
let e = RunConfig::parse("output:\n artifactdir: /tmp/x\n").unwrap_err();
assert!(e.contains("artifactdir"), "{e}");
}
#[test]
fn a_misspelled_section_is_an_error_too() {
let e = RunConfig::parse("executon:\n renderer: some-renderer\n").unwrap_err();
assert!(e.contains("executon"), "{e}");
}
#[test]
fn building_from_a_checkout_carries_the_change_id() {
let c = RunConfig::parse("execution:\n binary: {source: build, change: D123}\n").unwrap();
assert_eq!(c.execution.binary, Some(BinarySource::Build("D123".into())));
}
#[test]
fn excluding_a_recipe_by_glob() {
let d = Discovery {
exclude: vec!["slow-*".to_string(), "plugins".to_string()],
..Default::default()
};
assert!(d.excludes("slow-startup"));
assert!(d.excludes("plugins"));
assert!(!d.excludes("smoke"));
}
#[test]
fn an_unparseable_exclude_pattern_excludes_nothing() {
let d = Discovery {
exclude: vec!["[".to_string()],
..Default::default()
};
assert!(!d.excludes("smoke"));
}
#[test]
fn nothing_is_excluded_by_default() {
assert!(!Discovery::default().excludes("smoke"));
}
#[test]
fn a_missing_file_says_which_file() {
let e = RunConfig::from_path(Path::new("/nonexistent/config.yaml")).unwrap_err();
assert!(e.contains("/nonexistent/config.yaml"), "{e}");
}
#[test]
fn a_config_round_trips_through_serialisation() {
let original = RunConfig {
discovery: Discovery {
select: Some(Selection::Priority("P0".into())),
exclude: vec!["flaky-*".to_string()],
..Default::default()
},
execution: Execution {
renderer: Some("all".into()),
timeout_scale: Some(1.5),
env: BTreeMap::from([("KEY".to_string(), "value".to_string())]),
..Default::default()
},
output: Output {
artifact_dir: Some("/tmp/e".into()),
..Default::default()
},
};
let text = serde_yaml::to_string(&original).unwrap();
assert_eq!(RunConfig::parse(&text).unwrap(), original);
}
}