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};
3
4#[derive(Debug, Clone)]
5pub struct OwnedPolicy {
6    pub standalone: Vec<String>,
7    pub valued: Vec<String>,
8    pub bare: bool,
9    pub max_positional: Option<usize>,
10    pub min_positional: Option<usize>,
11    pub tolerance: FlagTolerance,
12}
13
14impl OwnedPolicy {
15    pub(super) fn allow_all() -> Self {
16        OwnedPolicy {
17            standalone: Vec::new(),
18            valued: Vec::new(),
19            bare: true,
20            max_positional: None,
21            min_positional: None,
22            tolerance: FlagTolerance { unknown: UnknownTolerance::Both, numeric_dash: false, single_dash_words: false },
23        }
24    }
25}
26
27pub(super) fn check_owned(tokens: &[Token], policy: &OwnedPolicy) -> bool {
28    let (standalone, valued) = (policy.standalone.as_slice(), policy.valued.as_slice());
29    check_flags(tokens, standalone, valued, policy.bare, policy.max_positional, policy.tolerance)
30        && policy
31            .min_positional
32            .is_none_or(|min| count_positionals(tokens, standalone, valued, policy.tolerance).is_some_and(|n| n >= min))
33}
34
35/// Whether one of `wanted` is given AS A FLAG: not as the value of the flag before it, not glued
36/// into a short cluster after a flag that takes the rest as its value (`-rm` is `-r m`), and not
37/// after `--`.
38///
39/// A required flag that only appears to be present is how a guarded sub runs its unguarded form:
40/// `jj describe -rm` names revision `m` and opens the editor.
41pub(super) fn flag_given(tokens: &[Token], policy: &OwnedPolicy, wanted: &[String]) -> bool {
42    let (standalone, valued) = (policy.standalone.as_slice(), policy.valued.as_slice());
43    let wants = |flag: &str| wanted.iter().any(|w| w == flag);
44    let mut i = 1;
45    while i < tokens.len() {
46        let t = tokens[i].as_str();
47        if t == "--" {
48            return false;
49        }
50        i += 1;
51        if wants(t) {
52            return true;
53        }
54        if !t.starts_with('-') || t == "-" {
55            continue;
56        }
57        if t.starts_with("--") {
58            let name = t.split_once('=').map_or(t, |(name, _)| name);
59            if wants(name) {
60                return true;
61            }
62            if !t.contains('=') && valued.contains_flag(name) && consumes_next_value(tokens.get(i)) {
63                i += 1;
64            }
65            continue;
66        }
67        if policy.tolerance.single_dash_words || valued.contains_flag(t) {
68            if valued.contains_flag(t) && consumes_next_value(tokens.get(i)) {
69                i += 1;
70            }
71            continue;
72        }
73        let bytes = t.as_bytes();
74        for (j, &b) in bytes.iter().enumerate().skip(1) {
75            if wanted.iter().any(|w| w.as_bytes() == [b'-', b]) {
76                return true;
77            }
78            if valued.contains_short(b) {
79                if j == bytes.len() - 1 && consumes_next_value(tokens.get(i)) {
80                    i += 1;
81                }
82                break;
83            }
84            if !standalone.contains_short(b) {
85                break;
86            }
87        }
88    }
89    false
90}
91
92/// Returns the first non-flag token after `tokens[0]`, treating the
93/// policy's `valued` flags as consuming the next argument and its
94/// `standalone` flags as zero-arg. `--` ends flag scanning. `-` is a
95/// positional (the conventional stdin marker). Used by fallback
96/// grammars that want to apply a `PositionalShape` predicate to the
97/// first positional without re-implementing flag walking.
98pub(super) fn min_positional_fits(parent: &str, toml: &super::types::TomlSub, policy_free: bool) -> Result<(), String> {
99    let Some(min) = toml.min_positional else { return Ok(()) };
100    if policy_free || !toml.sub.is_empty() || !toml.first_arg.is_empty() || !toml.credential_first_arg.is_empty() {
101        return Err(format!("command '{parent}' sub `{}`: min_positional needs a flag policy to count operands against", toml.name));
102    }
103    match toml.max_positional {
104        Some(max) if min > max => Err(format!("command '{parent}' sub `{}`: min_positional {min} exceeds max_positional {max}", toml.name)),
105        _ => Ok(()),
106    }
107}
108
109pub(super) fn first_positional<'a>(tokens: &'a [Token], policy: &OwnedPolicy) -> Option<&'a str> {
110    first_positional_at(tokens, policy).map(|(_, s)| s)
111}
112
113/// [`first_positional`], plus WHERE it was found.
114///
115/// The index is what lets a caller split an invocation at the executor: everything up to and
116/// including that token is the command's own grammar and can be checked against its flag policy,
117/// while everything after it is the SCRIPT's argv and cannot. `dispatch_executor` needs exactly
118/// that split — see the comment there.
119///
120/// Expressed as one walk with `first_positional` delegating to it, rather than two functions that
121/// scan independently: the value and its index must never disagree about which token is the
122/// executor, and two copies of this loop is how they would.
123pub(super) fn first_positional_at<'a>(tokens: &'a [Token], policy: &OwnedPolicy) -> Option<(usize, &'a str)> {
124    let standalone = policy.standalone.as_slice();
125    let valued = policy.valued.as_slice();
126    let mut i = 1;
127    while i < tokens.len() {
128        let t = &tokens[i];
129        let s = t.as_str();
130        if s == "--" {
131            return tokens.get(i + 1).map(|t| (i + 1, t.as_str()));
132        }
133        if s == "-" || !s.starts_with('-') {
134            return Some((i, s));
135        }
136        if standalone.contains_flag(s) {
137            i += 1;
138            continue;
139        }
140        if valued.contains_flag(s) {
141            i += 2;
142            continue;
143        }
144        if let Some((flag, _)) = s.split_once('=')
145            && valued.contains_flag(flag)
146        {
147            i += 1;
148            continue;
149        }
150        // Unknown flag: bail out — it's the policy validator's job to
151        // accept or reject. Either way, we've reached the end of the
152        // recognized flag run without finding a positional.
153        return None;
154    }
155    None
156}
157
158#[cfg(test)]
159mod tests {
160    use super::*;
161    use crate::parse::Token;
162    use crate::policy::FlagTolerance;
163
164    fn toks(words: &[&str]) -> Vec<Token> {
165        words.iter().map(|s| Token::from_test(s)).collect()
166    }
167
168    fn policy(standalone: &[&str], valued: &[&str], max_positional: Option<usize>) -> OwnedPolicy {
169        OwnedPolicy {
170            standalone: standalone.iter().map(|s| s.to_string()).collect(),
171            valued: valued.iter().map(|s| s.to_string()).collect(),
172            bare: true,
173            max_positional,
174            min_positional: None,
175            tolerance: FlagTolerance::strict(),
176        }
177    }
178
179    #[test]
180    fn first_positional_finds_bare_arg() {
181        let p = policy(&[], &[], None);
182        let tokens = toks(&["cmd", "arg"]);
183        assert_eq!(first_positional(&tokens, &p), Some("arg"));
184    }
185
186    #[test]
187    fn first_positional_skips_standalone_flags() {
188        let p = policy(&["--verbose"], &[], None);
189        let tokens = toks(&["cmd", "--verbose", "file"]);
190        assert_eq!(first_positional(&tokens, &p), Some("file"));
191    }
192
193    #[test]
194    fn first_positional_skips_valued_flag_value() {
195        let p = policy(&[], &["--type"], None);
196        let tokens = toks(&["cmd", "--type", "erb", "file.erb"]);
197        assert_eq!(first_positional(&tokens, &p), Some("file.erb"));
198    }
199
200    #[test]
201    fn first_positional_skips_valued_flag_eq_form() {
202        let p = policy(&[], &["--type"], None);
203        let tokens = toks(&["cmd", "--type=erb", "file.erb"]);
204        assert_eq!(first_positional(&tokens, &p), Some("file.erb"));
205    }
206
207    #[test]
208    fn first_positional_treats_double_dash_as_terminator() {
209        let p = policy(&["--verbose"], &[], None);
210        let tokens = toks(&["cmd", "--", "--verbose"]);
211        // After --, the very next token (even if flag-shaped) is positional.
212        assert_eq!(first_positional(&tokens, &p), Some("--verbose"));
213    }
214
215    #[test]
216    fn first_positional_treats_lone_dash_as_positional() {
217        let p = policy(&[], &[], None);
218        let tokens = toks(&["cmd", "-"]);
219        assert_eq!(first_positional(&tokens, &p), Some("-"));
220    }
221
222    #[test]
223    fn first_positional_returns_none_for_no_args() {
224        let p = policy(&[], &[], None);
225        let tokens = toks(&["cmd"]);
226        assert_eq!(first_positional(&tokens, &p), None);
227    }
228
229    #[test]
230    fn first_positional_returns_none_for_only_flags() {
231        let p = policy(&["--help"], &[], None);
232        let tokens = toks(&["cmd", "--help"]);
233        assert_eq!(first_positional(&tokens, &p), None);
234    }
235
236    #[test]
237    fn first_positional_returns_none_on_unknown_flag() {
238        // Bails out at the unknown flag rather than guessing — the policy
239        // validator is responsible for rejecting or accepting it.
240        let p = policy(&[], &[], None);
241        let tokens = toks(&["cmd", "--unknown", "file"]);
242        assert_eq!(first_positional(&tokens, &p), None);
243    }
244
245    /// Property tests for `first_positional` / `first_positional_at` / `check_owned`.
246    ///
247    /// Each property pins an invariant of the function pair rather than an example. They share
248    /// the in-module `policy`/`toks` builders and run under `proptest` so the synthesized tokens
249    /// stay inside the alphabet those builders already understand.
250    mod prop {
251        use super::*;
252        use proptest::prelude::*;
253
254        /// A flag-shaped tail token (regex covers `-`, `--`, and `--name=value` shapes).
255        const FLAG_RE: &str = "--?[a-zA-Z][a-zA-Z0-9._-]{0,7}(=[a-zA-Z0-9._-]{1,8})?";
256        /// A never-flag-shaped token (no leading `-`, otherwise printable).
257        const NON_FLAG_RE: &str = "[a-zA-Z][a-zA-Z0-9._]{0,7}";
258
259        fn toks_owned(words: &[String]) -> Vec<Token> {
260            words.iter().cloned().map(Token::from_raw).collect()
261        }
262
263        /// Reference implementation of `first_positional_at` for the case where BOTH flag lists
264        /// are empty. In that mode the documented behavior reduces to: walk forward, return
265        /// `(i + 1, next)` after a bare `--`, return `(i, s)` for `-` or any non-`-`-starting
266        /// token, and return `None` on any other flag-shaped token. Used as the oracle.
267        fn oracle_first_positional_at(tokens: &[Token]) -> Option<(usize, &str)> {
268            // Skips index 0 and returns the same answer the documented walk would on an empty
269            // grammar: look at one token, then stop. Encoded as `if let` rather than a loop
270            // because every branch decides the result on the first token and a loop would loop
271            // at most once.
272            let (offset, t) = tokens.iter().enumerate().nth(1)?;
273            let s = t.as_str();
274            if s == "--" {
275                let i = offset + 1;
276                return tokens.get(i).map(|t| (i, t.as_str()));
277            }
278            if s == "-" || !s.starts_with('-') {
279                return Some((offset, s));
280            }
281            None
282        }
283
284        proptest! {
285            /// Consistency / roundtrip: `first_positional` delegates to `first_positional_at`,
286            /// so the string it returns must equal the string half of the indexed pair for
287            /// EVERY (tokens, policy) pair. A regression that splits the two walks apart —
288            /// the very thing the docstring warns against — fails here.
289            #[test]
290            fn first_positional_and_first_positional_at_agree_on_the_returned_string(
291                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),
292                standalone in proptest::collection::vec(FLAG_RE, 0..4),
293                valued in proptest::collection::vec(FLAG_RE, 0..4),
294            ) {
295                let mut words = vec!["cmd".to_string()];
296                words.extend(tail);
297                let tokens = toks_owned(&words);
298                let p = policy(
299                    &standalone.iter().map(String::as_str).collect::<Vec<_>>(),
300                    &valued.iter().map(String::as_str).collect::<Vec<_>>(),
301                    None,
302                );
303                let expected = first_positional_at(&tokens, &p).map(|(_, s)| s.to_string());
304                let actual = first_positional(&tokens, &p).map(|s| s.to_string());
305                proptest::prop_assert_eq!(actual, expected);
306            }
307
308            /// Index honesty: the index returned by `first_positional_at` must really point
309            /// at the token whose text it pairs with. The walk stores `(i, s)` as one
310            /// expression so they cannot disagree by construction, and this property pins
311            /// that coupling against any future change that recomputes one half from a
312            /// different loop variable.
313            #[test]
314            fn first_positional_at_index_points_at_the_returned_token(
315                standalone in proptest::collection::vec(FLAG_RE, 0..3),
316                valued in proptest::collection::vec(FLAG_RE, 0..3),
317                tail in proptest::collection::vec(
318                    "(--|--?[a-zA-Z][a-zA-Z0-9._-]{0,7}(=[a-zA-Z0-9._-]{1,8})?|[a-zA-Z][a-zA-Z0-9._]{0,7})",
319                    1..6,
320                ),
321            ) {
322                let mut words = vec!["cmd".to_string()];
323                words.extend(tail);
324                let tokens = toks_owned(&words);
325                let p = policy(
326                    &standalone.iter().map(String::as_str).collect::<Vec<_>>(),
327                    &valued.iter().map(String::as_str).collect::<Vec<_>>(),
328                    None,
329                );
330                if let Some((i, s)) = first_positional_at(&tokens, &p) {
331                    proptest::prop_assert!(i < tokens.len(), "index {} past tokens.len()={}", i, tokens.len());
332                    proptest::prop_assert_eq!(tokens[i].as_str(), s);
333                }
334            }
335
336            /// Oracle / differential: with both `standalone` and `valued` empty the walk
337            /// collapses to a four-line scan. This property states that the contracted
338            /// implementation equals the inlined reference for EVERY generated shape, so
339            /// a refactor that introduced extra logic for the empty-grammar case would be
340            /// caught — the empty case is the one that has to match the docstring.
341            #[test]
342            fn first_positional_with_empty_grammars_matches_a_simple_scan(
343                tail in proptest::collection::vec(
344                    "(-|--|--?[a-zA-Z][a-zA-Z0-9._-]{0,7}(=[a-zA-Z0-9._-]{1,8})?|[a-zA-Z][a-zA-Z0-9._]{0,7})",
345                    0..6,
346                ),
347            ) {
348                let mut words = vec!["cmd".to_string()];
349                words.extend(tail);
350                let tokens = toks_owned(&words);
351                let p = policy(&[], &[], None);
352                let oracle = oracle_first_positional_at(&tokens).map(|(i, s)| (i, s.to_string()));
353                let actual = first_positional_at(&tokens, &p).map(|(i, s)| (i, s.to_string()));
354                proptest::prop_assert_eq!(actual, oracle);
355            }
356
357            /// Monotonicity: prepending a token that the policy declares as a STANDALONE flag
358            /// does not change the first positional found later. The walk consumes a standalone
359            /// in exactly one step (`i += 1`), so the rest of the scan is identical; the
360            /// property locks that "additive, not destructive" behavior in. The prepended flag
361            /// is taken from the SAME generated standalone list so we are asserting on real
362            /// acceptance, not on unknown-flag bailouts.
363            #[test]
364            fn prepending_a_known_standalone_flag_does_not_change_the_first_positional(
365                standalone in proptest::collection::vec(FLAG_RE, 1..4),
366                tail in proptest::collection::vec(NON_FLAG_RE, 0..5),
367            ) {
368                let prefix_token = standalone[0].clone();
369                let mut base = vec!["cmd".to_string()];
370                base.extend(tail.clone());
371                let base_tokens = toks_owned(&base);
372                let p = policy(
373                    &standalone.iter().map(String::as_str).collect::<Vec<_>>(),
374                    &[],
375                    None,
376                );
377                let before = first_positional(&base_tokens, &p).map(|s| s.to_string());
378
379                let mut prefixed = vec!["cmd".to_string(), prefix_token];
380                prefixed.extend(tail);
381                let prefixed_tokens = toks_owned(&prefixed);
382                let after = first_positional(&prefixed_tokens, &p).map(|s| s.to_string());
383
384                proptest::prop_assert_eq!(after, before);
385            }
386        }
387    }
388}
389
390#[cfg(test)]
391mod flag_given_tests {
392    use super::*;
393    use proptest::prelude::*;
394
395    fn jj_like(min_positional: Option<usize>) -> OwnedPolicy {
396        OwnedPolicy {
397            standalone: vec!["--quiet".into(), "-a".into(), "-k".into()],
398            valued: vec!["--message".into(), "--revision".into(), "-m".into(), "-r".into()],
399            bare: true,
400            max_positional: None,
401            min_positional,
402            tolerance: FlagTolerance::strict(),
403        }
404    }
405
406    fn toks(words: &[&str]) -> Vec<Token> {
407        std::iter::once("cmd").chain(words.iter().copied()).map(Token::from_test).collect()
408    }
409
410    fn given(words: &[&str]) -> bool {
411        flag_given(&toks(words), &jj_like(None), &["--message".to_string(), "-m".to_string()])
412    }
413
414    #[test]
415    fn a_flag_is_given_in_each_of_its_spellings() {
416        for words in [&["-m", "x"][..], &["-mx"], &["--message", "x"], &["--message=x"], &["-km", "x"], &["-r", "@", "-m", "x"]] {
417            assert!(given(words), "{words:?}");
418        }
419    }
420
421    #[test]
422    fn a_flag_that_only_looks_given_is_not() {
423        for words in [&[][..], &["-rm"], &["-r", "m"], &["--", "-m", "x"], &["--revision=-m"], &["--revision", "m"], &["m"]] {
424            assert!(!given(words), "{words:?}");
425        }
426    }
427
428    #[test]
429    fn a_required_word_matches_whole() {
430        let mut words = jj_like(None);
431        words.tolerance.single_dash_words = true;
432        let want = |w: &str| vec![w.to_string()];
433        assert!(flag_given(&toks(&["-statistics"]), &words, &want("-statistics")));
434        assert!(!flag_given(&toks(&["-statsonly"]), &words, &want("-s")));
435        assert!(flag_given(&toks(&["-", "bash"]), &jj_like(None), &want("-")));
436        assert!(!flag_given(&toks(&["--", "-"]), &jj_like(None), &want("-")));
437    }
438
439    #[test]
440    fn min_positional_counts_operands_not_flag_values() {
441        let p = jj_like(Some(1));
442        assert!(!check_owned(&toks(&["-m", "x"]), &p));
443        assert!(!check_owned(&toks(&["-m", "x", "-r", "src/a"]), &p));
444        assert!(check_owned(&toks(&["-m", "x", "src/a"]), &p));
445        assert!(check_owned(&toks(&["-m", "x", "--", "src/a"]), &p));
446        assert!(check_owned(&toks(&["-m", "x"]), &jj_like(None)));
447    }
448
449    #[test]
450    fn min_positional_is_named_in_the_reference() {
451        assert!(jj_like(Some(1)).flag_summary().ends_with("At least 1 positional argument"));
452        assert!(jj_like(Some(2)).flag_summary().ends_with("At least 2 positional arguments"));
453        assert!(!jj_like(None).flag_summary().contains("positional argument"));
454    }
455
456    fn demo(sub_fields: &str) -> Result<Vec<crate::registry::CommandSpec>, String> {
457        crate::registry::load_toml(&format!("[[command]]\nname = \"demo\"\n[[command.sub]]\nname = \"split\"\n{sub_fields}\n"), "test")
458    }
459
460    #[test]
461    fn min_positional_dispatches_through_a_loaded_definition() {
462        let specs = demo("level = \"SafeWrite\"\nrequire_any = [\"-m\"]\nmin_positional = 1\nvalued = [\"-m\", \"-r\"]").expect("loads");
463        let verdict = |words: &[&str]| crate::registry::dispatch_spec(&toks(words), &specs[0]);
464        assert_eq!(verdict(&["split", "-m", "x", "a"]), crate::verdict::Verdict::Allowed(crate::verdict::SafetyLevel::SafeWrite));
465        assert_eq!(verdict(&["split", "-m", "x"]), crate::verdict::Verdict::Denied);
466        assert_eq!(verdict(&["split", "-m", "x", "-r", "a"]), crate::verdict::Verdict::Denied);
467        assert_eq!(verdict(&["split", "a"]), crate::verdict::Verdict::Denied);
468    }
469
470    #[test]
471    fn min_positional_is_refused_where_nothing_would_count_operands() {
472        for fields in [
473            "min_positional = 1\nallow_all = true",
474            "min_positional = 1\nfirst_arg = [\"x\"]",
475            "min_positional = 1\nhandler = \"demo\"",
476            "level = \"SafeWrite\"\nmin_positional = 2\nmax_positional = 1",
477        ] {
478            let err = demo(fields).err().unwrap_or_else(|| panic!("{fields:?} loaded"));
479            assert!(err.contains("min_positional"), "{fields:?}: {err}");
480        }
481    }
482
483    #[derive(Debug, Clone)]
484    enum Unit {
485        Standalone(&'static str),
486        Valued(&'static str, &'static str),
487        Glued(&'static str),
488        Operand(&'static str),
489        Wanted(Vec<&'static str>),
490        End,
491    }
492
493    fn unit() -> impl Strategy<Value = Unit> {
494        let value = prop::sample::select(vec!["m", "x", "mx", "@-"]);
495        prop_oneof![
496            prop::sample::select(vec!["-a", "-k", "-ak", "--quiet"]).prop_map(Unit::Standalone),
497            (prop::sample::select(vec!["-r", "--revision"]), value.clone()).prop_map(|(f, v)| Unit::Valued(f, v)),
498            prop::sample::select(vec!["-rm", "-rx", "-arm", "--revision=m", "--revision=-m"]).prop_map(Unit::Glued),
499            value.prop_map(Unit::Operand),
500            prop::sample::select(vec![vec!["-m", "x"], vec!["-mx"], vec!["-am", "x"], vec!["--message", "m"], vec!["--message=m"]])
501                .prop_map(Unit::Wanted),
502            Just(Unit::End),
503        ]
504    }
505
506    proptest! {
507        #[test]
508        fn flag_given_matches_a_reading_unit_by_unit(units in prop::collection::vec(unit(), 0..8)) {
509            let mut words = Vec::new();
510            let mut expected = false;
511            let mut ended = false;
512            for u in &units {
513                match u {
514                    Unit::Standalone(f) | Unit::Glued(f) | Unit::Operand(f) => words.push(*f),
515                    Unit::Valued(f, v) => words.extend([*f, *v]),
516                    Unit::Wanted(w) => {
517                        expected |= !ended;
518                        words.extend(w.iter().copied());
519                    }
520                    Unit::End => {
521                        ended = true;
522                        words.push("--");
523                    }
524                }
525            }
526            prop_assert_eq!(given(&words), expected, "{:?}", words);
527        }
528    }
529}