cargo-tops 0.4.0

init / check / gate for the Rust-TOPS protocol. Orchestrates existing Cargo tools; does not replace them.
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
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
//! Argv steps for `cargo tops gate`.
//!
//! A layer is a list of [`Step`] values chained with `&&`, not one shell
//! string. [`tool_binary`] names the binary the command runs. `mkdir` and
//! `sh` are not that binary when the command runs `cargo llvm-cov` or
//! `cargo mutants`.
//!
//! A mutation diff that failed is [`Outcome::Failed`]. No config key waives
//! it. A diff that succeeded and is empty is [`Outcome::Vacuous`]: print it,
//! and count it for no law. [`init_exemptions`] is empty; `init` writes none.
//!
//! `main.rs` is the caller. This allow holds until that wiring references
//! the items.
#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used))]
#![allow(dead_code, reason = "main.rs wires these items")]

use std::fmt;
use std::fs;
use std::path::{Path, PathBuf};

const DIFF_NAME: &str = "rust-tops.diff";

/// The coverage layer's LCOV, under the gate's artifact directory.
pub(crate) const LCOV: &str = "lcov.info";
/// The coverage layer's per-file summary (`llvm.coverage.json.export`),
/// under the gate's artifact directory. The floors are judged on it.
pub(crate) const SUMMARY: &str = "coverage.json";
/// The crap layer's report, under the gate's artifact directory.
pub(crate) const CRAP: &str = "crap.json";

/// What a step is for.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Kind {
    /// [`tool_binary`] must be on `PATH`. A miss does not pass the layer.
    Tool,
    /// Run `argv`. A non-zero status is [`Outcome::Failed`].
    Command,
    /// `test -s`: the artifact exists and is non-empty.
    Artifact,
}

/// One argv invocation in a layer.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Step {
    pub argv: Vec<String>,
    pub kind: Kind,
}

impl Step {
    #[must_use]
    pub(crate) fn new(kind: Kind, argv: impl IntoIterator<Item = impl Into<String>>) -> Self {
        Self {
            kind,
            argv: argv.into_iter().map(Into::into).collect(),
        }
    }

    #[must_use]
    pub(crate) fn tool(argv: impl IntoIterator<Item = impl Into<String>>) -> Self {
        Self::new(Kind::Tool, argv)
    }

    #[must_use]
    pub(crate) fn command(argv: impl IntoIterator<Item = impl Into<String>>) -> Self {
        Self::new(Kind::Command, argv)
    }

    /// `test -s <path>`.
    #[must_use]
    pub(crate) fn artifact(path: impl Into<String>) -> Self {
        let path = path.into();
        Self::new(Kind::Artifact, ["test", "-s", path.as_str()])
    }

    /// Program and its arguments. Empty argv is `None`.
    #[must_use]
    pub(crate) fn program(&self) -> Option<(&str, &[String])> {
        let (program, args) = self.argv.split_first()?;
        Some((program.as_str(), args))
    }

    /// Path a [`Kind::Artifact`] step checks.
    #[must_use]
    pub(crate) fn artifact_path(&self) -> Option<&Path> {
        if self.kind != Kind::Artifact {
            return None;
        }
        let path = match self.argv.as_slice() {
            [test, flag, path, ..] if test == "test" && flag == "-s" => path,
            [.., path] => path,
            [] => return None,
        };
        Some(Path::new(path))
    }

    #[must_use]
    pub(crate) fn display(&self) -> String {
        self.argv.join(" ")
    }
}

/// How a step or a mutation diff finished.
///
/// [`Failed`](Self::Failed) and [`Vacuous`](Self::Vacuous) are different.
/// Vacuous counts for no law.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Outcome {
    Passed,
    Failed,
    ToolMissing,
    /// The diff command succeeded and the diff is empty.
    Vacuous,
}

impl Outcome {
    /// `Some(true)` pass, `Some(false)` fail, `None` when no law may count it.
    #[must_use]
    pub(crate) fn law_verdict(self) -> Option<bool> {
        match self {
            Self::Passed => Some(true),
            Self::Failed | Self::ToolMissing => Some(false),
            Self::Vacuous => None,
        }
    }

    /// Vacuous is not a pass and not a fail, so no law counts it.
    #[must_use]
    pub(crate) fn counts_for_a_law(self) -> bool {
        self.law_verdict().is_some()
    }

    /// Gate failure. Vacuous does not fail the gate.
    #[must_use]
    pub(crate) fn fails_the_gate(self) -> bool {
        matches!(self, Self::Failed | Self::ToolMissing)
    }
}

