Skip to main content

tak_cli/
condition.rs

1//! `when` conditions in `tak.toml`, written in [expr](https://expr-lang.org)
2//! — the language mise uses for its own conditions — and evaluated with
3//! [expr-lang](https://github.com/jdx/expr.rs).
4//!
5//! A benchmark or subject whose `when` is false is left out of the run
6//! before anything about it is rendered, so a subject for a tool that is not
7//! installed does not need the variables naming it either.
8//!
9//! In scope:
10//!
11//! - `env` — tak's environment, as a map: `env.VLT_BIN != ""`
12//! - `os`, `arch` — as Rust names them: `"linux"`, `"macos"`, `"x86_64"`, `"aarch64"`
13//! - `ci` — whether `CI` is set to anything but `""` or `"false"`
14//! - `bench`, `subject` — the names being decided on (`subject` is empty for
15//!   a benchmark's own `when`)
16//!
17//! Built without expr-lang's optional features: the operators, `??`, `?:`,
18//! and the string and collection builtins are there; `matches`, JSON and the
19//! date functions are not.
20
21use anyhow::{Context as _, Result, bail};
22use expr::{Context, Value};
23use indexmap::IndexMap;
24use std::collections::BTreeMap;
25
26/// Check a condition parses, without evaluating it. Run when `tak.toml` is
27/// loaded, so a typo fails before any benchmark runs.
28pub fn check(when: &str) -> Result<()> {
29    expr::compile(when)
30        .map(|_| ())
31        .map_err(|e| anyhow::anyhow!("{e}"))
32        .with_context(|| format!("invalid `when`: {when:?}"))
33}
34
35/// Evaluate a condition for `bench` (and `subject`, if deciding on one).
36pub fn eval(
37    when: &str,
38    env: &BTreeMap<String, String>,
39    bench: &str,
40    subject: Option<&str>,
41) -> Result<bool> {
42    let mut ctx = Context::default();
43    let map: IndexMap<String, Value> = env
44        .iter()
45        .map(|(k, v)| (k.clone(), Value::from(v.as_str())))
46        .collect();
47    ctx.insert("env", map);
48    ctx.insert("os", std::env::consts::OS);
49    ctx.insert("arch", std::env::consts::ARCH);
50    let ci = env.get("CI").is_some_and(|v| !v.is_empty() && v != "false");
51    ctx.insert("ci", ci);
52    ctx.insert("bench", bench);
53    ctx.insert("subject", subject.unwrap_or(""));
54    let value = expr::eval(when, &ctx)
55        .map_err(|e| anyhow::anyhow!("{e}"))
56        .with_context(|| format!("could not evaluate `when`: {when:?}"))?;
57    match value.as_bool() {
58        Some(b) => Ok(b),
59        // The value itself is not printed: a condition like `env.API_TOKEN`
60        // would put a credential into CI logs.
61        None => bail!(
62            "`when` must be true or false, but {when:?} returned a {}",
63            kind(&value)
64        ),
65    }
66}
67
68/// A value's type, for errors that must not show the value.
69fn kind(v: &Value) -> &'static str {
70    match v {
71        Value::String(_) => "string",
72        Value::Integer(_) => "integer",
73        Value::Float(_) => "number",
74        Value::Array(_) => "list",
75        Value::Map(_) | Value::KeyedMap(_) => "map",
76        Value::Nil => "nil",
77        _ => "non-boolean value",
78    }
79}
80
81#[cfg(test)]
82mod tests {
83    use super::*;
84
85    fn env(pairs: &[(&str, &str)]) -> BTreeMap<String, String> {
86        pairs
87            .iter()
88            .map(|(k, v)| (k.to_string(), v.to_string()))
89            .collect()
90    }
91
92    #[test]
93    fn conditions_see_env_platform_ci_and_names() {
94        let e = env(&[("VLT_BIN", "/bin/vlt"), ("CI", "true")]);
95        assert!(eval(r#"env.VLT_BIN != """#, &e, "b", None).unwrap());
96        assert!(!eval(r#"(env.MISSING ?? "") != """#, &e, "b", None).unwrap());
97        assert!(eval("ci", &e, "b", None).unwrap());
98        assert!(!eval("ci", &env(&[("CI", "false")]), "b", None).unwrap());
99        assert!(eval(&format!("os == {:?}", std::env::consts::OS), &e, "b", None).unwrap());
100        assert!(eval(r#"bench == "b" && subject == "vlt""#, &e, "b", Some("vlt")).unwrap());
101    }
102
103    #[test]
104    fn a_non_boolean_result_is_an_error() {
105        let err = eval(r#""yes""#, &env(&[]), "b", None).unwrap_err();
106        assert!(format!("{err:#}").contains("true or false"), "{err:#}");
107    }
108
109    /// A condition that evaluates to an environment value must not echo it:
110    /// the error goes to stderr, and from there into CI logs.
111    #[test]
112    fn a_non_boolean_error_does_not_leak_the_value() {
113        let e = env(&[("API_TOKEN", "sekrit-value")]);
114        let err = format!("{:#}", eval("env.API_TOKEN", &e, "b", None).unwrap_err());
115        assert!(!err.contains("sekrit-value"), "{err}");
116        assert!(err.contains("returned a string"), "{err}");
117    }
118
119    #[test]
120    fn a_syntax_error_is_caught_by_check() {
121        assert!(check("env.X ==").is_err());
122        assert!(check(r#"env.X == "y""#).is_ok());
123    }
124
125    /// `??` binds more loosely than `!=`, so the fallback needs parentheses;
126    /// this pins the form the docs recommend.
127    #[test]
128    fn a_missing_variable_fallback_needs_parentheses() {
129        let when = r#"(env.X ?? "") != """#;
130        assert!(eval(when, &env(&[("X", "/bin/x")]), "b", None).unwrap());
131        assert!(!eval(when, &env(&[]), "b", None).unwrap());
132        assert!(eval(r#"env.X ?? "" != """#, &env(&[("X", "/bin/x")]), "b", None).is_err());
133    }
134}