Debian Codegraph @

src/cli/examples.rs

raw
1 //! A framework to format and check examples.
2 //!
3 //! The help text for subcommands includes examples. That's great.
4 //! But, it is even better when they are tested. This module defines
5 //! data structures to describe the examples, mechanisms to format the
6 //! examples, and infrastructure to execute the examples.
7
8 use std::collections::BTreeMap;
9
10 use clap::builder::IntoResettable;
11 use clap::builder::Resettable;
12
13 /// A command that is executed by the integration test, but not shown
14 /// in the manual pages.
15 pub struct Setup<'a> {
16 pub command: &'a [ &'a str ],
17 }
18
19 /// Builds up setup actions in an extensible way.
20 pub struct SetupBuilder<'a> {
21 setup: Setup<'a>,
22 }
23
24 impl<'a> SetupBuilder<'a> {
25 /// Returns a new setup builder.
26 const fn new() -> Self {
27 SetupBuilder {
28 setup: Setup {
29 command: &[],
30 }
31 }
32 }
33
34 /// Provides the command as slice.
35 ///
36 /// It'd be nice to provide a per-argument interface, but that
37 /// requires some ingenuity for it to stay const.
38 pub const fn command(mut self, command: &'a [&'a str]) -> Self {
39 self.setup.command = command;
40 self
41 }
42
43 /// Finishes building the setup action.
44 pub const fn build(self) -> Action<'a> {
45 assert!(! self.setup.command.is_empty());
46 Action::Setup(self.setup)
47 }
48 }
49
50 /// A command that is executed by the integration test, and shown in
51 /// the manual pages.
52 pub struct Example<'a> {
53 // A human-readable comment.
54 pub comment: &'a str,
55 pub command: &'a [ &'a str ],
56 pub hide: &'a [ &'a str ],
57 }
58
59 /// Builds up example actions in an extensible way.
60 pub struct ExampleBuilder<'a> {
61 example: Example<'a>,
62 }
63
64 impl<'a> ExampleBuilder<'a> {
65 /// Returns a new example builder.
66 const fn new() -> Self {
67 ExampleBuilder {
68 example: Example {
69 comment: "",
70 command: &[],
71 hide: &[],
72 },
73 }
74 }
75
76 /// Provides the comment.
77 ///
78 /// It'd be nice to provide a per-argument interface, but that
79 /// requires some ingenuity for it to stay const.
80 pub const fn comment(mut self, comment: &'a str) -> Self {
81 self.example.comment = comment;
82 self
83 }
84
85 /// Provides the command as slice.
86 ///
87 /// It'd be nice to provide a per-argument interface, but that
88 /// requires some ingenuity for it to stay const.
89 pub const fn command(mut self, command: &'a [&'a str]) -> Self {
90 self.example.command = command;
91 self
92 }
93
94 /// Hides the parameters in the output
95 ///
96 /// Skip these parameters when generating human readable output
97 #[allow(unused)]
98 pub const fn hide(mut self, hide: &'a [&'a str]) -> Self {
99 self.example.hide = hide;
100 self
101 }
102
103 /// Finishes building the example action.
104 ///
105 /// The example will be executed by the test.
106 pub const fn build(self) -> Action<'a> {
107 assert!(! self.example.comment.is_empty());
108 assert!(! self.example.command.is_empty());
109 Action::Example(self.example)
110 }
111
112 /// Finishes building the example action, marking it for syntax
113 /// checking only.
114 ///
115 /// The example will not be executed by the test, but the syntax
116 /// will be checked using our command line parser.
117 pub const fn syntax_check(self) -> Action<'a> {
118 assert!(! self.example.comment.is_empty());
119 assert!(! self.example.command.is_empty());
120 Action::SyntaxCheck(self.example)
121 }
122 }
123
124 /// An action to execute.
125 #[allow(dead_code)]
126 pub enum Action<'a> {
127 /// A command that is executed by the integration test, but not
128 /// shown in the manual pages.
129 Setup(Setup<'a>),
130
131 /// A command that is syntax check (but not run) by the
132 /// integration test, and shown in the manual pages.
133 SyntaxCheck(Example<'a>),
134
135 /// A command that is executed by the integration test, and shown
136 /// in the manual pages.
137 Example(Example<'a>),
138 }
139
140 impl<'a> Action<'a> {
141 /// Creates a setup action.
142 pub const fn setup() -> SetupBuilder<'a> {
143 SetupBuilder::new()
144 }
145
146 /// Creates an example action.
147 pub const fn example() -> ExampleBuilder<'a> {
148 ExampleBuilder::new()
149 }
150
151 /// Return the action's command, if any.
152 #[allow(dead_code)]
153 pub fn command(&self) -> Option<&'a [ &'a str ]> {
154 match self {
155 Action::Setup(Setup { command, .. }) => Some(command),
156 Action::SyntaxCheck(Example { command, .. }) => Some(command),
157 Action::Example(Example { command, .. }) => Some(command),
158 }
159 }
160 }
161
162 /// A sequence of actions to execute.
163 pub struct Actions<'a> {
164 pub actions: &'a [Action<'a>],
165 }
166
167 impl<'a> IntoResettable<clap::builder::StyledStr> for Actions<'a> {
168 fn into_resettable(self) -> Resettable<clap::builder::StyledStr> {
169 // Default width when we aren't connected to a terminal.
170 let default_width = 72;
171
172 // We prefix lines with either `# `, `$ `, or ` `.
173 const PREFIX_WIDTH: usize = 2;
174
175 let terminal_size = terminal_size::terminal_size();
176 let width = if let Some((width, _height)) = terminal_size {
177 let width = width.0 as usize;
178
179 if width < 40 {
180 // If the terminal is too narrow, then give up and use
181 // the default.
182 default_width
183 } else {
184 std::cmp::max(40, width - PREFIX_WIDTH)
185 }
186 } else {
187 default_width
188 };
189
190 let mut lines = vec![ "Examples:".to_string() ];
191
192 lines.extend(self.actions
193 .iter()
194 .filter_map(|action| {
195 let example = match action {
196 Action::SyntaxCheck(example) => example,
197 Action::Example(example) => example,
198
199 // Don't show it.
200 Action::Setup(_) => return None,
201 };
202
203 let comment = textwrap::indent(
204 &textwrap::wrap(example.comment, width).join("\n"),
205 "# ");
206
207 // Our manpage generate complains if an
208 // example is too long:
209 //
210 // warning: Command in example exceeds 64 chars:
211 //
212 // or
213 //
214 // warning: Continuation in example exceeds 57 chars:
215 let command = wrap_command(&example.command,
216 &example.hide,
217 "", width.min(64),
218 " ", width.min(57));
219
220 Some(format!("{}\n{}", comment, command))
221 }));
222
223 let text = lines.join("\n\n").into();
224
225 Resettable::Value(text)
226 }
227 }
228
229 /// Wraps the given command to width, adding continuation backslashes.
230 ///
231 /// The first line is prefixed with `indent` and wrapped `to_width`,
232 /// any continuations are prefixed with `continuation_indent` and
233 /// wrapped to `continuation_width`.
234 pub fn wrap_command<S: AsRef<str>>(command: &[S],
235 hide: &[S],
236 indent: &str,
237 to_width: usize,
238 continuation_indent: &str,
239 continuation_width: usize)
240 -> String
241 {
242 let prompt = platform! {
243 unix => { "$" },
244 windows => { ">" },
245 };
246
247 let mut hide
248 = BTreeMap::from_iter(hide.iter().map(|s| (s.as_ref(), false)));
249
250 let result = command
251 .iter()
252 .filter(|&item| {
253 // Remove all of the items in command which are also in
254 // hide.
255 if let Some(used) = hide.get_mut(item.as_ref()) {
256 *used = true;
257 // Don't show it.
258 false
259 } else {
260 // Show it.
261 true
262 }
263 })
264 .fold(vec![format!("{}{}", indent, prompt)], |mut s, arg| {
265 let first = s.len() == 1;
266
267 let arg = arg.as_ref();
268 if arg == "|" {
269 let last = s.last_mut().expect("have one");
270 *last = format!("{} \\", last);
271 s.push(format!(" {}", arg));
272 return s;
273 }
274
275 // Quote the argument, if necessary.
276 let quote = |arg: &str| -> String {
277 if arg.contains(&[
278 '\"',
279 ]) {
280 format!("'{}'", arg)
281 } else if arg.chars().any(char::is_whitespace)
282 || arg.contains(&[
283 '`', '#', '$', '&', '*', '(', ')',
284 '\\', '|', '[', ']', '{', '}',
285 ';', '\'', '<', '>', '?', '!',
286 ])
287 {
288 format!("\"{}\"", arg)
289 } else {
290 arg.to_string()
291 }
292 };
293
294 // If we have --foo=bar, then only but bar in quotes.
295 let mut quoted = None;
296 if arg.starts_with("--") {
297 if let Some(i) = arg.find('=') {
298 if arg[0..i].chars().all(|c| {
299 c.is_alphanumeric() || c == '-'
300 })
301 {
302 quoted = Some(format!("{}={}",
303 &arg[..i],
304 quote(&arg[i + 1..])));
305 }
306 }
307 }
308
309 let arg = if let Some(quoted) = quoted {
310 quoted
311 } else {
312 quote(arg)
313 };
314
315 let last = s.last_mut().expect("have one");
316
317 let last_chars = last.chars().count();
318 let arg_chars = arg.chars().count();
319
320 let max_width = if first { to_width } else { continuation_width };
321 if last_chars + 1 + arg_chars <= max_width {
322 *last = format!("{} {}", last, arg);
323 } else {
324 *last = format!("{} \\", last);
325 s.push(format!("{}{}", continuation_indent, arg));
326 }
327
328 s
329 })
330 .join("\n");
331
332 #[cfg(debug_assertions)]
333 for (arg, used) in hide.into_iter() {
334 if ! used {
335 panic!("Example `{}` includes an argument to hide (`{}`), but the \
336 argument wasn't used by the example!",
337 command.iter()
338 .map(|arg| arg.as_ref().to_string())
339 .collect::<Vec<String>>()
340 .join(" "),
341 arg);
342 }
343 }
344
345 result
346 }
347
348 macro_rules! test_examples {
349 ($ident:ident, $actions:expr) => {
350 #[test]
351 fn $ident() {
352 use std::path::PathBuf;
353
354 use tempfile::TempDir;
355 use assert_cmd::Command;
356
357
358 let fixtures = PathBuf::from(concat!(
359 env!("CARGO_MANIFEST_DIR"),
360 "/tests/data/examples"));
361
362 let tmp_dir = TempDir::new().unwrap();
363
364 let options = fs_extra::dir::CopyOptions::new()
365 .content_only(true);
366 fs_extra::dir::copy(&fixtures, &tmp_dir, &options)
367 .expect(&format!("Copying {:?} to {:?}",
368 fixtures, &tmp_dir));
369
370 // Create an empty policy configuration file. We use this
371 // instead of the system-wide policy configuration file,
372 // which might be more strict than what our test vectors
373 // expect.
374 let policy = tmp_dir.path().join("empty-policy.toml");
375 std::fs::write(&policy, "").unwrap();
376
377 let home = tmp_dir.path().join("home");
378 let cert_store = tmp_dir.path().join("cert-store");
379 let key_store = tmp_dir.path().join("key-store");
380
381 eprintln!("Testing example from {}:{}", file!(), line!());
382
383 for (i, action) in $actions.actions.into_iter().enumerate() {
384 let command = if let Some(command) = action.command() {
385 command
386 } else {
387 continue;
388 };
389
390 if let Action::SyntaxCheck(_) = &action {
391 // Just syntax check it.
392 eprintln!("Syntax checking: {:?}", command);
393
394 use clap::Parser;
395 if let Err(err) = $crate::cli::SqCommand::try_parse_from(command.iter()) {
396 eprintln!("example:{}:{}: checking example #{}: {}",
397 file!(), line!(), i + 1, err);
398 panic!("syntax checking example failed");
399 }
400
401 continue;
402 }
403
404 // Handle pipelines by tracking intermediate results.
405 let mut intermediate = None;
406 for command in command.split(|p| *p == "|") {
407 eprintln!("Executing: {:?}", command);
408
409 let mut cmd = Command::cargo_bin(command[0]).unwrap();
410 cmd.current_dir(&tmp_dir)
411 .env("RUST_BACKTRACE", "1")
412 .env("RUST_LOG", "trace")
413 .env("SEQUOIA_CRYPTO_POLICY", &policy)
414 .env("SEQUOIA_HOME", &home)
415 .env("SEQUOIA_CERT_STORE", &cert_store)
416 .env("SEQUOIA_KEY_STORE", &key_store)
417 .arg("--batch")
418 .args(&command[1..]);
419
420 if let Some(prev) = intermediate {
421 cmd.write_stdin(prev);
422 }
423
424 let res = cmd.assert();
425 intermediate = Some(res.get_output().stdout.clone());
426 if let Err(err) = res.try_success() {
427 eprintln!("example:{}:{}: executing example #{}: {}",
428 file!(), line!(), i + 1, err);
429 panic!("executing example failed");
430 }
431 }
432 }
433 }
434 };
435 }