impl fmt::Display for Outcome {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::Passed => "passed",
            Self::Failed => "Failed",
            Self::ToolMissing => "not on PATH",
            Self::Vacuous => "Vacuous",
        })
    }
}

/// The binary a tool step names was not on `PATH`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct MissingTool {
    pub binary: String,
}

impl fmt::Display for MissingTool {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let binary = &self.binary;
        write!(
            f,
            "`{binary}` not on PATH (install it; cargo-tops does not vendor engines)"
        )
    }
}

impl std::error::Error for MissingTool {}

/// `Ok` when the binary [`tool_binary`] names is on `PATH`.
///
/// Call this for [`Kind::Tool`]. The name is the binary the command runs,
/// not the first word of a shell string.
pub(crate) fn check_tool(argv: &[String]) -> Result<(), MissingTool> {
    let binary = tool_binary(argv).unwrap_or_else(|| "command".to_string());
    if binary_present(&binary) {
        Ok(())
    } else {
        Err(MissingTool { binary })
    }
}

/// Binary the command actually runs.
///
/// Walks `&&` and `;` segments and unwraps `sh -c`. A leading `mkdir` or
/// `sh` is not the result when a later segment runs `cargo llvm-cov` or
/// `cargo mutants`.
#[must_use]
pub(crate) fn tool_binary(argv: &[String]) -> Option<String> {
    let tokens = tokens_from_argv(argv);
    best_binary(&split_chain(&tokens))
}

/// Coverage is `mkdir`, then `cargo llvm-cov`, then `test -s`, with
/// [`LCOV`] under `dir`, the gate's artifact directory, then the per-file
/// [`SUMMARY`] of the same run (`cargo llvm-cov report`, which reads that
/// run's profiles and runs no test) and its `test -s`.
/// The tool step names `cargo-llvm-cov`, not `mkdir`. It runs the suite with
/// the same `--workspace`, `--all-features` and `--profile ci` as `unit`, so
/// its run can stand for `unit`, `integration` and `property`. The run is
/// workspace-wide even for a crate's instance, so a test in any member
/// counts; the floors judge only that crate's files (`scope`).
#[must_use]
pub(crate) fn coverage_steps(dir: &Path) -> Vec<Step> {
    let dir_shown = dir.display().to_string();
    let lcov = dir.join(LCOV).display().to_string();
    let summary = dir.join(SUMMARY).display().to_string();
    vec![
        Step::command(["mkdir", "-p", dir_shown.as_str()]),
        Step::tool([
            "cargo",
            "llvm-cov",
            "nextest",
            "--workspace",
            "--all-features",
            "--profile",
            "ci",
            "--lcov",
            "--output-path",
            lcov.as_str(),
        ]),
        Step::artifact(lcov),
        Step::tool([
            "cargo",
            "llvm-cov",
            "report",
            "--json",
            "--summary-only",
            "--output-path",
            summary.as_str(),
        ]),
        Step::artifact(summary),
    ]
}

/// `test -s` is true when the path exists and its size is greater than zero.
/// An empty artifact is [`Outcome::Failed`], not [`Outcome::Vacuous`].
#[must_use]
pub(crate) fn artifact_outcome(path: &Path) -> Outcome {
    let present = fs::metadata(path).is_ok_and(|meta| meta.len() > 0);
    if present {
        Outcome::Passed
    } else {
        Outcome::Failed
    }
}

/// A failed or vacuous outcome stops the `&&` chain. Only a pass continues.
#[must_use]
pub(crate) fn chain_continues(outcome: Outcome) -> bool {
    outcome == Outcome::Passed
}

/// One layer id and the date the exemption stops.
///
/// Not a list of layers. [`init_exemptions`] is what `init` writes.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Exemption {
    pub layer: String,
    pub expires: String,
}

/// Why [`Exemption::new`] refused a value.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ExemptionError {
    /// Missing layer id, or more than one.
    Layer,
    /// Expiry is not a real `YYYY-MM-DD` date.
    Expiry,
}

impl fmt::Display for ExemptionError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::Layer => "an exemption names one layer id",
            Self::Expiry => "an exemption needs an expiry date (YYYY-MM-DD)",
        })
    }
}

impl std::error::Error for ExemptionError {}

impl Exemption {
    /// `layer` is one id such as `mutation`. `expires` is `YYYY-MM-DD`.
    pub(crate) fn new(
        layer: impl AsRef<str>,
        expires: impl AsRef<str>,
    ) -> Result<Self, ExemptionError> {
        let layer = layer.as_ref();
        if !one_layer(layer) {
            return Err(ExemptionError::Layer);
        }
        let expires = expires.as_ref();
        if !valid_expiry(expires) {
            return Err(ExemptionError::Expiry);
        }
        Ok(Self {
            layer: layer.to_string(),
            expires: expires.to_string(),
        })
    }
}

