Skip to main content

safe_chains/
policy.rs

1use crate::parse::{Token, WordSet};
2
3/// Whether unrecognized flag-shaped tokens are denied or silently accepted
4/// as positional arguments. The default (Strict) makes the allowlist
5/// authoritative — any unrecognized `-X` or `--foo` is denied.
6#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
7pub enum UnknownTolerance {
8    /// Deny every unrecognized flag-shaped token. The safe default.
9    #[default]
10    Strict,
11    /// Accept unknown single-dash tokens (`-X`, `-help`, `-mayDie`) as
12    /// positional. Reject unknown double-dash. Use for tools like
13    /// `pdftotext` that have single-dash long flags.
14    Short,
15    /// Accept unknown double-dash tokens (`--foo`, `--foo=value`) as
16    /// positional. Reject unknown single-dash. Dangerous: most modern
17    /// destructive flags are double-dash, so enabling this can silently
18    /// accept mutating options. Reserved for tools with genuinely
19    /// unbounded long-flag surfaces (AWS CLI service flags).
20    Long,
21    /// Accept both single-dash and double-dash unknowns as positional.
22    /// Most permissive; combines the cost of `Short` and `Long`.
23    Both,
24}
25
26impl UnknownTolerance {
27    pub const fn allows_short(self) -> bool {
28        matches!(self, Self::Short | Self::Both)
29    }
30    pub const fn allows_long(self) -> bool {
31        matches!(self, Self::Long | Self::Both)
32    }
33}
34
35/// How the dispatcher treats tokens that look like flags but aren't in the
36/// allowlist. `unknown` controls flag-shaped unknowns; `numeric_dash` opts
37/// into `-NUMBER` shorthand (e.g. `head -20`); `single_dash_words` stops a single-dash token
38/// being read as a cluster of short flags, for tools whose options are whole words (`exiftool -if`
39/// is one option that runs Perl, never `-i -f`).
40#[derive(Clone, Copy, Debug, Default)]
41pub struct FlagTolerance {
42    pub unknown: UnknownTolerance,
43    pub numeric_dash: bool,
44    pub single_dash_words: bool,
45}
46
47impl FlagTolerance {
48    /// Strict allowlist: deny every unrecognized flag-shaped token.
49    /// `const`-callable for use in static `FlagPolicy` literals.
50    pub const fn strict() -> Self {
51        Self { unknown: UnknownTolerance::Strict, numeric_dash: false, single_dash_words: false }
52    }
53}
54
55/// Predicate over the first positional token of a fallback grammar.
56/// Lets a TOML-declared fallback say "the first positional must look
57/// like a path" without the handler hardcoding the test.
58#[derive(Clone, Copy, Debug, PartialEq, Eq)]
59pub enum PositionalShape {
60    /// Looks like a file path: contains `/`, contains `.`, or is `-`
61    /// (the conventional stdin marker). Rejects flag-shaped tokens.
62    Path,
63    /// A go LOCAL package/file argument: `.`/`..`, a `./`-, `../`-, or
64    /// `/`-anchored path, or a `*.go` file. This is exactly Go's rule for
65    /// "this is a filesystem path, not an import path" — a BARE import path
66    /// (`rsc.io/x@latest`, `example.com/cmd`, `bin/tool`) is resolved via the
67    /// module system and, with `@version`, DOWNLOADS AND RUNS remote code, so
68    /// it must not be treated as a worktree-local executor.
69    GoPackage,
70}
71
72impl PositionalShape {
73    pub fn matches(self, token: &str) -> bool {
74        match self {
75            Self::Path => looks_like_path(token),
76            Self::GoPackage => is_go_local_package(token),
77        }
78    }
79
80    pub fn from_name(name: &str) -> Option<Self> {
81        match name {
82            "path" => Some(Self::Path),
83            "go-package" => Some(Self::GoPackage),
84            _ => None,
85        }
86    }
87}
88
89/// Whether `token` is a go LOCAL package/file (a filesystem path), as opposed to a
90/// module import path. See [`PositionalShape::GoPackage`].
91pub fn is_go_local_package(token: &str) -> bool {
92    token == "." || token == ".." || token.starts_with("./") || token.starts_with("../") || token.starts_with('/') || token.ends_with(".go")
93}
94
95/// Heuristic for "this token looks like a file path." Used by the
96/// `path` `PositionalShape`. Conservative on purpose — a bare word
97/// like `Tiltfile` is a valid filename in cwd but the heuristic
98/// rejects it to avoid swallowing flag-less subcommands. Callers
99/// that want bare-name acceptance should match a sub block instead.
100///
101/// A leading `~` counts, and its absence was a hole rather than part of the conservatism: the
102/// shell expands `~`, `~/x` and `~user` to a home directory, so all four are paths — but a BARE
103/// `~` carries neither `/` nor `.`, so it failed the test and every consumer that pre-filters on
104/// it skipped the operand entirely. `rg x ~` searched `$HOME` and printed matches to the model
105/// while `rg x ~/` denied; `od ~`, `tee ~`, `shred ~` and `awk '{print}' ~` did the same. The
106/// commands whose programs legitimately contain `~` (awk's match operator, an rg pattern) exclude
107/// it by POSITION before reaching here, so recognizing it costs them nothing.
108pub fn looks_like_path(token: &str) -> bool {
109    if token.is_empty() {
110        return false;
111    }
112    if token.starts_with('-') {
113        return token == "-";
114    }
115    token.starts_with('~') || token.contains('/') || token.contains('.')
116}
117
118pub trait FlagSet {
119    fn contains_flag(&self, token: &str) -> bool;
120    fn contains_short(&self, byte: u8) -> bool;
121}
122
123impl FlagSet for WordSet {
124    fn contains_flag(&self, token: &str) -> bool {
125        self.contains(token)
126    }
127    fn contains_short(&self, byte: u8) -> bool {
128        self.contains_short(byte)
129    }
130}
131
132impl FlagSet for [String] {
133    fn contains_flag(&self, token: &str) -> bool {
134        self.iter().any(|f| f.as_str() == token)
135    }
136    fn contains_short(&self, byte: u8) -> bool {
137        self.iter().any(|f| f.len() == 2 && f.as_bytes()[1] == byte)
138    }
139}
140
141impl FlagSet for Vec<String> {
142    fn contains_flag(&self, token: &str) -> bool {
143        self.as_slice().contains_flag(token)
144    }
145    fn contains_short(&self, byte: u8) -> bool {
146        self.as_slice().contains_short(byte)
147    }
148}
149
150pub struct FlagPolicy {
151    pub standalone: WordSet,
152    pub valued: WordSet,
153    pub bare: bool,
154    pub max_positional: Option<usize>,
155    pub tolerance: FlagTolerance,
156}
157
158impl FlagPolicy {
159    pub fn describe(&self) -> String {
160        use crate::docs::wordset_items;
161        let mut lines = Vec::new();
162        let standalone = wordset_items(&self.standalone);
163        if !standalone.is_empty() {
164            lines.push(format!("- Allowed standalone flags: {standalone}"));
165        }
166        let valued = wordset_items(&self.valued);
167        if !valued.is_empty() {
168            lines.push(format!("- Allowed valued flags: {valued}"));
169        }
170        if self.bare {
171            lines.push("- Bare invocation allowed".to_string());
172        }
173        if self.tolerance.unknown != UnknownTolerance::Strict {
174            lines.push("- Hyphen-prefixed positional arguments accepted".to_string());
175        }
176        if self.tolerance.numeric_dash {
177            lines.push("- Numeric shorthand accepted (e.g. -20 for -n 20)".to_string());
178        }
179        if lines.is_empty() && !self.bare {
180            return "- Positional arguments only".to_string();
181        }
182        lines.join("\n")
183    }
184}
185
186pub fn check(tokens: &[Token], policy: &FlagPolicy) -> bool {
187    check_flags(tokens, &policy.standalone, &policy.valued, policy.bare, policy.max_positional, policy.tolerance)
188}
189
190pub(crate) fn consumes_next_value(next: Option<&Token>) -> bool {
191    match next {
192        None => false,
193        Some(t) if crate::cst::opaque::is_flag_probe(t.as_str()) => true,
194        Some(t) => {
195            let b = t.as_bytes();
196            // An option-like token (starts with `-` and isn't a negative
197            // number) is never the value of a preceding valued flag. Consuming
198            // it would let an execution-enabling flag ride in as a bogus
199            // "value" — e.g. `node --check --require=evil.js`, where node runs
200            // the `--require` preload even in syntax-check mode. Negative
201            // numbers (`head -n -5`) and a lone `-` (stdin) are real values.
202            !(b.len() > 1 && b[0] == b'-' && !b[1].is_ascii_digit())
203        }
204    }
205}
206
207pub fn check_flags<S: FlagSet + ?Sized, V: FlagSet + ?Sized>(
208    tokens: &[Token],
209    standalone: &S,
210    valued: &V,
211    bare: bool,
212    max_positional: Option<usize>,
213    tolerance: FlagTolerance,
214) -> bool {
215    if tokens.len() == 1 {
216        return bare;
217    }
218
219    let mut i = 1;
220    let mut positionals: usize = 0;
221    while i < tokens.len() {
222        let t = &tokens[i];
223
224        if *t == "--" {
225            positionals += tokens.len() - i - 1;
226            break;
227        }
228
229        if !t.starts_with('-') {
230            positionals += 1;
231            i += 1;
232            continue;
233        }
234
235        if tolerance.numeric_dash && t.len() > 1 && t[1..].bytes().all(|b| b.is_ascii_digit()) {
236            i += 1;
237            continue;
238        }
239
240        if standalone.contains_flag(t) {
241            i += 1;
242            continue;
243        }
244
245        if valued.contains_flag(t) {
246            if consumes_next_value(tokens.get(i + 1)) {
247                i += 2;
248            } else {
249                i += 1;
250            }
251            continue;
252        }
253
254        if let Some(flag) = t.as_str().split_once('=').map(|(f, _)| f) {
255            if valued.contains_flag(flag) {
256                i += 1;
257                continue;
258            }
259            // `--foo=value` forms are governed by the long-flag tolerance.
260            if tolerance.unknown.allows_long() {
261                positionals += 1;
262                i += 1;
263                continue;
264            }
265            return false;
266        }
267
268        if t.starts_with("--") {
269            if tolerance.unknown.allows_long() {
270                positionals += 1;
271                i += 1;
272                continue;
273            }
274            return false;
275        }
276
277        if tolerance.single_dash_words && t.len() > 1 {
278            if tolerance.unknown.allows_short() {
279                positionals += 1;
280                i += 1;
281                continue;
282            }
283            return false;
284        }
285
286        let bytes = t.as_bytes();
287        let mut j = 1;
288        while j < bytes.len() {
289            let b = bytes[j];
290            let is_last = j == bytes.len() - 1;
291            if standalone.contains_short(b) {
292                j += 1;
293                continue;
294            }
295            if valued.contains_short(b) {
296                if is_last && consumes_next_value(tokens.get(i + 1)) {
297                    i += 1;
298                }
299                break;
300            }
301            if tolerance.unknown.allows_short() {
302                positionals += 1;
303                break;
304            }
305            return false;
306        }
307        i += 1;
308    }
309    max_positional.is_none_or(|max| positionals <= max)
310}
311
312#[cfg(test)]
313mod tests {
314    use super::*;
315
316    static TEST_POLICY: FlagPolicy = FlagPolicy {
317        standalone: WordSet::flags(&[
318            "--color", "--count", "--help", "--recursive", "--version", "-H", "-c", "-i", "-l", "-n", "-o", "-r", "-s", "-v", "-w",
319        ]),
320        valued: WordSet::flags(&["--after-context", "--before-context", "--max-count", "-A", "-B", "-m"]),
321        bare: false,
322        max_positional: None,
323        tolerance: FlagTolerance::strict(),
324    };
325
326    fn toks(words: &[&str]) -> Vec<Token> {
327        words.iter().map(|s| Token::from_test(s)).collect()
328    }
329
330    #[test]
331    fn bare_denied_when_bare_false() {
332        assert!(!check(&toks(&["grep"]), &TEST_POLICY));
333    }
334
335    #[test]
336    fn bare_allowed_when_bare_true() {
337        let policy = FlagPolicy {
338            standalone: WordSet::flags(&[]),
339            valued: WordSet::flags(&[]),
340            bare: true,
341            max_positional: None,
342            tolerance: FlagTolerance::strict(),
343        };
344        assert!(check(&toks(&["uname"]), &policy));
345    }
346
347    /// What a flag declared in BOTH lists actually does — measured, because the answer decides
348    /// whether an optional-value flag needs new machinery or only a name.
349    ///
350    /// TODO.md recorded that the two declarations "contradict each other and only one can be
351    /// honoured". That is not what the walk does. `standalone` is consulted first, so the BARE
352    /// spelling matches there and cannot swallow the next token; the `=` branch below it consults
353    /// `valued`, so the GLUED spelling matches too. Both are honoured, for different spellings —
354    /// which is exactly optional-value semantics, and matches getopt, where an optional argument
355    /// must be glued (`--flag=x`, never `--flag x`).
356    ///
357    /// The gap is the SHORT glued form: `-r0` reaches the cluster loop, which walks byte by byte
358    /// and has no notion of "the rest of this token is my value", so it fails on `0`.
359    #[test]
360    fn a_flag_declared_in_both_lists_already_takes_an_optional_value() {
361        static BOTH: FlagPolicy = FlagPolicy {
362            standalone: WordSet::flags(&["--long", "-r"]),
363            valued: WordSet::flags(&["--long", "-r"]),
364            bare: true,
365            max_positional: Some(0),
366            tolerance: FlagTolerance::strict(),
367        };
368        assert!(check(&toks(&["zstd", "--long"]), &BOTH), "bare long form");
369        assert!(check(&toks(&["zstd", "--long=27"]), &BOTH), "glued long form");
370        assert!(check(&toks(&["zstd", "-r"]), &BOTH), "bare short form");
371
372        // The bare form must NOT eat the next token — that swallow is how a path becomes a
373        // positional and slips the flag gate.
374        assert!(!check(&toks(&["zstd", "--long", "somefile"]), &BOTH), "the bare form must not consume the following token as its value");
375
376        // The short glued form is the one shape this does not cover.
377        assert!(!check(&toks(&["7z", "-r0"]), &BOTH), "short-glued is NOT handled today");
378    }
379
380    #[test]
381    fn standalone_long_flag() {
382        assert!(check(&toks(&["grep", "--recursive", "pattern", "."]), &TEST_POLICY));
383    }
384
385    #[test]
386    fn standalone_short_flag() {
387        assert!(check(&toks(&["grep", "-r", "pattern", "."]), &TEST_POLICY));
388    }
389
390    #[test]
391    fn valued_long_flag_space() {
392        assert!(check(&toks(&["grep", "--max-count", "5", "pattern"]), &TEST_POLICY));
393    }
394
395    #[test]
396    fn valued_long_flag_eq() {
397        assert!(check(&toks(&["grep", "--max-count=5", "pattern"]), &TEST_POLICY));
398    }
399
400    #[test]
401    fn valued_short_flag_space() {
402        assert!(check(&toks(&["grep", "-m", "5", "pattern"]), &TEST_POLICY));
403    }
404
405    #[test]
406    fn combined_standalone_short() {
407        assert!(check(&toks(&["grep", "-rn", "pattern", "."]), &TEST_POLICY));
408    }
409
410    #[test]
411    fn combined_short_with_valued_last() {
412        assert!(check(&toks(&["grep", "-rnm", "5", "pattern"]), &TEST_POLICY));
413    }
414
415    #[test]
416    fn combined_short_valued_mid_consumes_rest() {
417        assert!(check(&toks(&["grep", "-rmn", "pattern"]), &TEST_POLICY));
418    }
419
420    #[test]
421    fn unknown_long_flag_denied() {
422        assert!(!check(&toks(&["grep", "--exec", "cmd"]), &TEST_POLICY));
423    }
424
425    #[test]
426    fn unknown_short_flag_denied() {
427        assert!(!check(&toks(&["grep", "-z", "pattern"]), &TEST_POLICY));
428    }
429
430    #[test]
431    fn unknown_combined_short_denied() {
432        assert!(!check(&toks(&["grep", "-rz", "pattern"]), &TEST_POLICY));
433    }
434
435    #[test]
436    fn unknown_long_eq_denied() {
437        assert!(!check(&toks(&["grep", "--output=file.txt", "pattern"]), &TEST_POLICY));
438    }
439
440    #[test]
441    fn double_dash_stops_checking() {
442        assert!(check(&toks(&["grep", "--", "--not-a-flag", "file"]), &TEST_POLICY));
443    }
444
445    #[test]
446    fn positional_args_allowed() {
447        assert!(check(&toks(&["grep", "pattern", "file.txt", "other.txt"]), &TEST_POLICY));
448    }
449
450    #[test]
451    fn mixed_flags_and_positional() {
452        assert!(check(&toks(&["grep", "-rn", "--color", "--max-count", "10", "pattern", "."]), &TEST_POLICY,));
453    }
454
455    #[test]
456    fn valued_short_in_explicit_form() {
457        assert!(check(&toks(&["grep", "-A", "3", "-B", "3", "pattern"]), &TEST_POLICY));
458    }
459
460    #[test]
461    fn bare_dash_allowed_as_stdin() {
462        assert!(check(&toks(&["grep", "pattern", "-"]), &TEST_POLICY));
463    }
464
465    #[test]
466    fn valued_flag_at_end_without_value() {
467        assert!(check(&toks(&["grep", "--max-count"]), &TEST_POLICY));
468    }
469
470    #[test]
471    fn single_short_in_wordset_and_byte_array() {
472        assert!(check(&toks(&["grep", "-c", "pattern"]), &TEST_POLICY));
473    }
474
475    static SYNTAX_CHECK_POLICY: FlagPolicy = FlagPolicy {
476        standalone: WordSet::flags(&["--help", "-h"]),
477        valued: WordSet::flags(&["--check", "-c"]),
478        bare: false,
479        max_positional: Some(0),
480        tolerance: FlagTolerance::strict(),
481    };
482
483    #[test]
484    fn valued_flag_consumes_path_value() {
485        assert!(check(&toks(&["node", "--check", "app.js"]), &SYNTAX_CHECK_POLICY));
486        assert!(check(&toks(&["node", "-c", "app.js"]), &SYNTAX_CHECK_POLICY));
487    }
488
489    #[test]
490    fn valued_flag_does_not_swallow_following_long_option() {
491        assert!(!check(&toks(&["node", "--check", "--require=./evil.js"]), &SYNTAX_CHECK_POLICY,));
492    }
493
494    #[test]
495    fn valued_short_does_not_swallow_following_option() {
496        assert!(!check(&toks(&["node", "-c", "-r./evil.js"]), &SYNTAX_CHECK_POLICY));
497    }
498
499    #[test]
500    fn valued_flag_still_consumes_negative_number() {
501        let policy = FlagPolicy {
502            standalone: WordSet::flags(&[]),
503            valued: WordSet::flags(&["-n"]),
504            bare: false,
505            max_positional: Some(1),
506            tolerance: FlagTolerance::strict(),
507        };
508        assert!(check(&toks(&["head", "-n", "-5", "file"]), &policy));
509    }
510
511    static LIMITED_POLICY: FlagPolicy = FlagPolicy {
512        standalone: WordSet::flags(&["--count", "-c", "-d", "-i", "-u"]),
513        valued: WordSet::flags(&["--skip-fields", "-f", "-s"]),
514        bare: true,
515        max_positional: Some(1),
516        tolerance: FlagTolerance::strict(),
517    };
518
519    #[test]
520    fn max_positional_within_limit() {
521        assert!(check(&toks(&["uniq", "input.txt"]), &LIMITED_POLICY));
522    }
523
524    #[test]
525    fn max_positional_exceeded() {
526        assert!(!check(&toks(&["uniq", "input.txt", "output.txt"]), &LIMITED_POLICY));
527    }
528
529    #[test]
530    fn max_positional_with_flags_within_limit() {
531        assert!(check(&toks(&["uniq", "-c", "-f", "3", "input.txt"]), &LIMITED_POLICY));
532    }
533
534    #[test]
535    fn max_positional_with_flags_exceeded() {
536        assert!(!check(&toks(&["uniq", "-c", "input.txt", "output.txt"]), &LIMITED_POLICY));
537    }
538
539    #[test]
540    fn max_positional_after_double_dash() {
541        assert!(!check(&toks(&["uniq", "--", "input.txt", "output.txt"]), &LIMITED_POLICY));
542    }
543
544    #[test]
545    fn max_positional_bare_allowed() {
546        assert!(check(&toks(&["uniq"]), &LIMITED_POLICY));
547    }
548
549    static BOTH_TOLERANCES_POLICY: FlagPolicy = FlagPolicy {
550        standalone: WordSet::flags(&["-E", "-e", "-n"]),
551        valued: WordSet::flags(&[]),
552        bare: true,
553        max_positional: None,
554        tolerance: FlagTolerance { unknown: UnknownTolerance::Both, numeric_dash: false, single_dash_words: false },
555    };
556
557    #[test]
558    fn both_tolerances_accept_unknown_long() {
559        assert!(check(&toks(&["echo", "--unknown", "hello"]), &BOTH_TOLERANCES_POLICY));
560    }
561
562    #[test]
563    fn both_tolerances_accept_unknown_short() {
564        assert!(check(&toks(&["echo", "-x", "hello"]), &BOTH_TOLERANCES_POLICY));
565    }
566
567    #[test]
568    fn both_tolerances_accept_triple_dash() {
569        assert!(check(&toks(&["echo", "---"]), &BOTH_TOLERANCES_POLICY));
570    }
571
572    #[test]
573    fn both_tolerances_known_flags_still_work() {
574        assert!(check(&toks(&["echo", "-n", "hello"]), &BOTH_TOLERANCES_POLICY));
575    }
576
577    #[test]
578    fn both_tolerances_combo_known_short() {
579        assert!(check(&toks(&["echo", "-ne", "hello"]), &BOTH_TOLERANCES_POLICY));
580    }
581
582    #[test]
583    fn both_tolerances_combo_unknown_short_byte() {
584        assert!(check(&toks(&["echo", "-nx", "hello"]), &BOTH_TOLERANCES_POLICY));
585    }
586
587    #[test]
588    fn both_tolerances_unknown_eq_form() {
589        assert!(check(&toks(&["echo", "--foo=bar"]), &BOTH_TOLERANCES_POLICY));
590    }
591
592    // Narrow tolerance: short-only
593    // tolerate_unknown_short = true accepts unknown single-dash tokens
594    // (-X, -mayDie, -help) as positional, while leaving double-dash unknowns
595    // strict. This is the safer setting because most modern destructive
596    // flags are double-dash.
597
598    static SHORT_ONLY_POLICY: FlagPolicy = FlagPolicy {
599        standalone: WordSet::flags(&["--help"]),
600        valued: WordSet::flags(&[]),
601        bare: false,
602        max_positional: None,
603        tolerance: FlagTolerance { unknown: UnknownTolerance::Short, numeric_dash: false, single_dash_words: false },
604    };
605
606    #[test]
607    fn short_only_accepts_unknown_dash_letter() {
608        assert!(check(&toks(&["sample", "-mayDie"]), &SHORT_ONLY_POLICY));
609    }
610
611    #[test]
612    fn short_only_accepts_single_dash_long_word() {
613        // pdftotext-style: `-help`, `-layout`, `-version` (single dash + word)
614        assert!(check(&toks(&["pdftotext", "-layout"]), &SHORT_ONLY_POLICY));
615    }
616
617    #[test]
618    fn short_only_denies_unknown_double_dash() {
619        // The whole point of the narrow split: --evil-flag must not slip
620        // through when only short-tolerance is on.
621        assert!(!check(&toks(&["sample", "--evil-flag"]), &SHORT_ONLY_POLICY));
622    }
623
624    #[test]
625    fn short_only_denies_unknown_eq_form() {
626        assert!(!check(&toks(&["sample", "--evil=value"]), &SHORT_ONLY_POLICY));
627    }
628
629    #[test]
630    fn short_only_known_long_flag_still_works() {
631        assert!(check(&toks(&["sample", "--help"]), &SHORT_ONLY_POLICY));
632    }
633
634    // Narrow tolerance: long-only
635    // tolerate_unknown_long = true accepts unknown double-dash tokens as
636    // positional. This is the dangerous form; reserved for tools like AWS
637    // CLI whose long-flag surface is genuinely unbounded.
638
639    static LONG_ONLY_POLICY: FlagPolicy = FlagPolicy {
640        standalone: WordSet::flags(&["--help"]),
641        valued: WordSet::flags(&[]),
642        bare: false,
643        max_positional: None,
644        tolerance: FlagTolerance { unknown: UnknownTolerance::Long, numeric_dash: false, single_dash_words: false },
645    };
646
647    #[test]
648    fn long_only_accepts_unknown_double_dash() {
649        assert!(check(&toks(&["aws", "--some-aws-flag"]), &LONG_ONLY_POLICY));
650    }
651
652    #[test]
653    fn long_only_accepts_unknown_eq_form() {
654        assert!(check(&toks(&["aws", "--filter=Name=tag,Values=foo"]), &LONG_ONLY_POLICY,));
655    }
656
657    #[test]
658    fn long_only_denies_unknown_short_dash() {
659        assert!(!check(&toks(&["aws", "-x"]), &LONG_ONLY_POLICY));
660    }
661
662    // Both tolerances false: strict
663
664    static STRICT_POLICY: FlagPolicy = FlagPolicy {
665        standalone: WordSet::flags(&["--help"]),
666        valued: WordSet::flags(&[]),
667        bare: false,
668        max_positional: None,
669        tolerance: FlagTolerance::strict(),
670    };
671
672    #[test]
673    fn strict_denies_unknown_short() {
674        assert!(!check(&toks(&["foo", "-evil"]), &STRICT_POLICY));
675    }
676
677    #[test]
678    fn strict_denies_unknown_long() {
679        assert!(!check(&toks(&["foo", "--evil"]), &STRICT_POLICY));
680    }
681
682    #[test]
683    fn strict_known_flag_passes() {
684        assert!(check(&toks(&["foo", "--help"]), &STRICT_POLICY));
685    }
686
687    #[test]
688    fn both_tolerances_with_max_positional() {
689        let policy = FlagPolicy {
690            standalone: WordSet::flags(&["-n"]),
691            valued: WordSet::flags(&[]),
692            bare: true,
693            max_positional: Some(2),
694            tolerance: FlagTolerance { unknown: UnknownTolerance::Both, numeric_dash: false, single_dash_words: false },
695        };
696        assert!(check(&toks(&["echo", "--unknown", "hello"]), &policy));
697        assert!(!check(&toks(&["echo", "--a", "--b", "--c"]), &policy));
698    }
699
700    static NUMERIC_DASH_POLICY: FlagPolicy = FlagPolicy {
701        standalone: WordSet::flags(&["--help", "--quiet", "--verbose", "--version", "-V", "-h", "-q", "-v", "-z"]),
702        valued: WordSet::flags(&["--bytes", "--lines", "-c", "-n"]),
703        bare: true,
704        max_positional: None,
705        tolerance: FlagTolerance { numeric_dash: true, ..FlagTolerance::strict() },
706    };
707
708    #[test]
709    fn numeric_dash_single_digit() {
710        assert!(check(&toks(&["head", "-5"]), &NUMERIC_DASH_POLICY));
711    }
712
713    #[test]
714    fn numeric_dash_multi_digit() {
715        assert!(check(&toks(&["head", "-20"]), &NUMERIC_DASH_POLICY));
716    }
717
718    #[test]
719    fn numeric_dash_large_number() {
720        assert!(check(&toks(&["head", "-1000"]), &NUMERIC_DASH_POLICY));
721    }
722
723    #[test]
724    fn numeric_dash_with_file_arg() {
725        assert!(check(&toks(&["head", "-20", "file.txt"]), &NUMERIC_DASH_POLICY));
726    }
727
728    #[test]
729    fn numeric_dash_with_other_flags() {
730        assert!(check(&toks(&["head", "-q", "-20", "file.txt"]), &NUMERIC_DASH_POLICY));
731    }
732
733    #[test]
734    fn numeric_dash_zero() {
735        assert!(check(&toks(&["head", "-0"]), &NUMERIC_DASH_POLICY));
736    }
737
738    #[test]
739    fn numeric_dash_still_rejects_unknown_flags() {
740        assert!(!check(&toks(&["head", "-x"]), &NUMERIC_DASH_POLICY));
741    }
742
743    #[test]
744    fn numeric_dash_rejects_mixed_alpha_num() {
745        assert!(!check(&toks(&["head", "-20x"]), &NUMERIC_DASH_POLICY));
746    }
747
748    #[test]
749    fn numeric_dash_disabled_rejects_multi_digit() {
750        assert!(!check(&toks(&["grep", "-20", "pattern"]), &TEST_POLICY));
751    }
752
753    static WORDS_POLICY: FlagPolicy = FlagPolicy {
754        standalone: WordSet::flags(&["-a", "-f", "-i", "-ifd0"]),
755        valued: WordSet::flags(&["-ext"]),
756        bare: false,
757        max_positional: None,
758        tolerance: FlagTolerance { single_dash_words: true, ..FlagTolerance::strict() },
759    };
760
761    #[test]
762    fn single_dash_words_never_split_a_word_into_letters() {
763        assert!(!check(&toks(&["exiftool", "-if", "system(1)", "a.jpg"]), &WORDS_POLICY));
764        assert!(!check(&toks(&["exiftool", "-fa", "a.jpg"]), &WORDS_POLICY));
765        assert!(check(&toks(&["exiftool", "-fa", "a.jpg"]), &FlagPolicy { tolerance: FlagTolerance::strict(), ..WORDS_POLICY }));
766    }
767
768    #[test]
769    fn single_dash_words_accept_listed_words_values_and_stdin() {
770        assert!(check(&toks(&["exiftool", "-ifd0", "-a", "-ext", "jpg", "a.jpg"]), &WORDS_POLICY));
771        assert!(check(&toks(&["exiftool", "-i", "-f", "-"]), &WORDS_POLICY));
772    }
773
774    #[test]
775    fn single_dash_words_under_short_tolerance_count_unknowns_as_positionals() {
776        let policy = FlagPolicy {
777            max_positional: Some(1),
778            tolerance: FlagTolerance { unknown: UnknownTolerance::Short, single_dash_words: true, numeric_dash: false },
779            ..WORDS_POLICY
780        };
781        assert!(check(&toks(&["exiftool", "-if"]), &policy));
782        assert!(!check(&toks(&["exiftool", "-if", "-zz"]), &policy));
783    }
784
785    #[test]
786    fn looks_like_path_accepts_relative() {
787        assert!(looks_like_path("./Tiltfile"));
788        assert!(looks_like_path("path/to/file"));
789    }
790
791    #[test]
792    fn looks_like_path_accepts_dotted() {
793        assert!(looks_like_path("Tiltfile.dev"));
794        assert!(looks_like_path("file.rb"));
795    }
796
797    #[test]
798    fn looks_like_path_accepts_stdin_dash() {
799        assert!(looks_like_path("-"));
800    }
801
802    #[test]
803    fn looks_like_path_rejects_flag() {
804        assert!(!looks_like_path("--help"));
805        assert!(!looks_like_path("-x"));
806    }
807
808    #[test]
809    fn looks_like_path_rejects_bare_word() {
810        assert!(!looks_like_path("Tiltfile"));
811        assert!(!looks_like_path("up"));
812    }
813
814    #[test]
815    fn looks_like_path_rejects_empty() {
816        assert!(!looks_like_path(""));
817    }
818
819    #[test]
820    fn positional_shape_path_matches() {
821        assert!(PositionalShape::Path.matches("./file.rb"));
822        assert!(!PositionalShape::Path.matches("--flag"));
823    }
824
825    #[test]
826    fn positional_shape_from_name() {
827        assert_eq!(PositionalShape::from_name("path"), Some(PositionalShape::Path));
828        assert_eq!(PositionalShape::from_name("nope"), None);
829    }
830
831    #[test]
832    fn a_vec_of_flags_answers_short_lookups_as_its_slice_does() {
833        let lists: [&[&str]; 3] = [&[], &["-x", "--long", "-y"], &["--x", "-", "-xy"]];
834        for list in lists {
835            let flags: Vec<String> = list.iter().map(|s| (*s).to_string()).collect();
836            for byte in 0..=u8::MAX {
837                let expected = list.iter().any(|f| f.len() == 2 && f.as_bytes()[1] == byte);
838                assert_eq!(flags.contains_short(byte), expected, "{list:?} byte {byte}");
839                assert_eq!(flags.as_slice().contains_short(byte), expected, "{list:?} byte {byte}");
840            }
841        }
842    }
843
844    #[test]
845    fn an_opaque_probe_is_consumed_as_a_flag_value_where_other_options_are_not() {
846        let next = |w: &str| consumes_next_value(Some(&Token::from_test(w)));
847        assert!(next(crate::cst::opaque::FLAG_PROBE));
848        assert!(next(crate::cst::opaque::SHORT_PROBE));
849        assert!(!next("--require=evil.js"));
850        assert!(!next("-%x"));
851        assert!(next("-5"));
852        assert!(next("-"));
853        assert!(!consumes_next_value(None));
854    }
855}