]> git.lizzy.rs Git - rust.git/blob - src/tools/jsondocck/src/main.rs
Rollup merge of #93613 - crlf0710:rename_to_async_iter, r=yaahc
[rust.git] / src / tools / jsondocck / src / main.rs
1 use jsonpath_lib::select;
2 use once_cell::sync::Lazy;
3 use regex::{Regex, RegexBuilder};
4 use serde_json::Value;
5 use std::borrow::Cow;
6 use std::{env, fmt, fs};
7
8 mod cache;
9 mod config;
10 mod error;
11
12 use cache::Cache;
13 use config::parse_config;
14 use error::CkError;
15
16 fn main() -> Result<(), String> {
17     let config = parse_config(env::args().collect());
18
19     let mut failed = Vec::new();
20     let mut cache = Cache::new(&config.doc_dir);
21     let commands = get_commands(&config.template)
22         .map_err(|_| format!("Jsondocck failed for {}", &config.template))?;
23
24     for command in commands {
25         if let Err(e) = check_command(command, &mut cache) {
26             failed.push(e);
27         }
28     }
29
30     if failed.is_empty() {
31         Ok(())
32     } else {
33         for i in failed {
34             eprintln!("{}", i);
35         }
36         Err(format!("Jsondocck failed for {}", &config.template))
37     }
38 }
39
40 #[derive(Debug)]
41 pub struct Command {
42     negated: bool,
43     kind: CommandKind,
44     args: Vec<String>,
45     lineno: usize,
46 }
47
48 #[derive(Debug)]
49 pub enum CommandKind {
50     Has,
51     Count,
52     Is,
53     Set,
54 }
55
56 impl CommandKind {
57     fn validate(&self, args: &[String], command_num: usize, lineno: usize) -> bool {
58         let count = match self {
59             CommandKind::Has => (1..=3).contains(&args.len()),
60             CommandKind::Count | CommandKind::Is => 3 == args.len(),
61             CommandKind::Set => 4 == args.len(),
62         };
63
64         if !count {
65             print_err(&format!("Incorrect number of arguments to `@{}`", self), lineno);
66             return false;
67         }
68
69         if args[0] == "-" && command_num == 0 {
70             print_err(&format!("Tried to use the previous path in the first command"), lineno);
71             return false;
72         }
73
74         if let CommandKind::Count = self {
75             if args[2].parse::<usize>().is_err() {
76                 print_err(&format!("Third argument to @count must be a valid usize"), lineno);
77                 return false;
78             }
79         }
80
81         true
82     }
83 }
84
85 impl fmt::Display for CommandKind {
86     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
87         let text = match self {
88             CommandKind::Has => "has",
89             CommandKind::Count => "count",
90             CommandKind::Is => "is",
91             CommandKind::Set => "set",
92         };
93         write!(f, "{}", text)
94     }
95 }
96
97 static LINE_PATTERN: Lazy<Regex> = Lazy::new(|| {
98     RegexBuilder::new(
99         r#"
100         \s(?P<invalid>!?)@(?P<negated>!?)
101         (?P<cmd>[A-Za-z]+(?:-[A-Za-z]+)*)
102         (?P<args>.*)$
103     "#,
104     )
105     .ignore_whitespace(true)
106     .unicode(true)
107     .build()
108     .unwrap()
109 });
110
111 fn print_err(msg: &str, lineno: usize) {
112     eprintln!("Invalid command: {} on line {}", msg, lineno)
113 }
114
115 /// Get a list of commands from a file. Does the work of ensuring the commands
116 /// are syntactically valid.
117 fn get_commands(template: &str) -> Result<Vec<Command>, ()> {
118     let mut commands = Vec::new();
119     let mut errors = false;
120     let file = fs::read_to_string(template).unwrap();
121
122     for (lineno, line) in file.split('\n').enumerate() {
123         let lineno = lineno + 1;
124
125         let cap = match LINE_PATTERN.captures(line) {
126             Some(c) => c,
127             None => continue,
128         };
129
130         let negated = cap.name("negated").unwrap().as_str() == "!";
131         let cmd = cap.name("cmd").unwrap().as_str();
132
133         let cmd = match cmd {
134             "has" => CommandKind::Has,
135             "count" => CommandKind::Count,
136             "is" => CommandKind::Is,
137             "set" => CommandKind::Set,
138             _ => {
139                 print_err(&format!("Unrecognized command name `@{}`", cmd), lineno);
140                 errors = true;
141                 continue;
142             }
143         };
144
145         if let Some(m) = cap.name("invalid") {
146             if m.as_str() == "!" {
147                 print_err(
148                     &format!(
149                         "`!@{0}{1}`, (help: try with `@!{1}`)",
150                         if negated { "!" } else { "" },
151                         cmd,
152                     ),
153                     lineno,
154                 );
155                 errors = true;
156                 continue;
157             }
158         }
159
160         let args = cap.name("args").map_or(Some(vec![]), |m| shlex::split(m.as_str()));
161
162         let args = match args {
163             Some(args) => args,
164             None => {
165                 print_err(
166                     &format!(
167                         "Invalid arguments to shlex::split: `{}`",
168                         cap.name("args").unwrap().as_str()
169                     ),
170                     lineno,
171                 );
172                 errors = true;
173                 continue;
174             }
175         };
176
177         if !cmd.validate(&args, commands.len(), lineno) {
178             errors = true;
179             continue;
180         }
181
182         commands.push(Command { negated, kind: cmd, args, lineno })
183     }
184
185     if !errors { Ok(commands) } else { Err(()) }
186 }
187
188 /// Performs the actual work of ensuring a command passes. Generally assumes the command
189 /// is syntactically valid.
190 fn check_command(command: Command, cache: &mut Cache) -> Result<(), CkError> {
191     // FIXME: Be more granular about why, (e.g. syntax error, count not equal)
192     let result = match command.kind {
193         CommandKind::Has => {
194             match command.args.len() {
195                 // @has <path> = file existence
196                 1 => cache.get_file(&command.args[0]).is_ok(),
197                 // @has <path> <jsonpath> = check path exists
198                 2 => {
199                     let val = cache.get_value(&command.args[0])?;
200                     let results = select(&val, &command.args[1]).unwrap();
201                     !results.is_empty()
202                 }
203                 // @has <path> <jsonpath> <value> = check *any* item matched by path equals value
204                 3 => {
205                     let val = cache.get_value(&command.args[0])?;
206                     let results = select(&val, &command.args[1]).unwrap();
207                     let pat = string_to_value(&command.args[2], cache);
208                     let has = results.contains(&pat.as_ref());
209                     // Give better error for when @has check fails
210                     if !command.negated && !has {
211                         return Err(CkError::FailedCheck(
212                             format!(
213                                 "{} matched to {:?} but didn't have {:?}",
214                                 &command.args[1],
215                                 results,
216                                 pat.as_ref()
217                             ),
218                             command,
219                         ));
220                     } else {
221                         has
222                     }
223                 }
224                 _ => unreachable!(),
225             }
226         }
227         CommandKind::Count => {
228             // @count <path> <jsonpath> <count> = Check that the jsonpath matches exactly [count] times
229             assert_eq!(command.args.len(), 3);
230             let expected: usize = command.args[2].parse().unwrap();
231
232             let val = cache.get_value(&command.args[0])?;
233             let results = select(&val, &command.args[1]).unwrap();
234             let eq = results.len() == expected;
235             if !command.negated && !eq {
236                 return Err(CkError::FailedCheck(
237                     format!(
238                         "`{}` matched to `{:?}` with length {}, but expected length {}",
239                         &command.args[1],
240                         results,
241                         results.len(),
242                         expected
243                     ),
244                     command,
245                 ));
246             } else {
247                 eq
248             }
249         }
250         CommandKind::Is => {
251             // @has <path> <jsonpath> <value> = check *exactly one* item matched by path, and it equals value
252             assert_eq!(command.args.len(), 3);
253             let val = cache.get_value(&command.args[0])?;
254             let results = select(&val, &command.args[1]).unwrap();
255             let pat = string_to_value(&command.args[2], cache);
256             let is = results.len() == 1 && results[0] == pat.as_ref();
257             if !command.negated && !is {
258                 return Err(CkError::FailedCheck(
259                     format!(
260                         "{} matched to {:?}, but expected {:?}",
261                         &command.args[1],
262                         results,
263                         pat.as_ref()
264                     ),
265                     command,
266                 ));
267             } else {
268                 is
269             }
270         }
271         CommandKind::Set => {
272             // @set <name> = <path> <jsonpath>
273             assert_eq!(command.args.len(), 4);
274             assert_eq!(command.args[1], "=", "Expected an `=`");
275             let val = cache.get_value(&command.args[2])?;
276             let results = select(&val, &command.args[3]).unwrap();
277             assert_eq!(
278                 results.len(),
279                 1,
280                 "Didn't get 1 result for `{}`: got {:?}",
281                 command.args[3],
282                 results
283             );
284             match results.len() {
285                 0 => false,
286                 1 => {
287                     let r = cache.variables.insert(command.args[0].clone(), results[0].clone());
288                     assert!(r.is_none(), "Name collision: {} is duplicated", command.args[0]);
289                     true
290                 }
291                 _ => {
292                     panic!(
293                         "Got multiple results in `@set` for `{}`: {:?}",
294                         &command.args[3], results
295                     );
296                 }
297             }
298         }
299     };
300
301     if result == command.negated {
302         if command.negated {
303             Err(CkError::FailedCheck(
304                 format!(
305                     "`@!{} {}` matched when it shouldn't",
306                     command.kind,
307                     command.args.join(" ")
308                 ),
309                 command,
310             ))
311         } else {
312             // FIXME: In the future, try 'peeling back' each step, and see at what level the match failed
313             Err(CkError::FailedCheck(
314                 format!(
315                     "`@{} {}` didn't match when it should",
316                     command.kind,
317                     command.args.join(" ")
318                 ),
319                 command,
320             ))
321         }
322     } else {
323         Ok(())
324     }
325 }
326
327 fn string_to_value<'a>(s: &str, cache: &'a Cache) -> Cow<'a, Value> {
328     if s.starts_with("$") {
329         Cow::Borrowed(&cache.variables.get(&s[1..]).unwrap_or_else(|| {
330             // FIXME(adotinthevoid): Show line number
331             panic!("No variable: `{}`. Current state: `{:?}`", &s[1..], cache.variables)
332         }))
333     } else {
334         Cow::Owned(serde_json::from_str(s).expect(&format!("Cannot convert `{}` to json", s)))
335     }
336 }