/// Exemptions `init` writes. Always none.
#[must_use]
pub(crate) fn init_exemptions() -> &'static [Exemption] {
    &[]
}

#[expect(
    clippy::fn_params_excessive_bools,
    reason = "already in this crate when the strict table was turned on"
)]
/// Classify a mutation diff. A failed command is [`Outcome::Failed`] even
/// when the diff is empty. There is no waiver parameter and no config key
/// is read. A successful empty diff is [`Outcome::Vacuous`].
#[must_use]
pub(crate) fn diff_outcome(command_ok: bool, empty: bool) -> Outcome {
    if !command_ok {
        return Outcome::Failed;
    }
    if empty {
        Outcome::Vacuous
    } else {
        Outcome::Passed
    }
}

#[expect(
    clippy::fn_params_excessive_bools,
    reason = "already in this crate when the strict table was turned on"
)]
/// Read the diff file only after the command succeeded.
///
/// A failed command is [`Outcome::Failed`] even if a stale diff is sitting
/// at `diff_path`. A successful empty file is [`Outcome::Vacuous`].
#[must_use]
pub(crate) fn judge_diff(command_ok: bool, diff_path: &Path) -> Outcome {
    if !command_ok {
        return diff_outcome(false, false);
    }
    match fs::metadata(diff_path) {
        Ok(meta) if meta.len() == 0 => diff_outcome(true, true),
        Ok(_) => diff_outcome(true, false),
        Err(_) => diff_outcome(false, false),
    }
}

/// Mutation diff command, then the `cargo mutants` tool step.
///
/// The diff command uses `git merge-base` and `&&`, and writes
/// `<report_dir>/rust-tops.diff`. Run it with the project as the working
/// directory. [`MutationPlan::after_diff`] runs mutants only after a
/// non-empty diff; a failed diff is not waived, and an empty diff is not
/// handed to `cargo mutants`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct MutationPlan {
    pub diff: Step,
    pub diff_path: PathBuf,
    pub mutants: Step,
}

impl MutationPlan {
    #[must_use]
    pub(crate) fn new(report_dir: &Path) -> Self {
        let diff_path = report_dir.join(DIFF_NAME);
        let diff_arg = diff_path.display().to_string();
        let script = mutation_diff_script(report_dir, &diff_path);
        let diff = Step::command(["sh", "-c", script.as_str()]);
        let mutants = Step::tool([
            "cargo",
            "mutants",
            "--in-diff",
            diff_arg.as_str(),
            "-j",
            "2",
        ]);
        Self {
            diff,
            diff_path,
            mutants,
        }
    }

    /// Mutants runs only when the diff passed. Failed and Vacuous stop.
    #[must_use]
    pub(crate) fn after_diff(&self, outcome: Outcome) -> Option<&Step> {
        chain_continues(outcome).then_some(&self.mutants)
    }
}

/// Not a git work tree, or no commit: the command fails. No `origin/main`:
/// it writes an empty diff, so the layer is Vacuous. `origin/main` with no
/// merge-base: it fails. Otherwise the diff from the merge-base to `HEAD`.
fn mutation_diff_script(report_dir: &Path, diff_path: &Path) -> String {
    let dir = shell_quote(report_dir);
    let file = shell_quote(diff_path);
    format!(
        "mkdir -p {dir} && git rev-parse --verify --quiet HEAD >/dev/null \
         && if git rev-parse --verify --quiet refs/remotes/origin/main >/dev/null; \
         then base=\"$(git merge-base origin/main HEAD)\" \
         && git diff \"$base\" HEAD --unified=0 > {file}; \
         else : > {file}; fi"
    )
}

fn shell_quote(path: &Path) -> String {
    let text = path.display().to_string().replace('\'', "'\\''");
    format!("'{text}'")
}

fn one_layer(layer: &str) -> bool {
    !layer.is_empty()
        && !layer.starts_with('-')
        && !layer.ends_with('-')
        && !layer.contains("--")
        && layer
            .chars()
            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
}

