silicon-extend-cli 2.0.0

The extend command: find and use the devices a Silicon has access to
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
//! Reading the command line: the global flags, and each command's own flags and arguments.
//!
//! Every Extend command (not the device commands, whose arguments are the device's) says which
//! flags it takes in [`SPECS`]; anything else is refused with the valid choices. `help.rs` must
//! document every flag listed here (a test checks it).

use extend_protocol::{COMMAND_TIMEOUT_MAX_MS, COMMAND_TIMEOUT_MIN_MS};

use crate::error::{CliError, R};

#[derive(Debug, Default, Clone)]
pub struct Globals {
    pub json: bool,
    pub test: Option<String>,
    pub session: Option<String>,
    pub team: Option<String>,
    pub timeout: Option<u64>,
    pub help: bool,
    pub version: bool,
    pub verbose: bool,
}

/// The global flags, for messages.
pub const GLOBAL_FLAG_NAMES: &[&str] = &[
    "--json",
    "--test <test_id>",
    "--session <session_id>",
    "--team <handle>",
    "--timeout <ms>",
    "-h/--help",
    "-V/--version",
    "-v/--verbose",
];

/// Device commands whose arguments are a command line for the device itself (`adb shell df -h`).
/// Extend reads its own flags only between the command name and the device's first argument; from
/// that argument on, every token is sent exactly as typed, so `-h`, `-v`, `--json` and `--out`
/// reach the device. A `--` directly after the command name ends Extend's flags and is not sent.
pub const VERBATIM_COMMANDS: &[&str] = &["adb"];

/// Extend's own flags for device commands that make files, and whether each takes a value.
const FILE_FLAGS: &[(&str, bool)] = &[("--ttl", true), ("--keep", false), ("--out", true)];

fn file_flag_takes_value(token: &str) -> Option<bool> {
    FILE_FLAGS.iter().find(|(f, _)| *f == token).map(|(_, v)| *v)
}

pub fn missing_value(name: &str) -> CliError {
    match name {
        "--ttl" => CliError::usage(
            "--ttl needs a duration, like 7d",
            "Give it a duration from 1m to 30d: --ttl 90m, --ttl 12h, --ttl 7d.",
        ),
        "--out" => CliError::usage(
            "--out needs a local path",
            "Give the file or directory to save to: --out ./shot.png, or --out ./downloads/.",
        ),
        "--test" => CliError::usage(
            "--test needs a test id",
            "Give the Honeycomb environment id: extend --test 9b3e0c1a-2f4d-4e6b-8a7c-1d2e3f4a5b6c <command>.",
        ),
        "--session" => CliError::usage(
            "--session needs a session id",
            "Give the session id `extend session new` printed: --session a3f.",
        ),
        "--team" => CliError::usage(
            "--team needs a team handle",
            "Give one of your teams (see `extend team ls`): --team acme.",
        ),
        "--timeout" => CliError::usage(
            "--timeout needs a number of milliseconds",
            "Give 1000–300000: --timeout 60000.",
        ),
        _ => CliError::usage(
            format!("{name} needs a value"),
            format!("Put the value right after it: {name} <value>. `extend <command> --help` shows what it takes."),
        ),
    }
}

/// One Extend command's own flags: the name, and whether it takes a value.
pub struct Spec {
    pub path: &'static str,
    pub flags: &'static [(&'static str, bool)],
}

