use std::collections::HashMap;
use std::path::Path;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
pub const RECIPE_VERSION: u32 = 1;
fn default_recipe_version() -> u32 {
RECIPE_VERSION
}
fn default_description() -> String {
String::new()
}
fn default_intent() -> String {
String::new()
}
fn default_priority() -> String {
"P2".to_string()
}
fn default_execution() -> String {
"scripted".to_string()
}
fn default_determinism() -> String {
"deterministic".to_string()
}
fn default_timeout_seconds() -> f64 {
30.0
}
fn default_cols() -> u32 {
100
}
fn default_rows() -> u32 {
30
}
fn default_expect_exit_code() -> Option<i32> {
Some(0)
}
fn default_pty() -> bool {
true
}
fn default_renderers() -> HashMap<String, Vec<String>> {
let mut m = HashMap::new();
m.insert("default".to_string(), Vec::new());
m
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct CommandSpec {
pub argv: Vec<String>,
#[serde(default)]
#[schemars(with = "Option<String>")]
pub cwd: Option<String>,
#[serde(default)]
pub env: HashMap<String, String>,
#[serde(default = "default_pty")]
pub pty: bool,
#[serde(default, flatten)]
#[schemars(flatten)]
pub extension: HashMap<String, serde_json::Value>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct Step {
pub action: String,
#[serde(default)]
#[schemars(with = "Option<String>")]
pub name: Option<String>,
#[serde(default)]
#[schemars(with = "Option<f64>")]
pub timeout_seconds: Option<f64>,
#[serde(default, flatten)]
#[schemars(flatten)]
pub extra: HashMap<String, serde_json::Value>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct Assertion {
#[serde(rename = "type")]
pub kind: String,
#[serde(default)]
#[schemars(with = "Option<String>")]
pub name: Option<String>,
#[serde(default, flatten)]
#[schemars(flatten)]
pub extra: HashMap<String, serde_json::Value>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct Recipe {
#[serde(default = "default_recipe_version")]
#[schemars(range(min = 1, max = 1))]
pub recipe_version: u32,
pub name: String,
#[serde(default = "default_description")]
pub description: String,
#[serde(default = "default_intent")]
pub intent: String,
#[serde(default = "default_priority")]
pub priority: String,
#[serde(default = "default_execution")]
pub execution: String,
#[serde(default = "default_determinism")]
pub determinism: String,
#[serde(default)]
pub ci_paths: Vec<String>,
#[serde(default)]
pub checks: Vec<String>,
#[serde(default)]
pub operator: HashMap<String, serde_json::Value>,
#[serde(default = "default_renderers")]
pub renderers: HashMap<String, Vec<String>>,
pub command: CommandSpec,
#[serde(default)]
pub steps: Vec<Step>,
#[serde(default)]
pub assertions: Vec<Assertion>,
#[serde(default = "default_expect_exit_code")]
#[schemars(with = "Option<i32>")]
pub expect_exit_code: Option<i32>,
#[serde(default = "default_timeout_seconds")]
pub timeout_seconds: f64,
#[serde(default = "default_cols")]
pub cols: u32,
#[serde(default = "default_rows")]
pub rows: u32,
#[serde(skip, default)]
#[schemars(skip)]
pub source_path: Option<String>,
#[serde(default, flatten)]
#[schemars(flatten)]
pub extension: HashMap<String, serde_json::Value>,
}
impl Recipe {
pub fn from_file(path: &Path) -> Result<Self, crate::error::CoreError> {
let content = std::fs::read_to_string(path).map_err(|e| crate::error::CoreError::Io {
path: path.display().to_string(),
source: e,
})?;
Self::from_str(&content, Some(path))
}
pub fn from_str(content: &str, source: Option<&Path>) -> Result<Self, crate::error::CoreError> {
let mut recipe: Self = serde_json::from_str(content)
.or_else(|_| serde_yaml::from_str(content))
.map_err(|e| crate::error::CoreError::Parse {
path: source
.map(|p| p.display().to_string())
.unwrap_or_else(|| "<string>".to_string()),
message: e.to_string(),
})?;
if let Some(p) = source {
recipe.source_path = Some(p.display().to_string());
}
Ok(recipe)
}
pub fn was_recipe_version_missing(raw: &serde_json::Value) -> bool {
!raw.as_object()
.map(|o| o.contains_key("recipe_version"))
.unwrap_or(false)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn legacy_recipe_defaults_version_to_one() {
let recipe: Recipe =
serde_json::from_str(r#"{"name":"x","command":{"argv":["true"]}}"#).expect("parse");
assert_eq!(recipe.recipe_version, 1);
assert_eq!(recipe.priority, "P2");
assert_eq!(recipe.cols, 100);
assert_eq!(recipe.timeout_seconds, 30.0);
assert_eq!(recipe.expect_exit_code, Some(0));
}
#[test]
fn extension_fields_are_preserved() {
let recipe: Recipe = serde_json::from_str(
r#"{"name":"x","command":{"argv":["true"],"custom":"keep"},"my_extra":"hello","recipe_version":1}"#,
)
.expect("parse");
assert_eq!(recipe.extension.get("my_extra").unwrap(), "hello");
assert_eq!(recipe.command.extension.get("custom").unwrap(), "keep");
}
#[test]
fn json_and_yaml_both_load() {
let json_str = r#"{"name":"x","command":{"argv":["echo","hi"]},"recipe_version":1}"#;
let yaml_str = "name: x\ncommand:\n argv: [echo, hi]\nrecipe_version: 1\n";
let from_json = Recipe::from_str(json_str, None).expect("json");
let from_yaml = Recipe::from_str(yaml_str, None).expect("yaml");
assert_eq!(from_json.name, "x");
assert_eq!(from_yaml.name, "x");
assert_eq!(from_json.command.argv, from_yaml.command.argv);
}
#[test]
fn step_extra_preserved() {
let recipe: Recipe = serde_json::from_str(
r#"{"name":"x","command":{"argv":["true"]},"steps":[{"action":"wait_for_text","text":"hello","timeout_seconds":5}],"recipe_version":1}"#,
)
.expect("parse");
assert_eq!(recipe.steps[0].action, "wait_for_text");
assert_eq!(recipe.steps[0].extra.get("text").unwrap(), "hello");
}
}