1use std::fmt;
6
7use serde_json::Value;
8
9use super::eval;
10use crate::{Error, Result};
11
12#[derive(Clone)]
15pub struct Expr {
16 source: String,
17 compiled: jmespath::Expression<'static>,
18}
19
20impl Expr {
21 pub fn compile(source: &str) -> Result<Expr> {
26 let compiled = jmespath::compile(source)
27 .map_err(|e| Error::Query(e.to_string().trim_end().to_string()))?;
28 Ok(Expr {
29 source: source.to_string(),
30 compiled,
31 })
32 }
33
34 pub fn source(&self) -> &str {
36 &self.source
37 }
38
39 pub fn eval(&self, value: &Value) -> Result<Value> {
48 eval::eval(self.compiled.as_ast(), value).map_err(|e| Error::Query(e.to_string()))
49 }
50
51 pub fn truthy(&self, value: &Value) -> bool {
59 eval::eval(self.compiled.as_ast(), value).is_ok_and(|v| eval::truthy(&v))
60 }
61}
62
63impl fmt::Debug for Expr {
64 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
65 f.debug_tuple("Expr").field(&self.source).finish()
66 }
67}
68
69#[cfg(test)]
70mod tests {
71 use serde_json::json;
72
73 use super::*;
74
75 #[test]
76 fn compiles_or_refuses_with_the_crate_message() {
77 let e = Expr::compile("type=='Decision'").unwrap();
78 assert_eq!(e.source(), "type=='Decision'");
79 assert!(format!("{e:?}").contains("type=='Decision'"));
80 let err = Expr::compile("nodes[?").unwrap_err();
81 assert!(matches!(err, Error::Query(_)));
82 assert!(err.to_string().starts_with("query: "), "{err}");
83 }
84
85 #[test]
86 fn eval_projects_and_reports_runtime_failures() {
87 let e = Expr::compile("nodes[?kind=='document'].id").unwrap();
88 let value = json!({"nodes": [
89 {"kind": "document", "id": "a"},
90 {"kind": "file"},
91 {"kind": "document", "id": "b"}
92 ]});
93 assert_eq!(e.eval(&value).unwrap(), json!(["a", "b"]));
94 assert_eq!(
95 Expr::compile("nope").unwrap().eval(&value).unwrap(),
96 Value::Null
97 );
98 let bad = Expr::compile("contains(tags, 'core')").unwrap();
99 assert!(matches!(bad.eval(&json!({})), Err(Error::Query(_))));
100 }
101
102 #[test]
105 fn truthy_follows_jmespath_and_treats_failure_as_false() {
106 let doc = json!({"type": "Decision", "tags": ["core"], "title": "", "n": 0, "list": [], "map": {}});
107 let cases = [
108 ("type=='Decision'", true),
109 ("type=='Issue'", false),
110 ("contains(tags, 'core')", true),
111 ("title", false),
112 ("n", true),
113 ("list", false),
114 ("map", false),
115 ("missing", false),
116 ("!missing", true),
117 ("tags", true),
118 ];
119 for (src, expected) in cases {
120 assert_eq!(Expr::compile(src).unwrap().truthy(&doc), expected, "{src}");
121 }
122 let no_tags = json!({"type": "Decision"});
125 assert!(
126 !Expr::compile("contains(tags, 'core')")
127 .unwrap()
128 .truthy(&no_tags)
129 );
130 assert!(Expr::compile("!resource").unwrap().truthy(&no_tags));
131 }
132}