Skip to main content

safe_chains/registry/
policy.rs

1use crate::parse::Token;
2use crate::policy::{FlagSet, FlagTolerance, UnknownTolerance, check_flags, consumes_next_value, count_positionals, takes_next_word};
3use crate::verdict::{SafetyLevel, Verdict};
4
5use super::types::{DispatchKind, PassthroughSpec, TomlLevel, TomlPassthrough};
6
7#[derive(Debug, Clone)]
8pub struct OwnedPolicy {
9    pub standalone: Vec<String>,
10    pub valued: Vec<String>,
11    pub bare: bool,
12    pub max_positional: Option<usize>,
13    pub min_positional: Option<usize>,
14    pub tolerance: FlagTolerance,
15    pub passthrough: Option<Box<PassthroughSpec>>,
16}
17
18impl OwnedPolicy {
19    pub(super) fn allow_all() -> Self {
20        OwnedPolicy {
21            standalone: Vec::new(),
22            valued: Vec::new(),
23            bare: true,
24            max_positional: None,
25            min_positional: None,
26            tolerance: FlagTolerance { unknown: UnknownTolerance::Both, ..FlagTolerance::strict() },
27            passthrough: None,
28        }
29    }
30
31    pub(super) fn deny_all() -> Self {
32        OwnedPolicy {
33            standalone: Vec::new(),
34            valued: Vec::new(),
35            bare: false,
36            max_positional: Some(0),
37            min_positional: None,
38            tolerance: FlagTolerance::default(),
39            passthrough: None,
40        }
41    }
42}
43
44/// Whether the command's policy lists `flag` as standalone in any of its scopes, so the flag takes
45/// a value only glued or after `=`. The path gate consumes the next word by the same rule the
46/// policy walker does (`policy::takes_next_word`). `cmd` is already canonicalized by the caller.
47pub(crate) fn declares_standalone(cmd: &str, flag: &str) -> bool {
48    super::CUSTOM_REGISTRY
49        .get(cmd)
50        .or_else(|| super::TOML_REGISTRY.get(cmd))
51        .is_some_and(|spec| spec.kind.declares_standalone(flag))
52}
53
54impl DispatchKind {
55    /// Whether any scope of this command lists `flag` as standalone.
56    pub(super) fn declares_standalone(&self, flag: &str) -> bool {
57        let lists = |flags: &[String]| flags.iter().any(|f| f == flag);
58        match self {
59            DispatchKind::Policy { policy, .. }
60            | DispatchKind::RequireAny { policy, .. }
61            | DispatchKind::WriteFlagged { policy, .. }
62            | DispatchKind::Executor { policy, .. } => lists(&policy.standalone),
63            DispatchKind::FirstArg { standalone, .. } | DispatchKind::Wrapper { standalone, .. } => lists(standalone),
64            DispatchKind::Branching { pre_standalone, subs, .. } => {
65                lists(pre_standalone) || subs.iter().any(|sub| sub.kind.declares_standalone(flag))
66            }
67            DispatchKind::VerbChain(spec) => lists(&spec.main_standalone),
68            DispatchKind::Custom { subs, handler_policies, .. } => {
69                subs.iter().any(|sub| sub.kind.declares_standalone(flag))
70                    || handler_policies.values().any(|policy| lists(&policy.standalone))
71            }
72            DispatchKind::DelegateAfterSeparator(_) | DispatchKind::DelegateSkip { .. } => false,
73        }
74    }
75}
76
77pub(super) fn build_passthrough(toml: TomlPassthrough) -> Box<PassthroughSpec> {
78    let policy = super::build::build_policy(
79        toml.standalone, toml.valued, toml.optional_valued, toml.bare, toml.max_positional, toml.tolerate_unknown_short,
80        toml.tolerate_unknown_long, toml.numeric_dash,
81    );
82    let mut require_any = toml.require_any;
83    if let Some(guard) = toml.guard {
84        require_any.push(guard);
85    }
86    if let Some(short) = toml.guard_short {
87        require_any.push(short);
88    }
89    let level: SafetyLevel = toml.level.unwrap_or(TomlLevel::Inert).into();
90    Box::new(PassthroughSpec { policy, require_any, level })
91}
92
93fn has_unvalued_flag(tokens: &[Token], policy: &OwnedPolicy) -> bool {
94    let (standalone, valued) = (policy.standalone.as_slice(), policy.valued.as_slice());
95    for (i, token) in tokens.iter().enumerate().skip(1) {
96        let t = token.as_str();
97        if !t.starts_with('-') {
98            continue;
99        }
100        if takes_next_word(standalone, valued, t) {
101            if !consumes_next_value(tokens.get(i + 1)) {
102                return true;
103            }
104            continue;
105        }
106        if !policy.tolerance.single_dash_words {
107            let bytes = t.as_bytes();
108            for (j, &b) in bytes.iter().enumerate().skip(1) {
109                if standalone.contains_short(b) {
110                    continue;
111                }
112                if valued.contains_short(b) {
113                    if j + 1 == bytes.len() && !consumes_next_value(tokens.get(i + 1)) {
114                        return true;
115                    }
116                    break;
117                }
118                break;
119            }
120        }
121    }
122    false
123}
124
125pub(super) fn check_with_passthrough(tokens: &[Token], policy: &OwnedPolicy, base_level: SafetyLevel) -> Verdict {
126    if let Some(pass) = &policy.passthrough
127        && let Some(rel) = tokens[1..].iter().position(|t| t == "--")
128    {
129        let sep = rel + 1;
130        let prefix = &tokens[..sep];
131        let tail = &tokens[sep..];
132        if !check_owned(prefix, policy)
133            || has_unvalued_flag(prefix, policy)
134            || tail[1..].iter().any(|t| t == "--")
135            || !check_owned(tail, &pass.policy)
136            || has_unvalued_flag(tail, &pass.policy)
137        {
138            return Verdict::Denied;
139        }
140        let guarded = pass.require_any.is_empty()
141            || flag_given(tail, &pass.policy, &pass.require_any)
142            || flag_given(prefix, policy, &pass.require_any);
143        return if guarded { Verdict::Allowed(pass.level) } else { Verdict::Denied };
144    }
145    if check_owned(tokens, policy) {
146        if let Some(pass) = &policy.passthrough {
147            if has_unvalued_flag(tokens, policy) {
148                return Verdict::Denied;
149            }
150            if flag_given(tokens, policy, &pass.require_any) {
151                return Verdict::Allowed(pass.level);
152            }
153        }
154        Verdict::Allowed(base_level)
155    } else {
156        Verdict::Denied
157    }
158}
159
160pub(super) fn check_owned(tokens: &[Token], policy: &OwnedPolicy) -> bool {
161    let (standalone, valued) = (policy.standalone.as_slice(), policy.valued.as_slice());
162    !(policy.tolerance.reads_commands.stdin && crate::cst::stdin_fed::fed())
163        && check_flags(tokens, standalone, valued, policy.bare, policy.max_positional, policy.tolerance)
164        && policy
165            .min_positional
166            .is_none_or(|min| count_positionals(tokens, standalone, valued, policy.tolerance).is_some_and(|n| n >= min))
167}
168
169/// Reads `reads_commands_from`: `"plus"` limits a `+word` operand to a line number, and `"stdin"`
170/// refuses the command when anything feeds its standard input.
171pub(super) fn reads_commands_from(tolerance: &mut FlagTolerance, command: &str, sources: &[String]) -> Result<(), String> {
172    for source in sources {
173        match source.as_str() {
174            "plus" => tolerance.reads_commands.plus = true,
175            "stdin" => tolerance.reads_commands.stdin = true,
176            other => return Err(format!("command '{command}': unknown reads_commands_from source `{other}` (known: plus, stdin)")),
177        }
178    }
179    Ok(())
180}
181
182/// Whether one of `wanted` is given AS A FLAG: not as the value of the flag before it, not glued
183/// into a short cluster after a flag that takes the rest as its value (`-rm` is `-r m`), and not
184/// after `--`. A valued flag with nothing glued to it takes the next word whatever it looks like,
185/// as getopt does: `make -f -n` reads a makefile named `-n`.
186///
187/// A required flag that only appears to be present is how a guarded sub runs its unguarded form:
188/// `jj describe -rm` names revision `m` and opens the editor.
189pub(super) fn flag_given(tokens: &[Token], policy: &OwnedPolicy, wanted: &[String]) -> bool {
190    let (standalone, valued) = (policy.standalone.as_slice(), policy.valued.as_slice());
191    let wants = |flag: &str| wanted.iter().any(|w| w == flag);
192    let mut i = 1;
193    while i < tokens.len() {
194        let t = tokens[i].as_str();
195        if t == "--" {
196            return false;
197        }
198        i += 1;
199        if wants(t) {
200            return true;
201        }
202        if !t.starts_with('-') || t == "-" {
203            continue;
204        }
205        if t.starts_with("--") {
206            let name = t.split_once('=').map_or(t, |(name, _)| name);
207            if wants(name) {
208                return true;
209            }
210            if !t.contains('=') && takes_next_word(standalone, valued, name) {
211                i += 1;
212            }
213            continue;
214        }
215        if policy.tolerance.single_dash_words || valued.contains_flag(t) {
216            if takes_next_word(standalone, valued, t) {
217                i += 1;
218            }
219            continue;
220        }
221        let bytes = t.as_bytes();
222        for (j, &b) in bytes.iter().enumerate().skip(1) {
223            if wanted.iter().any(|w| w.as_bytes() == [b'-', b]) {
224                return true;
225            }
226            if valued.contains_short(b) {
227                if j == bytes.len() - 1 {
228                    i += 1;
229                }
230                break;
231            }
232            if !standalone.contains_short(b) {
233                break;
234            }
235        }
236    }
237    false
238}
239
240/// Returns the first non-flag token after `tokens[0]`, treating the
241/// policy's `valued` flags as consuming the next argument and its
242/// `standalone` flags as zero-arg. `--` ends flag scanning. `-` is a
243/// positional (the conventional stdin marker). Used by fallback
244/// grammars that want to apply a `PositionalShape` predicate to the
245/// first positional without re-implementing flag walking.
246pub(super) fn min_positional_fits(parent: &str, toml: &super::types::TomlSub, policy_free: bool) -> Result<(), String> {
247    let Some(min) = toml.min_positional else { return Ok(()) };
248    if policy_free || !toml.sub.is_empty() || !toml.first_arg.is_empty() || !toml.credential_first_arg.is_empty() {
249        return Err(format!("command '{parent}' sub `{}`: min_positional needs a flag policy to count operands against", toml.name));
250    }
251    match toml.max_positional {
252        Some(max) if min > max => Err(format!("command '{parent}' sub `{}`: min_positional {min} exceeds max_positional {max}", toml.name)),
253        _ => Ok(()),
254    }
255}
256
257pub(super) fn first_positional<'a>(tokens: &'a [Token], policy: &OwnedPolicy) -> Option<&'a str> {
258    first_positional_at(tokens, policy).map(|(_, s)| s)
259}
260
261/// [`first_positional`], plus WHERE it was found.
262///
263/// The index is what lets a caller split an invocation at the executor: everything up to and
264/// including that token is the command's own grammar and can be checked against its flag policy,
265/// while everything after it is the SCRIPT's argv and cannot. `dispatch_executor` needs exactly
266/// that split — see the comment there.
267///
268/// Expressed as one walk with `first_positional` delegating to it, rather than two functions that
269/// scan independently: the value and its index must never disagree about which token is the
270/// executor, and two copies of this loop is how they would.
271pub(super) fn first_positional_at<'a>(tokens: &'a [Token], policy: &OwnedPolicy) -> Option<(usize, &'a str)> {
272    let standalone = policy.standalone.as_slice();
273    let valued = policy.valued.as_slice();
274    let mut i = 1;
275    while i < tokens.len() {
276        let t = &tokens[i];
277        let s = t.as_str();
278        if s == "--" {
279            return tokens.get(i + 1).map(|t| (i + 1, t.as_str()));
280        }
281        if s == "-" || !s.starts_with('-') {
282            return Some((i, s));
283        }
284        if standalone.contains_flag(s) {
285            i += 1;
286            continue;
287        }
288        if valued.contains_flag(s) {
289            i += 2;
290            continue;
291        }
292        if let Some((flag, _)) = s.split_once('=')
293            && valued.contains_flag(flag)
294        {
295            i += 1;
296            continue;
297        }
298        // Unknown flag: bail out — it's the policy validator's job to
299        // accept or reject. Either way, we've reached the end of the
300        // recognized flag run without finding a positional.
301        return None;
302    }
303    None
304}
305
306#[cfg(test)]
307mod tests {
308    use super::*;
309    use crate::parse::Token;
310    use crate::policy::FlagTolerance;
311
312    fn toks(words: &[&str]) -> Vec<Token> {
313        words.iter().map(|s| Token::from_test(s)).collect()
314    }
315
316    fn policy(standalone: &[&str], valued: &[&str], max_positional: Option<usize>) -> OwnedPolicy {
317        OwnedPolicy {
318            standalone: standalone.iter().map(|s| s.to_string()).collect(),
319            valued: valued.iter().map(|s| s.to_string()).collect(),
320            bare: true,
321            max_positional,
322            min_positional: None,
323            tolerance: FlagTolerance::strict(),
324            passthrough: None,
325        }
326    }
327
328    #[test]
329    fn first_positional_finds_bare_arg() {
330        let p = policy(&[], &[], None);
331        let tokens = toks(&["cmd", "arg"]);
332        assert_eq!(first_positional(&tokens, &p), Some("arg"));
333    }
334
335    #[test]
336    fn first_positional_skips_standalone_flags() {
337        let p = policy(&["--verbose"], &[], None);
338        let tokens = toks(&["cmd", "--verbose", "file"]);
339        assert_eq!(first_positional(&tokens, &p), Some("file"));
340    }
341
342    #[test]
343    fn first_positional_skips_valued_flag_value() {
344        let p = policy(&[], &["--type"], None);
345        let tokens = toks(&["cmd", "--type", "erb", "file.erb"]);
346        assert_eq!(first_positional(&tokens, &p), Some("file.erb"));
347    }
348
349    #[test]
350    fn first_positional_skips_valued_flag_eq_form() {
351        let p = policy(&[], &["--type"], None);
352        let tokens = toks(&["cmd", "--type=erb", "file.erb"]);
353        assert_eq!(first_positional(&tokens, &p), Some("file.erb"));
354    }
355
356    #[test]
357    fn first_positional_treats_double_dash_as_terminator() {
358        let p = policy(&["--verbose"], &[], None);
359        let tokens = toks(&["cmd", "--", "--verbose"]);
360        // After --, the very next token (even if flag-shaped) is positional.
361        assert_eq!(first_positional(&tokens, &p), Some("--verbose"));
362    }
363
364    #[test]
365    fn first_positional_treats_lone_dash_as_positional() {
366        let p = policy(&[], &[], None);
367        let tokens = toks(&["cmd", "-"]);
368        assert_eq!(first_positional(&tokens, &p), Some("-"));
369    }
370
371    #[test]
372    fn first_positional_returns_none_for_no_args() {
373        let p = policy(&[], &[], None);
374        let tokens = toks(&["cmd"]);
375        assert_eq!(first_positional(&tokens, &p), None);
376    }
377
378    #[test]
379    fn first_positional_returns_none_for_only_flags() {
380        let p = policy(&["--help"], &[], None);
381        let tokens = toks(&["cmd", "--help"]);
382        assert_eq!(first_positional(&tokens, &p), None);
383    }
384
385    #[test]
386    fn first_positional_returns_none_on_unknown_flag() {
387        // Bails out at the unknown flag rather than guessing — the policy
388        // validator is responsible for rejecting or accepting it.
389        let p = policy(&[], &[], None);
390        let tokens = toks(&["cmd", "--unknown", "file"]);
391        assert_eq!(first_positional(&tokens, &p), None);
392    }
393
394    /// Property tests for `first_positional` / `first_positional_at` / `check_owned`.
395    ///
396    /// Each property pins an invariant of the function pair rather than an example. They share
397    /// the in-module `policy`/`toks` builders and run under `proptest` so the synthesized tokens
398    /// stay inside the alphabet those builders already understand.
399    mod prop {
400        use super::*;
401        use proptest::prelude::*;
402
403        /// A flag-shaped tail token (regex covers `-`, `--`, and `--name=value` shapes).
404        const FLAG_RE: &str = "--?[a-zA-Z][a-zA-Z0-9._-]{0,7}(=[a-zA-Z0-9._-]{1,8})?";
405        /// A never-flag-shaped token (no leading `-`, otherwise printable).
406        const NON_FLAG_RE: &str = "[a-zA-Z][a-zA-Z0-9._]{0,7}";
407
408        fn toks_owned(words: &[String]) -> Vec<Token> {
409            words.iter().cloned().map(Token::from_raw).collect()
410        }
411
412        /// Reference implementation of `first_positional_at` for the case where BOTH flag lists
413        /// are empty. In that mode the documented behavior reduces to: walk forward, return
414        /// `(i + 1, next)` after a bare `--`, return `(i, s)` for `-` or any non-`-`-starting
415        /// token, and return `None` on any other flag-shaped token. Used as the oracle.
416        fn oracle_first_positional_at(tokens: &[Token]) -> Option<(usize, &str)> {
417            // Skips index 0 and returns the same answer the documented walk would on an empty
418            // grammar: look at one token, then stop. Encoded as `if let` rather than a loop
419            // because every branch decides the result on the first token and a loop would loop
420            // at most once.
421            let (offset, t) = tokens.iter().enumerate().nth(1)?;
422            let s = t.as_str();
423            if s == "--" {
424                let i = offset + 1;
425                return tokens.get(i).map(|t| (i, t.as_str()));
426            }
427            if s == "-" || !s.starts_with('-') {
428                return Some((offset, s));
429            }
430            None
431        }
432
433        proptest! {
434            /// Consistency / roundtrip: `first_positional` delegates to `first_positional_at`,
435            /// so the string it returns must equal the string half of the indexed pair for
436            /// EVERY (tokens, policy) pair. A regression that splits the two walks apart —
437            /// the very thing the docstring warns against — fails here.
438            #[test]
439            fn first_positional_and_first_positional_at_agree_on_the_returned_string(
440                tail in proptest::collection::vec("(-|--|--?[a-zA-Z][a-zA-Z0-9._-]{0,7}(=[a-zA-Z0-9._-]{1,8})?|[a-zA-Z][a-zA-Z0-9._]{0,7})", 0..8),
441                standalone in proptest::collection::vec(FLAG_RE, 0..4),
442                valued in proptest::collection::vec(FLAG_RE, 0..4),
443            ) {
444                let mut words = vec!["cmd".to_string()];
445                words.extend(tail);
446                let tokens = toks_owned(&words);
447                let p = policy(
448                    &standalone.iter().map(String::as_str).collect::<Vec<_>>(),
449                    &valued.iter().map(String::as_str).collect::<Vec<_>>(),
450                    None,
451                );
452                let expected = first_positional_at(&tokens, &p).map(|(_, s)| s.to_string());
453                let actual = first_positional(&tokens, &p).map(|s| s.to_string());
454                proptest::prop_assert_eq!(actual, expected);
455            }
456
457            /// Index honesty: the index returned by `first_positional_at` must really point
458            /// at the token whose text it pairs with. The walk stores `(i, s)` as one
459            /// expression so they cannot disagree by construction, and this property pins
460            /// that coupling against any future change that recomputes one half from a
461            /// different loop variable.
462            #[test]
463            fn first_positional_at_index_points_at_the_returned_token(
464                standalone in proptest::collection::vec(FLAG_RE, 0..3),
465                valued in proptest::collection::vec(FLAG_RE, 0..3),
466                tail in proptest::collection::vec(
467                    "(--|--?[a-zA-Z][a-zA-Z0-9._-]{0,7}(=[a-zA-Z0-9._-]{1,8})?|[a-zA-Z][a-zA-Z0-9._]{0,7})",
468                    1..6,
469                ),
470            ) {
471                let mut words = vec!["cmd".to_string()];
472                words.extend(tail);
473                let tokens = toks_owned(&words);
474                let p = policy(
475                    &standalone.iter().map(String::as_str).collect::<Vec<_>>(),
476                    &valued.iter().map(String::as_str).collect::<Vec<_>>(),
477                    None,
478                );
479                if let Some((i, s)) = first_positional_at(&tokens, &p) {
480                    proptest::prop_assert!(i < tokens.len(), "index {} past tokens.len()={}", i, tokens.len());
481                    proptest::prop_assert_eq!(tokens[i].as_str(), s);
482                }
483            }
484
485            /// Oracle / differential: with both `standalone` and `valued` empty the walk
486            /// collapses to a four-line scan. This property states that the contracted
487            /// implementation equals the inlined reference for EVERY generated shape, so
488            /// a refactor that introduced extra logic for the empty-grammar case would be
489            /// caught — the empty case is the one that has to match the docstring.
490            #[test]
491            fn first_positional_with_empty_grammars_matches_a_simple_scan(
492                tail in proptest::collection::vec(
493                    "(-|--|--?[a-zA-Z][a-zA-Z0-9._-]{0,7}(=[a-zA-Z0-9._-]{1,8})?|[a-zA-Z][a-zA-Z0-9._]{0,7})",
494                    0..6,
495                ),
496            ) {
497                let mut words = vec!["cmd".to_string()];
498                words.extend(tail);
499                let tokens = toks_owned(&words);
500                let p = policy(&[], &[], None);
501                let oracle = oracle_first_positional_at(&tokens).map(|(i, s)| (i, s.to_string()));
502                let actual = first_positional_at(&tokens, &p).map(|(i, s)| (i, s.to_string()));
503                proptest::prop_assert_eq!(actual, oracle);
504            }
505
506            /// Monotonicity: prepending a token that the policy declares as a STANDALONE flag
507            /// does not change the first positional found later. The walk consumes a standalone
508            /// in exactly one step (`i += 1`), so the rest of the scan is identical; the
509            /// property locks that "additive, not destructive" behavior in. The prepended flag
510            /// is taken from the SAME generated standalone list so we are asserting on real
511            /// acceptance, not on unknown-flag bailouts.
512            #[test]
513            fn prepending_a_known_standalone_flag_does_not_change_the_first_positional(
514                standalone in proptest::collection::vec(FLAG_RE, 1..4),
515                tail in proptest::collection::vec(NON_FLAG_RE, 0..5),
516            ) {
517                let prefix_token = standalone[0].clone();
518                let mut base = vec!["cmd".to_string()];
519                base.extend(tail.clone());
520                let base_tokens = toks_owned(&base);
521                let p = policy(
522                    &standalone.iter().map(String::as_str).collect::<Vec<_>>(),
523                    &[],
524                    None,
525                );
526                let before = first_positional(&base_tokens, &p).map(|s| s.to_string());
527
528                let mut prefixed = vec!["cmd".to_string(), prefix_token];
529                prefixed.extend(tail);
530                let prefixed_tokens = toks_owned(&prefixed);
531                let after = first_positional(&prefixed_tokens, &p).map(|s| s.to_string());
532
533                proptest::prop_assert_eq!(after, before);
534            }
535        }
536    }
537}
538
539#[cfg(test)]
540mod flag_given_tests {
541    use super::*;
542    use proptest::prelude::*;
543
544    fn jj_like(min_positional: Option<usize>) -> OwnedPolicy {
545        OwnedPolicy {
546            standalone: vec!["--quiet".into(), "-a".into(), "-k".into()],
547            valued: vec!["--message".into(), "--revision".into(), "-m".into(), "-r".into()],
548            bare: true,
549            max_positional: None,
550            min_positional,
551            tolerance: FlagTolerance::strict(),
552            passthrough: None,
553        }
554    }
555
556    fn toks(words: &[&str]) -> Vec<Token> {
557        std::iter::once("cmd").chain(words.iter().copied()).map(Token::from_test).collect()
558    }
559
560    fn given(words: &[&str]) -> bool {
561        flag_given(&toks(words), &jj_like(None), &["--message".to_string(), "-m".to_string()])
562    }
563
564    #[test]
565    fn a_flag_is_given_in_each_of_its_spellings() {
566        for words in [&["-m", "x"][..], &["-mx"], &["--message", "x"], &["--message=x"], &["-km", "x"], &["-r", "@", "-m", "x"]] {
567            assert!(given(words), "{words:?}");
568        }
569    }
570
571    #[test]
572    fn a_flag_that_only_looks_given_is_not() {
573        for words in [
574            &[][..],
575            &["-rm"],
576            &["-r", "m"],
577            &["--", "-m", "x"],
578            &["--revision=-m"],
579            &["--revision", "m"],
580            &["m"],
581            &["-r", "-m"],
582            &["--revision", "-m"],
583            &["--revision", "--message"],
584            &["-ar", "-m"],
585            &["-r", "--message=x"],
586        ] {
587            assert!(!given(words), "{words:?}");
588        }
589    }
590
591    #[test]
592    fn a_required_word_matches_whole() {
593        let mut words = jj_like(None);
594        words.tolerance.single_dash_words = true;
595        let want = |w: &str| vec![w.to_string()];
596        assert!(flag_given(&toks(&["-statistics"]), &words, &want("-statistics")));
597        assert!(!flag_given(&toks(&["-statsonly"]), &words, &want("-s")));
598        assert!(flag_given(&toks(&["-", "bash"]), &jj_like(None), &want("-")));
599        assert!(!flag_given(&toks(&["--", "-"]), &jj_like(None), &want("-")));
600    }
601
602    #[test]
603    fn min_positional_counts_operands_not_flag_values() {
604        let p = jj_like(Some(1));
605        assert!(!check_owned(&toks(&["-m", "x"]), &p));
606        assert!(!check_owned(&toks(&["-m", "x", "-r", "src/a"]), &p));
607        assert!(check_owned(&toks(&["-m", "x", "src/a"]), &p));
608        assert!(check_owned(&toks(&["-m", "x", "--", "src/a"]), &p));
609        assert!(check_owned(&toks(&["-m", "x"]), &jj_like(None)));
610    }
611
612    #[test]
613    fn min_positional_is_named_in_the_reference() {
614        assert!(jj_like(Some(1)).flag_summary().ends_with("At least 1 positional argument"));
615        assert!(jj_like(Some(2)).flag_summary().ends_with("At least 2 positional arguments"));
616        assert!(!jj_like(None).flag_summary().contains("positional argument"));
617    }
618
619    fn demo(sub_fields: &str) -> Result<Vec<crate::registry::CommandSpec>, String> {
620        crate::registry::load_toml(&format!("[[command]]\nname = \"demo\"\n[[command.sub]]\nname = \"split\"\n{sub_fields}\n"), "test")
621    }
622
623    #[test]
624    fn min_positional_dispatches_through_a_loaded_definition() {
625        let specs = demo("level = \"SafeWrite\"\nrequire_any = [\"-m\"]\nmin_positional = 1\nvalued = [\"-m\", \"-r\"]").expect("loads");
626        let verdict = |words: &[&str]| crate::registry::dispatch_spec(&toks(words), &specs[0]);
627        assert_eq!(verdict(&["split", "-m", "x", "a"]), crate::verdict::Verdict::Allowed(crate::verdict::SafetyLevel::SafeWrite));
628        assert_eq!(verdict(&["split", "-m", "x"]), crate::verdict::Verdict::Denied);
629        assert_eq!(verdict(&["split", "-m", "x", "-r", "a"]), crate::verdict::Verdict::Denied);
630        assert_eq!(verdict(&["split", "a"]), crate::verdict::Verdict::Denied);
631    }
632
633    #[test]
634    fn min_positional_is_refused_where_nothing_would_count_operands() {
635        for fields in [
636            "min_positional = 1\nallow_all = true",
637            "min_positional = 1\nfirst_arg = [\"x\"]",
638            "min_positional = 1\nhandler = \"demo\"",
639            "level = \"SafeWrite\"\nmin_positional = 2\nmax_positional = 1",
640        ] {
641            let err = demo(fields).err().unwrap_or_else(|| panic!("{fields:?} loaded"));
642            assert!(err.contains("min_positional"), "{fields:?}: {err}");
643        }
644    }
645
646    #[derive(Debug, Clone)]
647    enum Unit {
648        Standalone(&'static str),
649        Valued(&'static str, &'static str),
650        Glued(&'static str),
651        Operand(&'static str),
652        Wanted(Vec<&'static str>),
653        End,
654    }
655
656    fn unit() -> impl Strategy<Value = Unit> {
657        let value = prop::sample::select(vec!["m", "x", "mx", "@-"]);
658        prop_oneof![
659            prop::sample::select(vec!["-a", "-k", "-ak", "--quiet"]).prop_map(Unit::Standalone),
660            (prop::sample::select(vec!["-r", "--revision", "-ar"]), prop::sample::select(vec!["m", "@-", "-m", "--message", "-k", "--"]))
661                .prop_map(|(f, v)| Unit::Valued(f, v)),
662            prop::sample::select(vec!["-rm", "-rx", "-arm", "--revision=m", "--revision=-m"]).prop_map(Unit::Glued),
663            value.prop_map(Unit::Operand),
664            prop::sample::select(vec![vec!["-m", "x"], vec!["-mx"], vec!["-am", "x"], vec!["--message", "m"], vec!["--message=m"]])
665                .prop_map(Unit::Wanted),
666            Just(Unit::End),
667        ]
668    }
669
670    proptest! {
671        #[test]
672        fn flag_given_matches_a_reading_unit_by_unit(units in prop::collection::vec(unit(), 0..8)) {
673            let mut words = Vec::new();
674            let mut expected = false;
675            let mut ended = false;
676            for u in &units {
677                match u {
678                    Unit::Standalone(f) | Unit::Glued(f) | Unit::Operand(f) => words.push(*f),
679                    Unit::Valued(f, v) => words.extend([*f, *v]),
680                    Unit::Wanted(w) => {
681                        expected |= !ended;
682                        words.extend(w.iter().copied());
683                    }
684                    Unit::End => {
685                        ended = true;
686                        words.push("--");
687                    }
688                }
689            }
690            prop_assert_eq!(given(&words), expected, "{:?}", words);
691        }
692    }
693}
694
695#[cfg(test)]
696mod passthrough_tests {
697    use super::*;
698    use crate::policy::FlagTolerance;
699    use proptest::prelude::*;
700
701    fn spec() -> OwnedPolicy {
702        let inner = |standalone: &[&str], valued: &[&str]| OwnedPolicy {
703            standalone: standalone.iter().map(|s| s.to_string()).collect(),
704            valued: valued.iter().map(|s| s.to_string()).collect(),
705            bare: false,
706            max_positional: Some(0),
707            min_positional: None,
708            tolerance: FlagTolerance::strict(),
709            passthrough: None,
710        };
711        let mut outer = inner(&["--all", "--check", "-q"], &["-p"]);
712        outer.bare = true;
713        outer.passthrough = Some(Box::new(PassthroughSpec {
714            policy: inner(&["--check", "--quiet", "-l"], &["--edition", "--color"]),
715            require_any: vec!["--check".to_string()],
716            level: SafetyLevel::SafeRead,
717        }));
718        outer
719    }
720
721    fn verdict(words: &[String]) -> Verdict {
722        let tokens: Vec<Token> = words.iter().cloned().map(Token::from_raw).collect();
723        check_with_passthrough(&tokens, &spec(), SafetyLevel::SafeWrite)
724    }
725
726    fn verdict_strs(words: &[&str]) -> Verdict {
727        let owned: Vec<String> = words.iter().map(|s| (*s).to_string()).collect();
728        verdict(&owned)
729    }
730
731    /// One whole unit of the passthrough grammar: a standalone flag or a valued flag with its value.
732    fn allowed_unit() -> impl Strategy<Value = Vec<&'static str>> {
733        prop_oneof![
734            prop::sample::select(vec!["--quiet", "-l", "--check"]).prop_map(|f| vec![f]),
735            prop::sample::select(vec!["--edition", "--color"])
736                .prop_flat_map(|f| { prop::sample::select(vec!["2024", "never", "always"]).prop_map(move |v| vec![f, v]) }),
737        ]
738    }
739
740    /// A token the passthrough lists do not hold: an unknown flag, a path or a bare word.
741    fn outsider() -> impl Strategy<Value = String> {
742        prop_oneof![
743            "--[a-z]{3,8}".prop_filter("not a listed flag", |f| !["--check", "--quiet", "--edition", "--color"].contains(&f.as_str())),
744            "-[a-km-z]{1,3}",
745            "[a-z]{1,6}(\\.rs)?",
746            "(/|~/)[a-z]{1,6}",
747            prop::sample::select(vec![
748                "--emit".to_string(),
749                "--backup".to_string(),
750                "--config=emit_mode=files".to_string(),
751                "--print-config".to_string(),
752            ]),
753        ]
754    }
755
756    fn assemble(units: &[Vec<&str>], outsider_at: Option<(usize, String)>) -> Vec<String> {
757        let mut words: Vec<String> = ["cmd", "--all", "--"].iter().map(|s| s.to_string()).collect();
758        words.push("--check".to_string());
759        for (i, unit) in units.iter().enumerate() {
760            if let Some((at, word)) = &outsider_at
761                && *at == i
762            {
763                words.push(word.clone());
764            }
765            words.extend(unit.iter().map(|s| s.to_string()));
766        }
767        if let Some((at, word)) = outsider_at
768            && at >= units.len()
769        {
770            words.push(word);
771        }
772        words
773    }
774
775    proptest! {
776        /// Never Allowed when the tail holds a token outside the passthrough lists, wherever it sits.
777        #[test]
778        fn a_tail_token_outside_the_passthrough_lists_is_never_allowed(
779            units in prop::collection::vec(allowed_unit(), 0..5),
780            at in 0usize..6,
781            word in outsider(),
782        ) {
783            let words = assemble(&units, Some((at, word)));
784            prop_assert_eq!(verdict(&words), Verdict::Denied, "{:?}", words);
785        }
786
787        /// The same tails without the outsider are approved at the passthrough's level, so the
788        /// property above cannot pass by denying everything.
789        #[test]
790        fn a_tail_of_listed_flags_with_the_guard_is_allowed_at_the_passthrough_level(
791            units in prop::collection::vec(allowed_unit(), 0..5),
792        ) {
793            let words = assemble(&units, None);
794            prop_assert_eq!(verdict(&words), Verdict::Allowed(SafetyLevel::SafeRead), "{:?}", words);
795        }
796
797        /// A valued flag at the end of the tail with no value is never Allowed.
798        #[test]
799        fn a_valued_flag_with_no_value_in_the_tail_is_never_allowed(
800            units in prop::collection::vec(allowed_unit(), 0..4),
801            flag in prop::sample::select(vec!["--edition", "--color"]),
802        ) {
803            let mut words = assemble(&units, None);
804            words.push(flag.to_string());
805            prop_assert_eq!(verdict(&words), Verdict::Denied, "{:?}", words);
806        }
807
808        /// A second `--` anywhere in the tail is never Allowed.
809        #[test]
810        fn a_second_separator_is_never_allowed(units in prop::collection::vec(allowed_unit(), 0..4)) {
811            let mut words = assemble(&units, None);
812            words.push("--".to_string());
813            prop_assert_eq!(verdict(&words), Verdict::Denied, "{:?}", words);
814        }
815    }
816
817    #[test]
818    fn an_unvalued_valued_flag_before_the_separator_is_denied() {
819        assert_eq!(verdict_strs(&["cmd", "-p", "--", "--check"]), Verdict::Denied);
820        assert_eq!(verdict_strs(&["cmd", "-qp", "--", "--check"]), Verdict::Denied);
821        assert_eq!(verdict_strs(&["cmd", "-p"]), Verdict::Denied);
822        assert_eq!(verdict_strs(&["cmd", "-p", "xp", "--", "--check"]), Verdict::Allowed(SafetyLevel::SafeRead));
823        assert_eq!(verdict_strs(&["cmd", "-qp", "xp", "--", "--check"]), Verdict::Allowed(SafetyLevel::SafeRead));
824        assert_eq!(verdict_strs(&["cmd", "-qpx", "--", "--check"]), Verdict::Allowed(SafetyLevel::SafeRead));
825        assert_eq!(verdict_strs(&["cmd", "--check", "--", "-l"]), Verdict::Allowed(SafetyLevel::SafeRead));
826        assert_eq!(verdict_strs(&["cmd", "--check"]), Verdict::Allowed(SafetyLevel::SafeRead));
827        assert_eq!(verdict_strs(&["cmd", "--all"]), Verdict::Allowed(SafetyLevel::SafeWrite));
828    }
829}