/// Whether `text` is a real `YYYY-MM-DD` day.
pub(crate) fn valid_expiry(text: &str) -> bool {
    let bytes = text.as_bytes();
    #[expect(
        clippy::indexing_slicing,
        reason = "already in this crate when the strict table was turned on"
    )]
    if bytes.len() != 10 || bytes[4] != b'-' || bytes[7] != b'-' {
        return false;
    }
    let Ok(year) = text[0..4].parse::<i32>() else {
        return false;
    };
    let Ok(month) = text[5..7].parse::<u8>() else {
        return false;
    };
    let Ok(day) = text[8..10].parse::<u8>() else {
        return false;
    };
    let max = match month {
        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
        4 | 6 | 9 | 11 => 30,
        2 if leap(year) => 29,
        2 => 28,
        _ => return false,
    };
    (1..=max).contains(&day)
}

fn leap(year: i32) -> bool {
    let by4 = year % 4 == 0;
    let by100 = year % 100 == 0;
    let by400 = year % 400 == 0;
    by4 && (!by100 || by400)
}

fn binary_present(binary: &str) -> bool {
    on_path(binary) || aliases(binary).iter().any(|name| on_path(name))
}

fn aliases(binary: &str) -> &'static [&'static str] {
    match binary {
        "cargo-crap" => &["cargo-crappy"],
        "cargo-kani" => &["kani"],
        _ => &[],
    }
}

fn on_path(bin: &str) -> bool {
    let Some(path) = std::env::var_os("PATH") else {
        return false;
    };
    std::env::split_paths(&path).any(|dir| is_executable(&dir.join(bin)))
}

fn is_executable(path: &Path) -> bool {
    let Ok(meta) = fs::metadata(path) else {
        return false;
    };
    if !meta.is_file() {
        return false;
    }
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        meta.permissions().mode() & 0o111 != 0
    }
    #[cfg(not(unix))]
    {
        true
    }
}

fn tokens_from_argv(argv: &[String]) -> Vec<String> {
    #[expect(
        clippy::indexing_slicing,
        reason = "already in this crate when the strict table was turned on"
    )]
    if argv.len() >= 3 && argv[0] == "sh" && argv[1] == "-c" {
        #[expect(
            clippy::indexing_slicing,
            reason = "already in this crate when the strict table was turned on"
        )]
        let mut tokens = tokenize(&argv[2]);
        tokens.extend(argv.iter().skip(3).cloned());
        return unwrap_all(tokens);
    }
    let mut tokens = Vec::new();
    for arg in argv {
        if contains_shell_syntax(arg) {
            tokens.extend(tokenize(arg));
        } else {
            tokens.push(arg.clone());
        }
    }
    unwrap_all(tokens)
}

fn contains_shell_syntax(arg: &str) -> bool {
    arg.contains([' ', '\t', '\n', '&', ';', '|', '\'', '"', '$', '>', '<'])
}

fn unwrap_all(mut tokens: Vec<String>) -> Vec<String> {
    for _ in 0..8 {
        let (next, changed) = unwrap_once(&tokens);
        if !changed {
            return next;
        }
        tokens = next;
    }
    tokens
}

fn unwrap_once(tokens: &[String]) -> (Vec<String>, bool) {
    let mut out = Vec::new();
    let mut changed = false;
    let mut index = 0;
    while index < tokens.len() {
        #[expect(
            clippy::indexing_slicing,
            reason = "already in this crate when the strict table was turned on"
        )]
        let is_shell = tokens[index] == "sh"
            && tokens.get(index + 1).map(String::as_str) == Some("-c")
            && index + 2 < tokens.len();
        if is_shell {
            #[expect(
                clippy::indexing_slicing,
                reason = "already in this crate when the strict table was turned on"
            )]
            out.extend(tokenize(&tokens[index + 2]));
            index += 3;
            changed = true;
        } else {
            #[expect(
                clippy::indexing_slicing,
                reason = "already in this crate when the strict table was turned on"
            )]
            out.push(tokens[index].clone());
            index += 1;
        }
    }
    (out, changed)
}

fn tokenize(input: &str) -> Vec<String> {
    let mut tokens = Vec::new();
    let mut buf = String::new();
    let mut chars = input.chars().peekable();
    let mut quote: Option<char> = None;
    while let Some(c) = chars.next() {
        if let Some(q) = quote {
            if c == q {
                quote = None;
            } else {
                buf.push(c);
            }
            continue;
        }
        match c {
            '\'' | '"' => quote = Some(c),
            ' ' | '\t' | '\n' | '\r' => flush(&mut tokens, &mut buf),
            '&' if chars.peek() == Some(&'&') => {
                chars.next();
                flush(&mut tokens, &mut buf);
                tokens.push("&&".to_string());
            }
            '|' if chars.peek() == Some(&'|') => {
                chars.next();
                flush(&mut tokens, &mut buf);
                tokens.push("||".to_string());
            }
            ';' | '|' => {
                flush(&mut tokens, &mut buf);
                tokens.push(c.to_string());
            }
            _ => buf.push(c),
        }
    }
    flush(&mut tokens, &mut buf);
    tokens
}

