Skip to main content

docsrs_cli/agent_ops/
filter.rs

1//! Path addressing and the `--filter` predicate grammar.
2//!
3//! Both `--filter` and `--dedupe-by` address fields by dotted path and compare
4//! them as scalars, so resolution and comparison live together here, separate
5//! from the pipeline that applies them.
6
7use serde_json::Value;
8
9use crate::error::{AppError, AppResult, ErrorDetail};
10
11/// Comparison operator of a single `--filter` expression.
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub enum FilterOp {
14    /// `key=value` / `key==value` — exact string equality.
15    Eq,
16    /// `key!=value` — string inequality (a missing key never matches).
17    Ne,
18    /// `key~value` — substring containment.
19    Contains,
20}
21
22/// One parsed `--filter` expression.
23#[derive(Debug, Clone)]
24pub struct Filter {
25    /// Dotted path resolved against each element.
26    pub path: String,
27    /// Comparison operator.
28    pub op: FilterOp,
29    /// Right-hand literal, compared against the scalar rendering of the field.
30    pub value: String,
31}
32
33impl Filter {
34    /// Parse one `key=value` / `key!=value` / `key==value` / `key~value` expression.
35    ///
36    /// # Errors
37    ///
38    /// Returns [`crate::error::ErrorKind::InvalidInput`] (exit 65) when no operator is present or
39    /// the key side is empty. A malformed expression is fail-closed on purpose: a
40    /// silently empty result set hides a typo far longer than an error does.
41    pub fn parse(expr: &str) -> AppResult<Self> {
42        let bytes = expr.as_bytes();
43        for (idx, _) in expr.char_indices() {
44            let rest = &bytes[idx..];
45            let (op, width) = if rest.starts_with(b"!=") {
46                (FilterOp::Ne, 2)
47            } else if rest.starts_with(b"==") {
48                (FilterOp::Eq, 2)
49            } else if rest.starts_with(b"=") {
50                (FilterOp::Eq, 1)
51            } else if rest.starts_with(b"~") {
52                (FilterOp::Contains, 1)
53            } else {
54                continue;
55            };
56            let path = expr[..idx].trim();
57            if path.is_empty() {
58                return Err(invalid_filter(expr, "key side is empty"));
59            }
60            return Ok(Self {
61                path: path.to_string(),
62                op,
63                value: expr[idx + width..].to_string(),
64            });
65        }
66        Err(invalid_filter(
67            expr,
68            "expected key=value, key!=value or key~substring",
69        ))
70    }
71
72    /// Whether `element` satisfies this predicate.
73    pub(super) fn matches(&self, element: &Value, strip: &[&str]) -> bool {
74        let Some(found) = resolve_path(element, &self.path, strip) else {
75            // A missing field never matches — not even under `!=`.
76            return false;
77        };
78        let Some(actual) = scalar_text(found) else {
79            return false;
80        };
81        match self.op {
82            FilterOp::Eq => actual == self.value,
83            FilterOp::Ne => actual != self.value,
84            FilterOp::Contains => actual.contains(&self.value),
85        }
86    }
87}
88
89fn invalid_filter(expr: &str, why: &str) -> AppError {
90    AppError::of(ErrorDetail::InvalidFilterExpression {
91        expr: expr.to_string(),
92        reason: why.to_string(),
93    })
94}
95
96/// Resolve a dotted path against `root`.
97///
98/// A leading `data.` segment, and a leading segment naming the located result array,
99/// are tolerated so `data.hits.name`, `hits.name` and `name` all address the same
100/// field of an element.
101pub(super) fn resolve_path<'a>(root: &'a Value, path: &str, strip: &[&str]) -> Option<&'a Value> {
102    let mut segments: Vec<&str> = path.split('.').filter(|s| !s.is_empty()).collect();
103    if segments.first() == Some(&"data") && segments.len() > 1 {
104        segments.remove(0);
105    }
106    if segments.len() > 1 && segments.first().is_some_and(|s| strip.contains(s)) {
107        segments.remove(0);
108    }
109    let mut cur = root;
110    for seg in segments {
111        cur = cur.get(seg)?;
112    }
113    Some(cur)
114}
115
116/// Scalar rendering used by `--filter` and `--dedupe-by`. Containers and `null`
117/// yield `None` and therefore never match.
118pub(super) fn scalar_text(v: &Value) -> Option<String> {
119    match v {
120        Value::String(s) => Some(s.clone()),
121        Value::Number(n) => Some(n.to_string()),
122        Value::Bool(b) => Some(b.to_string()),
123        _ => None,
124    }
125}
126
127#[cfg(test)]
128mod tests {
129    use super::*;
130    use crate::error::ErrorKind;
131
132    #[test]
133    fn parses_every_operator_form() {
134        let eq = Filter::parse("name=serde").expect("valid");
135        assert_eq!(eq.op, FilterOp::Eq);
136        assert_eq!(eq.path, "name");
137        assert_eq!(eq.value, "serde");
138        assert_eq!(
139            Filter::parse("name==serde").expect("valid").op,
140            FilterOp::Eq
141        );
142        assert_eq!(
143            Filter::parse("name!=serde").expect("valid").op,
144            FilterOp::Ne
145        );
146        assert_eq!(
147            Filter::parse("name~serde").expect("valid").op,
148            FilterOp::Contains
149        );
150    }
151
152    #[test]
153    fn double_equals_is_not_split_as_single_equals() {
154        let f = Filter::parse("name==x").expect("valid");
155        assert_eq!(f.value, "x", "`==` consumes both bytes");
156    }
157
158    #[test]
159    fn malformed_expressions_are_invalid_input() {
160        for bad in ["nope", "=x", "  =x"] {
161            let e = Filter::parse(bad).expect_err("must reject");
162            assert_eq!(e.kind(), ErrorKind::InvalidInput, "input {bad:?}");
163            assert_eq!(e.kind().exit_code(), 65);
164        }
165    }
166
167    #[test]
168    fn empty_value_is_allowed() {
169        let f = Filter::parse("name=").expect("valid");
170        assert!(f.value.is_empty());
171    }
172
173    #[test]
174    fn scalar_text_covers_scalars_only() {
175        assert_eq!(scalar_text(&serde_json::json!("a")).as_deref(), Some("a"));
176        assert_eq!(scalar_text(&serde_json::json!(7)).as_deref(), Some("7"));
177        assert_eq!(
178            scalar_text(&serde_json::json!(true)).as_deref(),
179            Some("true")
180        );
181        assert!(scalar_text(&serde_json::json!(null)).is_none());
182        assert!(scalar_text(&serde_json::json!([1])).is_none());
183        assert!(scalar_text(&serde_json::json!({"a": 1})).is_none());
184    }
185
186    #[test]
187    fn resolve_path_strips_data_and_array_prefixes() {
188        let el = serde_json::json!({"name": "serde", "meta": {"total": 3}});
189        for path in ["name", "hits.name", "data.hits.name"] {
190            assert_eq!(
191                resolve_path(&el, path, &["hits"])
192                    .and_then(scalar_text)
193                    .as_deref(),
194                Some("serde"),
195                "path {path}"
196            );
197        }
198        assert_eq!(
199            resolve_path(&el, "meta.total", &["hits"]).and_then(scalar_text),
200            Some("3".to_string()),
201            "nested paths still resolve"
202        );
203        assert!(resolve_path(&el, "absent", &[]).is_none());
204    }
205
206    #[test]
207    fn missing_field_never_matches_any_operator() {
208        let el = serde_json::json!({"version": "1"});
209        for expr in ["name=x", "name!=x", "name~x"] {
210            let f = Filter::parse(expr).expect("valid");
211            assert!(!f.matches(&el, &[]), "expr {expr}");
212        }
213    }
214}