/// Every Extend command and the flags it takes (besides the global flags). Deprecated flags stay
/// accepted so 1.0 scripts keep running: `device ls --team-visible` and `device pair --visibility`
/// (a device is only visible to the Carbons who paired it from 1.1).
pub const SPECS: &[Spec] = &[
    Spec {
        path: "login",
        flags: &[],
    },
    Spec {
        path: "login status",
        flags: &[],
    },
    Spec {
        path: "logout",
        flags: &[],
    },
    Spec {
        path: "iam",
        flags: &[],
    },
    Spec {
        path: "team ls",
        flags: &[],
    },
    Spec {
        path: "team silicons",
        flags: &[("--all-teams", false)],
    },
    Spec {
        path: "team use",
        flags: &[],
    },
    Spec {
        path: "config ls",
        flags: &[],
    },
    Spec {
        path: "config get",
        flags: &[],
    },
    Spec {
        path: "config set",
        flags: &[],
    },
    Spec {
        path: "config unset",
        flags: &[],
    },
    Spec {
        path: "config home",
        flags: &[("--use-existing", false)],
    },
    Spec {
        path: "config test add",
        flags: &[],
    },
    Spec {
        path: "config test ls",
        flags: &[],
    },
    Spec {
        path: "config test rm",
        flags: &[],
    },
    Spec {
        path: "device ls",
        flags: &[
            ("--online", false),
            ("--os", true),
            ("--team-visible", false),
            ("--removed", false),
        ],
    },
    Spec {
        path: "device show",
        flags: &[],
    },
    Spec {
        path: "device pair",
        flags: &[
            ("--name", true),
            ("--visibility", true),
            ("--ttl-days", true),
            ("--access", true),
        ],
    },
    Spec {
        path: "device attach",
        flags: &[("--os", true), ("--name", true), ("--address", true)],
    },
    Spec {
        path: "device setup",
        flags: &[("--watch", false), ("--retry", false), ("--step", true)],
    },
    Spec {
        path: "device setup-code",
        flags: &[],
    },
    Spec {
        path: "device rename",
        flags: &[],
    },
    Spec {
        path: "device banner",
        flags: &[],
    },
    Spec {
        path: "device visibility",
        flags: &[],
    },
    Spec {
        path: "device ttl",
        flags: &[],
    },
    Spec {
        path: "device stop",
        flags: &[],
    },
    Spec {
        path: "device rm",
        flags: &[("--yes", false)],
    },
    Spec {
        path: "device access",
        flags: &[],
    },
    Spec {
        path: "device activity",
        flags: &[
            ("--silicon", true),
            ("--since", true),
            ("--until", true),
            ("--limit", true),
        ],
    },
    Spec {
        path: "device requests",
        flags: &[],
    },
    Spec {
        path: "device wake",
        flags: &[("--reason", true), ("--cancel", false)],
    },
    Spec {
        path: "device wake-requests",
        flags: &[
            ("--open", false),
            ("--wake-id", true),
            ("--silicon", true),
            ("--only-team", true),
        ],
    },
    Spec {
        path: "session new",
        flags: &[("--connect", false)],
    },
    Spec {
        path: "session connect",
        flags: &[],
    },
    Spec {
        path: "session disconnect",
        flags: &[],
    },
    Spec {
        path: "session status",
        flags: &[],
    },
    Spec {
        path: "session ls",
        flags: &[("--device", true), ("--state", true)],
    },
    Spec {
        path: "session end",
        flags: &[],
    },
    Spec {
        path: "takeover",
        flags: &[("--reason", true)],
    },
    Spec {
        path: "request send",
        flags: &[("--reason", true)],
    },
    Spec {
        path: "request ls",
        flags: &[("--sent", false), ("--received", false), ("--device", true)],
    },
    Spec {
        path: "ting status",
        flags: &[("--all-teams", false)],
    },
    Spec {
        path: "ting on",
        flags: &[("--all-teams", false)],
    },
    Spec {
        path: "file ls",
        flags: &[("--device", true), ("--kind", true)],
    },
    Spec {
        path: "file show",
        flags: &[],
    },
    Spec {
        path: "file get",
        flags: &[("--out", true)],
    },
    Spec {
        path: "file keep",
        flags: &[],
    },
    Spec {
        path: "report",
        flags: &[("--pr", true)],
    },
    Spec {
        path: "env",
        flags: &[],
    },
    Spec {
        path: "version",
        flags: &[],
    },
    Spec {
        path: "docs",
        flags: &[],
    },
    Spec {
        path: "help",
        flags: &[],
    },
];

pub fn spec(path: &str) -> &'static Spec {
    SPECS
        .iter()
        .find(|s| s.path == path)
        .unwrap_or_else(|| panic!("no flag spec for `extend {path}`"))
}

/// Whether `token` (or its `--flag=` part) takes a value in any Extend command.
fn extend_value_flag(token: &str) -> bool {
    SPECS
        .iter()
        .flat_map(|s| s.flags.iter())
        .any(|(f, takes)| *takes && *f == token)
}

fn is_extend_command(word: &str) -> bool {
    SPECS
        .iter()
        .any(|s| s.path == word || s.path.split(' ').next() == Some(word))
}

fn parse_timeout(v: &str) -> R<u64> {
    let ms: u64 = v.parse().map_err(|_| {
        CliError::usage(
            format!("--timeout takes milliseconds, got {v:?}"),
            "Give a whole number of milliseconds, 1000–300000: --timeout 60000.",
        )
    })?;
    if !(COMMAND_TIMEOUT_MIN_MS..=COMMAND_TIMEOUT_MAX_MS).contains(&ms) {
        return Err(CliError::usage(
            format!("--timeout {ms} is outside 1000–300000 milliseconds"),
            "Give 1000 (1 second) to 300000 (5 minutes); the default is 30000.",
        ));
    }
    Ok(ms)
}

