Skip to main content

weirdnet_rules/
template.rs

1//! Templates: `{rule}`, `{date}`, `{time}`, `{now}` and `{FIELD}` from a lookup.
2use crate::compare::text;
3use serde_json::Value;
4
5/// Fill `{rule}` (the rule's name), `{date}` (`2026-11-01`), `{time}` (`030000`), `{now}`
6/// (`2026-11-01 03:00`) from `now`, and any other `{FIELD}` from `field`; unknown ones and
7/// ones with spaces stay as written. An unclosed `{` ends the template as written.
8pub fn expand<Tz>(t: &str, now: &chrono::DateTime<Tz>, rule: &str, field: impl Fn(&str) -> Option<Value>) -> String
9where
10    Tz: chrono::TimeZone,
11    Tz::Offset: std::fmt::Display,
12{
13    let mut out = String::new();
14    let mut rest = t;
15    while let Some(i) = rest.find('{') {
16        out.push_str(&rest[..i]);
17        let after = &rest[i + 1..];
18        let Some(j) = after.find('}') else {
19            out.push_str(&rest[i..]);
20            return out;
21        };
22        let key = &after[..j];
23        let v = match key {
24            "rule" => Some(rule.to_string()),
25            "date" => Some(now.format("%Y-%m-%d").to_string()),
26            "time" => Some(now.format("%H%M%S").to_string()),
27            "now" => Some(now.format("%Y-%m-%d %H:%M").to_string()),
28            k if !k.is_empty() && !k.contains(char::is_whitespace) => field(k).map(|v| text(&v)),
29            _ => None,
30        };
31        match v {
32            Some(v) => out.push_str(&v),
33            None => out.push_str(&rest[i..i + j + 2]),
34        }
35        rest = &after[j + 1..];
36    }
37    out.push_str(rest);
38    out
39}
40
41#[cfg(test)]
42mod tests {
43    use super::*;
44    use chrono::{FixedOffset, TimeZone};
45    use serde_json::json;
46
47    #[test]
48    fn fills_from_a_fake_clock_and_lookup() {
49        let now = FixedOffset::west_opt(5 * 3600).unwrap().with_ymd_and_hms(2026, 11, 1, 3, 4, 5).unwrap();
50        let f = |k: &str| match k {
51            "inserted" => Some(json!(401)),
52            "out" => Some(json!("/tmp/a.pdf")),
53            _ => None,
54        };
55        assert_eq!(expand("{rule}: {inserted} at {date} {time} ({now})", &now, "Nightly", f), "Nightly: 401 at 2026-11-01 030405 (2026-11-01 03:04)");
56        assert_eq!(expand("{out}{missing}{ spaced }{}{open", &now, "r", f), "/tmp/a.pdf{missing}{ spaced }{}{open");
57        assert_eq!(expand("no fields", &now, "r", f), "no fields");
58    }
59}