use std::fmt;
use serde_json::Value;
use super::eval;
use crate::{Error, Result};
#[derive(Clone)]
pub struct Expr {
source: String,
compiled: jmespath::Expression<'static>,
}
impl Expr {
pub fn compile(source: &str) -> Result<Expr> {
let compiled = jmespath::compile(source)
.map_err(|e| Error::Query(e.to_string().trim_end().to_string()))?;
Ok(Expr {
source: source.to_string(),
compiled,
})
}
pub fn source(&self) -> &str {
&self.source
}
pub fn eval(&self, value: &Value) -> Result<Value> {
eval::eval(self.compiled.as_ast(), value).map_err(|e| Error::Query(e.to_string()))
}
pub fn truthy(&self, value: &Value) -> bool {
eval::eval(self.compiled.as_ast(), value)
.map(|v| eval::truthy(&v))
.unwrap_or(false)
}
}
impl fmt::Debug for Expr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("Expr").field(&self.source).finish()
}
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::*;
#[test]
fn compiles_or_refuses_with_the_crate_message() {
let e = Expr::compile("type=='Decision'").unwrap();
assert_eq!(e.source(), "type=='Decision'");
assert!(format!("{e:?}").contains("type=='Decision'"));
let err = Expr::compile("nodes[?").unwrap_err();
assert!(matches!(err, Error::Query(_)));
assert!(err.to_string().starts_with("query: "), "{err}");
}
#[test]
fn eval_projects_and_reports_runtime_failures() {
let e = Expr::compile("nodes[?kind=='document'].id").unwrap();
let value = json!({"nodes": [
{"kind": "document", "id": "a"},
{"kind": "file"},
{"kind": "document", "id": "b"}
]});
assert_eq!(e.eval(&value).unwrap(), json!(["a", "b"]));
assert_eq!(
Expr::compile("nope").unwrap().eval(&value).unwrap(),
Value::Null
);
let bad = Expr::compile("contains(tags, 'core')").unwrap();
assert!(matches!(bad.eval(&json!({})), Err(Error::Query(_))));
}
#[test]
fn truthy_follows_jmespath_and_treats_failure_as_false() {
let doc = json!({"type": "Decision", "tags": ["core"], "title": "", "n": 0, "list": [], "map": {}});
let cases = [
("type=='Decision'", true),
("type=='Issue'", false),
("contains(tags, 'core')", true),
("title", false),
("n", true),
("list", false),
("map", false),
("missing", false),
("!missing", true),
("tags", true),
];
for (src, expected) in cases {
assert_eq!(Expr::compile(src).unwrap().truthy(&doc), expected, "{src}");
}
let no_tags = json!({"type": "Decision"});
assert!(
!Expr::compile("contains(tags, 'core')")
.unwrap()
.truthy(&no_tags)
);
assert!(Expr::compile("!resource").unwrap().truthy(&no_tags));
}
}