/// A refused command line, with the globals read before the problem.
pub type GlobalsError = Box<(Globals, CliError)>;

/// Takes the global flags out of argv. They may come anywhere before a `--`, except inside a
/// verbatim command's own arguments (see [`VERBATIM_COMMANDS`]) and in the value of an Extend
/// command's flag (`extend request send 7c1e09ab --reason -h` sends the reason `-h`).
///
/// On an error, the globals read so far come back too, so `--test` can still be reported.
pub fn parse_globals(argv: Vec<String>) -> Result<(Globals, Vec<String>), GlobalsError> {
    let mut g = Globals::default();
    let mut rest: Vec<String> = Vec::new();
    let mut it = argv.into_iter();
    let mut passthrough = false;
    // Between a verbatim command's name and its first argument, where only Extend's flags go.
    let mut leading = false;
    // The first word is an Extend command (not a device command), whose flag values are taken
    // as they are.
    let mut extend_command = false;
    macro_rules! value {
        ($name:expr) => {
            match it.next() {
                Some(v) => v,
                None => return Err(Box::new((g, missing_value($name)))),
            }
        };
    }
    while let Some(a) = it.next() {
        if passthrough {
            rest.push(a);
            continue;
        }
        let flag_name = a.split_once('=').map_or(a.as_str(), |(k, _)| k);
        match a.as_str() {
            "--" => {
                passthrough = true;
                rest.push(a);
            }
            _ if extend_command && a.starts_with("--") && !a.contains('=') && extend_value_flag(flag_name) => {
                let v = it.next();
                rest.push(a);
                rest.extend(v);
            }
            "--json" => g.json = true,
            "-h" | "--help" => g.help = true,
            "-V" | "--version" => g.version = true,
            "-v" | "--verbose" => g.verbose = true,
            "--test" => g.test = Some(value!("--test")),
            "--session" => g.session = Some(value!("--session")),
            "--team" => g.team = Some(value!("--team")),
            "--timeout" => {
                let v = value!("--timeout");
                match parse_timeout(&v) {
                    Ok(ms) => g.timeout = Some(ms),
                    Err(e) => return Err(Box::new((g, e))),
                }
            }
            _ if a.starts_with("--test=") => g.test = Some(a["--test=".len()..].to_owned()),
            _ if a.starts_with("--session=") => g.session = Some(a["--session=".len()..].to_owned()),
            _ if a.starts_with("--team=") => g.team = Some(a["--team=".len()..].to_owned()),
            _ if a.starts_with("--timeout=") => match parse_timeout(&a["--timeout=".len()..]) {
                Ok(ms) => g.timeout = Some(ms),
                Err(e) => return Err(Box::new((g, e))),
            },
            // `--ttl`, `--keep` and `--out` stay in place for the device command, with their
            // values, so a value is never mistaken for the device's first argument.
            _ if leading && file_flag_takes_value(&a).is_some() => {
                let v = if file_flag_takes_value(&a) == Some(true) {
                    Some(value!(&a))
                } else {
                    None
                };
                rest.push(a);
                rest.extend(v);
            }
            _ => {
                if leading {
                    // The device's command line starts here; nothing after this is Extend's.
                    passthrough = true;
                } else if rest.is_empty() && VERBATIM_COMMANDS.contains(&a.as_str()) {
                    leading = true;
                } else if rest.is_empty() && is_extend_command(&a) {
                    extend_command = true;
                }
                rest.push(a);
            }
        }
    }
    Ok((g, rest))
}

/// The `--test` value in a command line the parser refused, so the test environment can still be
/// named on stderr.
pub fn find_test_id(argv: &[String]) -> Option<String> {
    let mut it = argv.iter();
    while let Some(a) = it.next() {
        if a == "--" {
            return None;
        }
        if a == "--test" {
            return it.next().cloned();
        }
        if let Some(v) = a.strip_prefix("--test=") {
            return Some(v.to_owned());
        }
    }
    None
}

/// An Extend command's arguments: positionals, and the flags its [`Spec`] allows.
#[derive(Debug)]
pub struct Args {
    pub pos: Vec<String>,
    pub flags: Vec<(String, Option<String>)>,
    path: &'static str,
}

/// Plain `x`, `-`, and negative numbers are positional; `-x` and `--x` are flags.
fn looks_like_flag(a: &str) -> bool {
    a.len() > 1 && a.starts_with('-') && !a[1..].starts_with(|c: char| c.is_ascii_digit() || c == '.')
}

