1use crate::error::{Result, RulesError};
3use crate::model::{Condition, Op};
4
5pub fn matches_kind(p: &str, kind: &str) -> bool {
7 let p = p.trim();
8 p == "*" || p == kind || p.strip_suffix(".*").is_some_and(|pre| kind.starts_with(&format!("{pre}.")) || kind == pre)
9}
10
11pub fn check_pattern(p: &str, kinds: &[&str], hint: &str) -> Result<String> {
14 let p = p.trim();
15 if p.is_empty() {
16 return Err(RulesError::invalid("--on", "is empty"));
17 }
18 if kinds.iter().any(|k| matches_kind(p, k)) {
19 Ok(p.to_string())
20 } else {
21 Err(RulesError::invalid("--on", format!("`{p}` matches no action kind{hint}")))
22 }
23}
24
25pub fn parse_on(v: &[String], kinds: &[&str], hint: &str) -> Result<Vec<String>> {
27 v.iter().flat_map(|s| s.split([',', ' '])).filter(|s| !s.trim().is_empty()).map(|p| check_pattern(p, kinds, hint)).collect()
28}
29
30pub fn split_list(s: &str) -> Vec<String> {
32 let mut out = vec![];
33 let mut cur = String::new();
34 let mut q: Option<char> = None;
35 for c in s.chars() {
36 match (q, c) {
37 (None, '"' | '\'') => {
38 q = Some(c);
39 cur.push(c)
40 }
41 (Some(o), c) if c == o => {
42 q = None;
43 cur.push(c)
44 }
45 (None, ';') => out.push(std::mem::take(&mut cur)),
46 _ => cur.push(c),
47 }
48 }
49 out.push(cur);
50 out.into_iter().map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect()
51}
52
53pub fn tokenize(s: &str) -> Result<Vec<(String, Option<String>)>> {
56 let mut out = vec![];
57 let mut it = s.chars().peekable();
58 loop {
59 while it.peek().is_some_and(|c| c.is_whitespace()) {
60 it.next();
61 }
62 if it.peek().is_none() {
63 break;
64 }
65 let mut w = String::new();
66 let mut key = None;
67 let mut quoted_any = false;
68 while let Some(&c) = it.peek() {
69 if c.is_whitespace() {
70 break;
71 }
72 it.next();
73 match c {
74 '"' | '\'' => {
75 quoted_any = true;
76 let mut closed = false;
77 for d in it.by_ref() {
78 if d == c {
79 closed = true;
80 break;
81 }
82 w.push(d);
83 }
84 if !closed {
85 return Err(RulesError::invalid("then", format!("unclosed {c} in `{s}`")));
86 }
87 }
88 '=' if key.is_none() && !quoted_any && !w.is_empty() && w.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-') => {
89 key = Some(std::mem::take(&mut w))
90 }
91 c => w.push(c),
92 }
93 }
94 out.push(match key {
95 Some(k) => (k, Some(w)),
96 None => (w, None),
97 });
98 }
99 Ok(out)
100}
101
102pub fn parse_condition(s: &str) -> Result<Condition> {
104 parse_condition_with(s, &[])
105}
106
107pub fn parse_condition_with(s: &str, call_prefixes: &[&str]) -> Result<Condition> {
110 let s = s.trim();
111 let end = if let Some(pre) = call_prefixes.iter().find(|p| s.starts_with(**p)) {
112 let open = s.find('(');
113 let from = match (open, s.find(')')) {
114 (Some(o), Some(c)) if o < s.find(char::is_whitespace).unwrap_or(s.len()) => c + 1,
115 _ => pre.len(),
116 };
117 from + s[from..].find(|c: char| !(c.is_ascii_alphanumeric() || "_.-:/".contains(c))).unwrap_or(s.len() - from)
118 } else {
119 s.find(|c: char| !(c.is_ascii_alphanumeric() || c == '_' || c == '.' || c == '-')).unwrap_or(s.len())
120 };
121 let field = &s[..end];
122 if field.is_empty() {
123 return Err(RulesError::invalid("--if", format!("`{s}`: start with a field, e.g. `inserted > 0`")));
124 }
125 let rest = s[end..].trim_start();
126 let Some(op) = Op::ALL.into_iter().find(|o| rest.starts_with(o.as_str())) else {
127 return Err(RulesError::invalid("--if", format!("`{s}`: expected an operator (= != ~ !~ > >= < <= ? !?)")));
128 };
129 let mut value = rest[op.as_str().len()..].trim().to_string();
130 if value.len() >= 2 && (value.starts_with('"') && value.ends_with('"') || value.starts_with('\'') && value.ends_with('\'')) {
131 value = value[1..value.len() - 1].to_string();
132 }
133 if op.unary() != value.is_empty() {
134 return Err(RulesError::invalid("--if", format!("`{s}`: {}", if op.unary() { "`?` and `!?` take no value" } else { "missing a value" })));
135 }
136 Ok(Condition { field: field.to_string(), op, value })
137}
138
139pub fn condition_text(c: &Condition) -> String {
141 if c.op.unary() { format!("{} {}", c.field, c.op.as_str()) } else { format!("{} {} {}", c.field, c.op.as_str(), quote(&c.value)) }
142}
143
144pub fn quote(s: &str) -> String {
146 if !s.is_empty() && !s.contains(|c: char| c.is_whitespace() || "\"';=".contains(c)) {
147 s.to_string()
148 } else if s.contains('"') {
149 format!("'{s}'")
150 } else {
151 format!("\"{s}\"")
152 }
153}
154
155#[cfg(test)]
156mod tests {
157 use super::*;
158
159 const KINDS: &[&str] = &["import", "journal.export", "report.section.add", "schedule"];
160
161 #[test]
162 fn patterns() {
163 assert!(matches_kind("journal.*", "journal.export") && matches_kind("*", "import") && !matches_kind("entry.*", "entryx"));
164 assert!(matches_kind("journal.*", "journal"));
165 assert!(check_pattern("nope", KINDS, "").is_err() && check_pattern("report.section.*", KINDS, "").is_ok());
166 assert_eq!(check_pattern("x", KINDS, " (see the list)").unwrap_err().to_string(), "invalid --on: `x` matches no action kind (see the list)");
167 assert_eq!(parse_on(&["import,journal.*".into(), "schedule".into()], KINDS, "").unwrap(), ["import", "journal.*", "schedule"]);
168 assert!(check_pattern(" ", KINDS, "").is_err());
169 }
170
171 #[test]
172 fn conditions_parse_print_and_round_trip() {
173 let c = parse_condition("inserted>=10").unwrap();
174 assert_eq!((c.field.as_str(), c.op, c.value.as_str()), ("inserted", Op::Ge, "10"));
175 assert_eq!(parse_condition("title ~ \"btc halving\"").unwrap().value, "btc halving");
176 assert_eq!(parse_condition("out ?").unwrap().op, Op::Exists);
177 assert!(parse_condition("out ? x").is_err() && parse_condition("= 3").is_err() && parse_condition("x 3").is_err());
178 for s in ["inserted > 0", "title ~ \"btc halving\"", "out ?", "name = 'say \"hi\"'", "a.b-c != x"] {
179 let c = parse_condition(s).unwrap();
180 assert_eq!(parse_condition(&condition_text(&c)).unwrap(), c, "{s}");
181 }
182 let c = parse_condition_with("svc:a/b(q=x y,n=2).count > 1", &["svc:"]).unwrap();
184 assert_eq!((c.field.as_str(), c.op), ("svc:a/b(q=x y,n=2).count", Op::Gt));
185 assert!(parse_condition("svc:a/b(q=x y).count > 1").is_err());
186 }
187
188 #[test]
189 fn lists_words_and_quotes() {
190 assert_eq!(split_list("a; b ;\"c;d\"; ;'e;f'"), ["a", "b", "\"c;d\"", "'e;f'"]);
191 let t = tokenize("entry \"two words\" title=T x='a b' \"k=v\"").unwrap();
192 assert_eq!(t[1], ("two words".to_string(), None));
193 assert_eq!(t[2], ("title".to_string(), Some("T".to_string())));
194 assert_eq!(t[3], ("x".to_string(), Some("a b".to_string())));
195 assert_eq!(t[4], ("k=v".to_string(), None), "a quoted = is not a key");
196 assert_eq!(tokenize("status \"open").unwrap_err().to_string(), "invalid then: unclosed \" in `status \"open`");
197 assert_eq!(quote("plain"), "plain");
198 assert_eq!(quote("two words"), "\"two words\"");
199 assert_eq!(quote("say \"hi\""), "'say \"hi\"'");
200 assert_eq!(quote(""), "\"\"");
201 }
202}