fn flush(tokens: &mut Vec<String>, buf: &mut String) {
    if !buf.is_empty() {
        tokens.push(std::mem::take(buf));
    }
}

fn split_chain(tokens: &[String]) -> Vec<Vec<String>> {
    let mut segments = Vec::new();
    let mut current = Vec::new();
    for token in tokens {
        if matches!(token.as_str(), "&&" | "||" | ";" | "|") {
            if !current.is_empty() {
                segments.push(std::mem::take(&mut current));
            }
        } else {
            current.push(token.clone());
        }
    }
    if !current.is_empty() {
        segments.push(current);
    }
    segments
}

fn best_binary(segments: &[Vec<String>]) -> Option<String> {
    let mut builtin = None;
    let mut other = None;
    for segment in segments {
        let Some(argv0) = command_word(segment) else {
            continue;
        };
        if argv0 == "cargo" {
            let name = cargo_binary(cargo_subcommand(segment).as_deref());
            if name == "cargo" {
                builtin.get_or_insert(name);
            } else {
                return Some(name);
            }
        } else if !is_prep(&argv0) {
            other.get_or_insert(argv0);
        }
    }
    builtin
        .or(other)
        .or_else(|| segments.iter().find_map(|segment| command_word(segment)))
}

fn command_word(segment: &[String]) -> Option<String> {
    segment.iter().find_map(|token| {
        if token.is_empty() || is_redirect(token) || is_env_assign(token) {
            None
        } else {
            Some(token.clone())
        }
    })
}

fn cargo_subcommand(segment: &[String]) -> Option<String> {
    let mut seen_cargo = false;
    for token in segment {
        if token.is_empty() || is_redirect(token) || is_env_assign(token) {
            continue;
        }
        if !seen_cargo {
            if token == "cargo" {
                seen_cargo = true;
            }
            continue;
        }
        if token.starts_with('+') || token.starts_with('-') {
            continue;
        }
        return Some(token.clone());
    }
    None
}

/// Built-ins (`fmt`, `clippy`, `test`, `build`, `check`, `bench`) and unknown
/// subcommands are `cargo`. External subcommands are `cargo-<sub>`.
fn cargo_binary(sub: Option<&str>) -> String {
    match sub {
        Some("nextest") => "cargo-nextest",
        Some("llvm-cov") => "cargo-llvm-cov",
        Some("crap") => "cargo-crap",
        Some("mutants") => "cargo-mutants",
        Some("deny") => "cargo-deny",
        Some("fuzz") => "cargo-fuzz",
        Some("kani") => "cargo-kani",
        _ => "cargo",
    }
    .to_string()
}

fn is_prep(argv0: &str) -> bool {
    matches!(argv0, "mkdir" | "sh" | "test")
}

fn is_redirect(token: &str) -> bool {
    if token.starts_with('>') || token.starts_with('<') {
        return true;
    }
    match token.find('>') {
        Some(at) if at > 0 => token[..at].chars().all(|c| c.is_ascii_digit()),
        _ => false,
    }
}

fn is_env_assign(token: &str) -> bool {
    let Some((name, _)) = token.split_once('=') else {
        return false;
    };
    !name.is_empty()
        && !name.starts_with('-')
        && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
}

#[cfg(test)]
mod expiry {
    use super::{Exemption, ExemptionError, Outcome};

    #[test]
    fn a_bad_layer_is_refused_and_each_refusal_says_why() {
        assert_eq!(
            Exemption::new("crap mutation", "2030-01-01"),
            Err(ExemptionError::Layer)
        );
        assert_eq!(Exemption::new("", "2030-01-01"), Err(ExemptionError::Layer));
        assert_eq!(
            ExemptionError::Layer.to_string(),
            "an exemption names one layer id"
        );
        assert_eq!(
            ExemptionError::Expiry.to_string(),
            "an exemption needs an expiry date (YYYY-MM-DD)"
        );
        assert_eq!(Outcome::Vacuous.to_string(), "Vacuous");
    }

    #[test]
    fn a_real_date_is_accepted_and_a_fake_one_is_not() {
        assert!(Exemption::new("mutation", "2024-02-29").is_ok());
        assert!(Exemption::new("mutation", "2023-02-29").is_err());
        assert!(Exemption::new("mutation", "2024-13-01").is_err());
        assert!(Exemption::new("mutation", "not-a-date").is_err());
    }
}