impl Args {
    /// Reads `argv` for `extend <path>`, refusing flags the command doesn't take.
    pub fn parse(argv: &[String], path: &str) -> R<Self> {
        let spec = spec(path);
        let mut pos = Vec::new();
        let mut flags = Vec::new();
        let mut i = 0;
        while i < argv.len() {
            let a = &argv[i];
            if a == "--" {
                // Everything after `--` is positional, even if it looks like a flag.
                pos.extend(argv[i + 1..].iter().cloned());
                break;
            }
            if !looks_like_flag(a) {
                pos.push(a.clone());
                i += 1;
                continue;
            }
            let (name, inline) = match a.split_once('=').filter(|_| a.starts_with("--")) {
                Some((k, v)) => (k.to_owned(), Some(v.to_owned())),
                None => (a.clone(), None),
            };
            let Some((_, takes)) = spec.flags.iter().find(|(f, _)| *f == name) else {
                return Err(unknown_flag(spec, &name));
            };
            match (takes, inline) {
                (true, Some(v)) => flags.push((name, Some(v))),
                (true, None) => {
                    let Some(v) = argv.get(i + 1) else {
                        return Err(missing_value(&name).hint(format!(
                            "Put the value right after it. Usage: {}",
                            crate::help::usage_of(spec.path)
                        )));
                    };
                    flags.push((name, Some(v.clone())));
                    i += 1;
                }
                (false, Some(v)) => {
                    return Err(CliError::usage(
                        format!("{name} takes no value, but got {name}={v}"),
                        format!("Write {name} on its own. Usage: {}", crate::help::usage_of(spec.path)),
                    ));
                }
                (false, None) => flags.push((name, None)),
            }
            i += 1;
        }
        Ok(Self {
            pos,
            flags,
            path: spec.path,
        })
    }

    pub fn flag(&self, name: &str) -> bool {
        self.flags.iter().any(|(k, _)| k == name)
    }
    pub fn value(&self, name: &str) -> Option<String> {
        self.flags
            .iter()
            .rev()
            .find(|(k, _)| k == name)
            .and_then(|(_, v)| v.clone())
    }
    pub fn values(&self, name: &str) -> Vec<String> {
        self.flags
            .iter()
            .filter(|(k, _)| k == name)
            .filter_map(|(_, v)| v.clone())
            .collect()
    }
    /// The `i`th positional, or a usage error naming it.
    pub fn req(&self, i: usize, what: &str) -> R<String> {
        self.pos.get(i).cloned().ok_or_else(|| {
            CliError::usage(
                format!("`extend {}` is missing the {what}", self.path),
                format!("Usage: {}", crate::help::usage_of(self.path)),
            )
        })
    }
    /// Refuses positionals past the first `n`.
    pub fn at_most(&self, n: usize) -> R<()> {
        if self.pos.len() <= n {
            return Ok(());
        }
        let extra = &self.pos[n..];
        Err(CliError::usage(
            format!(
                "`extend {}` takes {} argument{}, and got {} more: {}",
                self.path,
                if n == 0 { "no".to_owned() } else { n.to_string() },
                if n == 1 { "" } else { "s" },
                extra.len(),
                extra.iter().map(|a| format!("{a:?}")).collect::<Vec<_>>().join(" ")
            ),
            format!(
                "Usage: {}. A value with spaces goes in quotes: \"like this\".",
                crate::help::usage_of(self.path)
            ),
        ))
    }
}

fn unknown_flag(spec: &Spec, name: &str) -> CliError {
    let known: Vec<String> = spec
        .flags
        .iter()
        .map(|(f, v)| if *v { format!("{f} <value>") } else { (*f).to_owned() })
        .collect();
    let near = spec
        .flags
        .iter()
        .map(|(f, _)| *f)
        .find(|f| similar(f, name))
        .map(|f| format!("Did you mean {f}? "))
        .unwrap_or_default();
    let choices = if known.is_empty() {
        format!("`extend {}` takes no flags of its own", spec.path)
    } else {
        format!("`extend {}` takes {}", spec.path, known.join(", "))
    };
    let dash = if name.starts_with("--") {
        String::new()
    } else {
        format!(" If {name} is a value, not a flag, put it after `--`.")
    };
    CliError::usage(
        format!("`extend {}` has no flag {name}", spec.path),
        format!(
            "{near}{choices}, plus the global flags ({}).{dash}",
            GLOBAL_FLAG_NAMES.join(", ")
        ),
    )
}

/// Close enough to be a typo: one edit apart, or the same after the first four letters.
fn similar(a: &str, b: &str) -> bool {
    let (a, b): (Vec<char>, Vec<char>) = (a.chars().collect(), b.chars().collect());
    if a.len().abs_diff(b.len()) > 2 {
        return false;
    }
    // Levenshtein distance, small inputs.
    let mut prev: Vec<usize> = (0..=b.len()).collect();
    for (i, ca) in a.iter().enumerate() {
        let mut cur = vec![i + 1];
        for (j, cb) in b.iter().enumerate() {
            let sub = prev[j] + usize::from(ca != cb);
            cur.push(sub.min(prev[j + 1] + 1).min(cur[j] + 1));
        }
        prev = cur;
    }
    prev[b.len()] <= 2
}

#[cfg(test)]
mod tests {
    use super::*;

    fn strings(items: &[&str]) -> Vec<String> {
        items.iter().map(|s| s.to_string()).collect()
    }

    #[test]
    fn unknown_flags_are_refused_with_the_choices() {
        let e = Args::parse(&strings(&["--onlinee"]), "device ls").unwrap_err();
        assert_eq!(e.message, "`extend device ls` has no flag --onlinee");
        let hint = e.hint.unwrap();
        assert!(hint.starts_with("Did you mean --online? "), "{hint}");
        assert!(
            hint.contains("--os <value>") && hint.contains("--team-visible"),
            "{hint}"
        );
        let e = Args::parse(&strings(&["--bogus"]), "login status").unwrap_err();
        assert!(
            e.hint
                .unwrap()
                .contains("`extend login status` takes no flags of its own"),
            "{}",
            e.message
        );
        let e = Args::parse(&strings(&["7c1e09ab", "-x"]), "device show").unwrap_err();
        assert!(e.hint.unwrap().contains("put it after `--`"));
        // Values of flags, `--` and negative numbers are not flags.
        let a = Args::parse(&strings(&["7c1e09ab", "--", "-x"]), "device rename").unwrap();
        assert_eq!(a.pos, strings(&["7c1e09ab", "-x"]));
        let a = Args::parse(&strings(&["7c1e09ab", "-5"]), "device ttl").unwrap();
        assert_eq!(a.pos, strings(&["7c1e09ab", "-5"]));
        let e = Args::parse(&strings(&["--online=yes"]), "device ls").unwrap_err();
        assert!(e.message.contains("--online takes no value"), "{}", e.message);
        let e = Args::parse(&strings(&["x", "--name"]), "device pair").unwrap_err();
        assert!(e.message.contains("--name needs a value"), "{}", e.message);
    }

    #[test]
    fn extra_arguments_are_refused() {
        let a = Args::parse(&strings(&["a", "b"]), "device show").unwrap();
        let e = a.at_most(1).unwrap_err();
        assert!(
            e.message
                .contains("`extend device show` takes 1 argument, and got 1 more: \"b\""),
            "{}",
            e.message
        );
        assert!(e.hint.unwrap().starts_with("Usage: extend device show <device_id>"));
    }

    #[test]
    fn an_extend_flag_value_is_never_a_global_flag() {
        let (g, rest) = parse_globals(strings(&["request", "send", "7c1e09ab", "--reason", "-h"])).unwrap();
        assert!(!g.help);
        assert_eq!(rest, strings(&["request", "send", "7c1e09ab", "--reason", "-h"]));
        let (g, rest) = parse_globals(strings(&["device", "pair", "4f9c2a", "--name", "--json"])).unwrap();
        assert!(!g.json);
        assert_eq!(rest[3..], strings(&["--name", "--json"]));
        // A global flag elsewhere still counts.
        let (g, _) = parse_globals(strings(&["request", "send", "x", "--reason", "hi", "--json"])).unwrap();
        assert!(g.json);
    }

    #[test]
    fn a_parse_error_keeps_the_test_id() {
        let (g, e) = *parse_globals(strings(&["--test", "abc", "device", "ls", "--timeout", "5"])).unwrap_err();
        assert_eq!(g.test.as_deref(), Some("abc"));
        assert!(e.message.contains("outside 1000–300000"), "{}", e.message);
        assert_eq!(
            find_test_id(&strings(&["device", "ls", "--test=xyz"])).as_deref(),
            Some("xyz")
        );
    }

    #[test]
    fn every_spec_names_a_documented_command() {
        for s in SPECS {
            assert!(
                crate::help::find(s.path).is_some() || crate::help::find(s.path.split(' ').next().unwrap()).is_some(),
                "`extend {}` has no help node",
                s.path
            );
        }
    }
}