1use crate::parse::{Token, WordSet};
2
3#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
7pub enum UnknownTolerance {
8 #[default]
10 Strict,
11 Short,
15 Long,
21 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#[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 pub const fn strict() -> Self {
51 Self { unknown: UnknownTolerance::Strict, numeric_dash: false, single_dash_words: false }
52 }
53}
54
55#[derive(Clone, Copy, Debug, PartialEq, Eq)]
59pub enum PositionalShape {
60 Path,
63 GoPackage,
70 ToolchainName,
74}
75
76impl PositionalShape {
77 pub fn matches(self, token: &str) -> bool {
78 match self {
79 Self::Path => looks_like_path(token),
80 Self::GoPackage => is_go_local_package(token),
81 Self::ToolchainName => crate::envvars::is_toolchain_name(token),
82 }
83 }
84
85 pub fn from_name(name: &str) -> Option<Self> {
86 match name {
87 "path" => Some(Self::Path),
88 "go-package" => Some(Self::GoPackage),
89 "toolchain-name" => Some(Self::ToolchainName),
90 _ => None,
91 }
92 }
93
94 pub fn from_toml(name: Option<&str>, owner: &str) -> Result<Option<Self>, String> {
96 name.map(|n| Self::from_name(n).ok_or_else(|| format!("{owner}: unknown positional_shape `{n}`")))
97 .transpose()
98 }
99}
100
101pub fn is_go_local_package(token: &str) -> bool {
104 token == "." || token == ".." || token.starts_with("./") || token.starts_with("../") || token.starts_with('/') || token.ends_with(".go")
105}
106
107pub fn looks_like_path(token: &str) -> bool {
121 if token.is_empty() {
122 return false;
123 }
124 if token.starts_with('-') {
125 return token == "-";
126 }
127 token.starts_with('~') || token.contains('/') || token.contains('.')
128}
129
130pub trait FlagSet {
131 fn contains_flag(&self, token: &str) -> bool;
132 fn contains_short(&self, byte: u8) -> bool;
133}
134
135pub(crate) fn takes_next_word<S: FlagSet + ?Sized, V: FlagSet + ?Sized>(standalone: &S, valued: &V, flag: &str) -> bool {
138 valued.contains_flag(flag) && !standalone.contains_flag(flag)
139}
140
141impl FlagSet for WordSet {
142 fn contains_flag(&self, token: &str) -> bool {
143 self.contains(token)
144 }
145 fn contains_short(&self, byte: u8) -> bool {
146 self.contains_short(byte)
147 }
148}
149
150impl FlagSet for [String] {
151 fn contains_flag(&self, token: &str) -> bool {
152 self.iter().any(|f| f.as_str() == token)
153 }
154 fn contains_short(&self, byte: u8) -> bool {
155 self.iter().any(|f| f.len() == 2 && f.as_bytes()[0] == b'-' && f.as_bytes()[1] == byte)
156 }
157}
158
159impl FlagSet for Vec<String> {
160 fn contains_flag(&self, token: &str) -> bool {
161 self.as_slice().contains_flag(token)
162 }
163 fn contains_short(&self, byte: u8) -> bool {
164 self.as_slice().contains_short(byte)
165 }
166}
167
168pub struct FlagPolicy {
169 pub standalone: WordSet,
170 pub valued: WordSet,
171 pub bare: bool,
172 pub max_positional: Option<usize>,
173 pub tolerance: FlagTolerance,
174}
175
176impl FlagPolicy {
177 pub fn describe(&self) -> String {
178 use crate::docs::wordset_items;
179 let mut lines = Vec::new();
180 let standalone = wordset_items(&self.standalone);
181 if !standalone.is_empty() {
182 lines.push(format!("- Allowed standalone flags: {standalone}"));
183 }
184 let valued = wordset_items(&self.valued);
185 if !valued.is_empty() {
186 lines.push(format!("- Allowed valued flags: {valued}"));
187 }
188 if self.bare {
189 lines.push("- Bare invocation allowed".to_string());
190 }
191 if self.tolerance.unknown != UnknownTolerance::Strict {
192 lines.push("- Hyphen-prefixed positional arguments accepted".to_string());
193 }
194 if self.tolerance.numeric_dash {
195 lines.push("- Numeric shorthand accepted (e.g. -20 for -n 20)".to_string());
196 }
197 if lines.is_empty() && !self.bare {
198 return "- Positional arguments only".to_string();
199 }
200 lines.join("\n")
201 }
202}
203
204pub fn check(tokens: &[Token], policy: &FlagPolicy) -> bool {
205 check_flags(tokens, &policy.standalone, &policy.valued, policy.bare, policy.max_positional, policy.tolerance)
206}
207
208pub(crate) fn consumes_next_value(next: Option<&Token>) -> bool {
209 match next {
210 None => false,
211 Some(t) if crate::cst::opaque::is_flag_probe(t.as_str()) => true,
212 Some(t) => {
213 let b = t.as_bytes();
214 !(b.len() > 1 && b[0] == b'-' && !b[1].is_ascii_digit())
221 }
222 }
223}
224
225pub fn check_flags<S: FlagSet + ?Sized, V: FlagSet + ?Sized>(
226 tokens: &[Token],
227 standalone: &S,
228 valued: &V,
229 bare: bool,
230 max_positional: Option<usize>,
231 tolerance: FlagTolerance,
232) -> bool {
233 if tokens.len() == 1 {
234 return bare;
235 }
236 count_positionals(tokens, standalone, valued, tolerance).is_some_and(|n| max_positional.is_none_or(|max| n <= max))
237}
238
239pub fn count_positionals<S: FlagSet + ?Sized, V: FlagSet + ?Sized>(
241 tokens: &[Token],
242 standalone: &S,
243 valued: &V,
244 tolerance: FlagTolerance,
245) -> Option<usize> {
246 let mut i = 1;
247 let mut positionals: usize = 0;
248 while i < tokens.len() {
249 let t = &tokens[i];
250
251 if *t == "--" {
252 positionals += tokens.len() - i - 1;
253 break;
254 }
255
256 if !t.starts_with('-') {
257 positionals += 1;
258 i += 1;
259 continue;
260 }
261
262 if tolerance.numeric_dash && t.len() > 1 && t[1..].bytes().all(|b| b.is_ascii_digit()) {
263 i += 1;
264 continue;
265 }
266
267 if standalone.contains_flag(t) {
268 i += 1;
269 continue;
270 }
271
272 if valued.contains_flag(t) {
273 if consumes_next_value(tokens.get(i + 1)) {
274 i += 2;
275 } else {
276 i += 1;
277 }
278 continue;
279 }
280
281 if let Some(flag) = t.as_str().split_once('=').map(|(f, _)| f) {
282 if valued.contains_flag(flag) {
283 i += 1;
284 continue;
285 }
286 if tolerance.unknown.allows_long() {
288 positionals += 1;
289 i += 1;
290 continue;
291 }
292 return None;
293 }
294
295 if t.starts_with("--") {
296 if tolerance.unknown.allows_long() {
297 positionals += 1;
298 i += 1;
299 continue;
300 }
301 return None;
302 }
303
304 if tolerance.single_dash_words && t.len() > 1 {
305 if tolerance.unknown.allows_short() {
306 positionals += 1;
307 i += 1;
308 continue;
309 }
310 return None;
311 }
312
313 let bytes = t.as_bytes();
314 let mut j = 1;
315 while j < bytes.len() {
316 let b = bytes[j];
317 let is_last = j == bytes.len() - 1;
318 if standalone.contains_short(b) {
319 j += 1;
320 continue;
321 }
322 if valued.contains_short(b) {
323 if is_last && consumes_next_value(tokens.get(i + 1)) {
324 i += 1;
325 }
326 break;
327 }
328 if tolerance.unknown.allows_short() {
329 positionals += 1;
330 break;
331 }
332 return None;
333 }
334 i += 1;
335 }
336 Some(positionals)
337}
338
339#[cfg(test)]
340mod tests {
341 use super::*;
342
343 #[test]
344 fn go_local_package_each_alternative_alone() {
345 for local in [".", "..", "./x", "../x", "/x", "x.go"] {
346 assert!(is_go_local_package(local), "{local} is local");
347 }
348 for module in ["fmt", "github.com/a/b", "a/../b", "~/x", ""] {
349 assert!(!is_go_local_package(module), "{module} is a module path");
350 }
351 }
352
353 static TEST_POLICY: FlagPolicy = FlagPolicy {
354 standalone: WordSet::flags(&[
355 "--color", "--count", "--help", "--recursive", "--version", "-H", "-c", "-i", "-l", "-n", "-o", "-r", "-s", "-v", "-w",
356 ]),
357 valued: WordSet::flags(&["--after-context", "--before-context", "--max-count", "-A", "-B", "-m"]),
358 bare: false,
359 max_positional: None,
360 tolerance: FlagTolerance::strict(),
361 };
362
363 fn toks(words: &[&str]) -> Vec<Token> {
364 words.iter().map(|s| Token::from_test(s)).collect()
365 }
366
367 #[test]
368 fn bare_denied_when_bare_false() {
369 assert!(!check(&toks(&["grep"]), &TEST_POLICY));
370 }
371
372 #[test]
373 fn bare_allowed_when_bare_true() {
374 let policy = FlagPolicy {
375 standalone: WordSet::flags(&[]),
376 valued: WordSet::flags(&[]),
377 bare: true,
378 max_positional: None,
379 tolerance: FlagTolerance::strict(),
380 };
381 assert!(check(&toks(&["uname"]), &policy));
382 }
383
384 #[test]
397 fn a_flag_declared_in_both_lists_already_takes_an_optional_value() {
398 static BOTH: FlagPolicy = FlagPolicy {
399 standalone: WordSet::flags(&["--long", "-r"]),
400 valued: WordSet::flags(&["--long", "-r"]),
401 bare: true,
402 max_positional: Some(0),
403 tolerance: FlagTolerance::strict(),
404 };
405 assert!(check(&toks(&["zstd", "--long"]), &BOTH), "bare long form");
406 assert!(check(&toks(&["zstd", "--long=27"]), &BOTH), "glued long form");
407 assert!(check(&toks(&["zstd", "-r"]), &BOTH), "bare short form");
408
409 assert!(!check(&toks(&["zstd", "--long", "somefile"]), &BOTH), "the bare form must not consume the following token as its value");
412
413 assert!(!check(&toks(&["7z", "-r0"]), &BOTH), "short-glued is NOT handled today");
415 }
416
417 #[test]
418 fn only_a_flag_that_requires_a_value_takes_the_next_word() {
419 let standalone: Vec<String> = ["--toc", "--both"].map(String::from).to_vec();
420 let valued: Vec<String> = ["--to", "--both"].map(String::from).to_vec();
421 assert!(super::takes_next_word(&standalone, &valued, "--to"));
422 assert!(!super::takes_next_word(&standalone, &valued, "--both"));
423 assert!(!super::takes_next_word(&standalone, &valued, "--toc"));
424 assert!(!super::takes_next_word(&standalone, &valued, "--unknown"));
425 }
426
427 #[test]
428 fn standalone_long_flag() {
429 assert!(check(&toks(&["grep", "--recursive", "pattern", "."]), &TEST_POLICY));
430 }
431
432 #[test]
433 fn standalone_short_flag() {
434 assert!(check(&toks(&["grep", "-r", "pattern", "."]), &TEST_POLICY));
435 }
436
437 #[test]
438 fn valued_long_flag_space() {
439 assert!(check(&toks(&["grep", "--max-count", "5", "pattern"]), &TEST_POLICY));
440 }
441
442 #[test]
443 fn valued_long_flag_eq() {
444 assert!(check(&toks(&["grep", "--max-count=5", "pattern"]), &TEST_POLICY));
445 }
446
447 #[test]
448 fn valued_short_flag_space() {
449 assert!(check(&toks(&["grep", "-m", "5", "pattern"]), &TEST_POLICY));
450 }
451
452 #[test]
453 fn combined_standalone_short() {
454 assert!(check(&toks(&["grep", "-rn", "pattern", "."]), &TEST_POLICY));
455 }
456
457 #[test]
458 fn combined_short_with_valued_last() {
459 assert!(check(&toks(&["grep", "-rnm", "5", "pattern"]), &TEST_POLICY));
460 }
461
462 #[test]
463 fn combined_short_valued_mid_consumes_rest() {
464 assert!(check(&toks(&["grep", "-rmn", "pattern"]), &TEST_POLICY));
465 }
466
467 #[test]
468 fn unknown_long_flag_denied() {
469 assert!(!check(&toks(&["grep", "--exec", "cmd"]), &TEST_POLICY));
470 }
471
472 #[test]
473 fn unknown_short_flag_denied() {
474 assert!(!check(&toks(&["grep", "-z", "pattern"]), &TEST_POLICY));
475 }
476
477 #[test]
478 fn unknown_combined_short_denied() {
479 assert!(!check(&toks(&["grep", "-rz", "pattern"]), &TEST_POLICY));
480 }
481
482 #[test]
483 fn unknown_long_eq_denied() {
484 assert!(!check(&toks(&["grep", "--output=file.txt", "pattern"]), &TEST_POLICY));
485 }
486
487 #[test]
488 fn double_dash_stops_checking() {
489 assert!(check(&toks(&["grep", "--", "--not-a-flag", "file"]), &TEST_POLICY));
490 }
491
492 #[test]
493 fn positional_args_allowed() {
494 assert!(check(&toks(&["grep", "pattern", "file.txt", "other.txt"]), &TEST_POLICY));
495 }
496
497 #[test]
498 fn mixed_flags_and_positional() {
499 assert!(check(&toks(&["grep", "-rn", "--color", "--max-count", "10", "pattern", "."]), &TEST_POLICY,));
500 }
501
502 #[test]
503 fn valued_short_in_explicit_form() {
504 assert!(check(&toks(&["grep", "-A", "3", "-B", "3", "pattern"]), &TEST_POLICY));
505 }
506
507 #[test]
508 fn bare_dash_allowed_as_stdin() {
509 assert!(check(&toks(&["grep", "pattern", "-"]), &TEST_POLICY));
510 }
511
512 #[test]
513 fn valued_flag_at_end_without_value() {
514 assert!(check(&toks(&["grep", "--max-count"]), &TEST_POLICY));
515 }
516
517 #[test]
518 fn single_short_in_wordset_and_byte_array() {
519 assert!(check(&toks(&["grep", "-c", "pattern"]), &TEST_POLICY));
520 }
521
522 static SYNTAX_CHECK_POLICY: FlagPolicy = FlagPolicy {
523 standalone: WordSet::flags(&["--help", "-h"]),
524 valued: WordSet::flags(&["--check", "-c"]),
525 bare: false,
526 max_positional: Some(0),
527 tolerance: FlagTolerance::strict(),
528 };
529
530 #[test]
531 fn valued_flag_consumes_path_value() {
532 assert!(check(&toks(&["node", "--check", "app.js"]), &SYNTAX_CHECK_POLICY));
533 assert!(check(&toks(&["node", "-c", "app.js"]), &SYNTAX_CHECK_POLICY));
534 }
535
536 #[test]
537 fn valued_flag_does_not_swallow_following_long_option() {
538 assert!(!check(&toks(&["node", "--check", "--require=./evil.js"]), &SYNTAX_CHECK_POLICY,));
539 }
540
541 #[test]
542 fn valued_short_does_not_swallow_following_option() {
543 assert!(!check(&toks(&["node", "-c", "-r./evil.js"]), &SYNTAX_CHECK_POLICY));
544 }
545
546 #[test]
547 fn valued_flag_still_consumes_negative_number() {
548 let policy = FlagPolicy {
549 standalone: WordSet::flags(&[]),
550 valued: WordSet::flags(&["-n"]),
551 bare: false,
552 max_positional: Some(1),
553 tolerance: FlagTolerance::strict(),
554 };
555 assert!(check(&toks(&["head", "-n", "-5", "file"]), &policy));
556 }
557
558 static LIMITED_POLICY: FlagPolicy = FlagPolicy {
559 standalone: WordSet::flags(&["--count", "-c", "-d", "-i", "-u"]),
560 valued: WordSet::flags(&["--skip-fields", "-f", "-s"]),
561 bare: true,
562 max_positional: Some(1),
563 tolerance: FlagTolerance::strict(),
564 };
565
566 #[test]
567 fn max_positional_within_limit() {
568 assert!(check(&toks(&["uniq", "input.txt"]), &LIMITED_POLICY));
569 }
570
571 #[test]
572 fn max_positional_exceeded() {
573 assert!(!check(&toks(&["uniq", "input.txt", "output.txt"]), &LIMITED_POLICY));
574 }
575
576 #[test]
577 fn max_positional_with_flags_within_limit() {
578 assert!(check(&toks(&["uniq", "-c", "-f", "3", "input.txt"]), &LIMITED_POLICY));
579 }
580
581 #[test]
582 fn max_positional_with_flags_exceeded() {
583 assert!(!check(&toks(&["uniq", "-c", "input.txt", "output.txt"]), &LIMITED_POLICY));
584 }
585
586 #[test]
587 fn max_positional_after_double_dash() {
588 assert!(!check(&toks(&["uniq", "--", "input.txt", "output.txt"]), &LIMITED_POLICY));
589 }
590
591 #[test]
592 fn max_positional_bare_allowed() {
593 assert!(check(&toks(&["uniq"]), &LIMITED_POLICY));
594 }
595
596 static BOTH_TOLERANCES_POLICY: FlagPolicy = FlagPolicy {
597 standalone: WordSet::flags(&["-E", "-e", "-n"]),
598 valued: WordSet::flags(&[]),
599 bare: true,
600 max_positional: None,
601 tolerance: FlagTolerance { unknown: UnknownTolerance::Both, numeric_dash: false, single_dash_words: false },
602 };
603
604 #[test]
605 fn both_tolerances_accept_unknown_long() {
606 assert!(check(&toks(&["echo", "--unknown", "hello"]), &BOTH_TOLERANCES_POLICY));
607 }
608
609 #[test]
610 fn both_tolerances_accept_unknown_short() {
611 assert!(check(&toks(&["echo", "-x", "hello"]), &BOTH_TOLERANCES_POLICY));
612 }
613
614 #[test]
615 fn both_tolerances_accept_triple_dash() {
616 assert!(check(&toks(&["echo", "---"]), &BOTH_TOLERANCES_POLICY));
617 }
618
619 #[test]
620 fn both_tolerances_known_flags_still_work() {
621 assert!(check(&toks(&["echo", "-n", "hello"]), &BOTH_TOLERANCES_POLICY));
622 }
623
624 #[test]
625 fn both_tolerances_combo_known_short() {
626 assert!(check(&toks(&["echo", "-ne", "hello"]), &BOTH_TOLERANCES_POLICY));
627 }
628
629 #[test]
630 fn both_tolerances_combo_unknown_short_byte() {
631 assert!(check(&toks(&["echo", "-nx", "hello"]), &BOTH_TOLERANCES_POLICY));
632 }
633
634 #[test]
635 fn both_tolerances_unknown_eq_form() {
636 assert!(check(&toks(&["echo", "--foo=bar"]), &BOTH_TOLERANCES_POLICY));
637 }
638
639 static SHORT_ONLY_POLICY: FlagPolicy = FlagPolicy {
646 standalone: WordSet::flags(&["--help"]),
647 valued: WordSet::flags(&[]),
648 bare: false,
649 max_positional: None,
650 tolerance: FlagTolerance { unknown: UnknownTolerance::Short, numeric_dash: false, single_dash_words: false },
651 };
652
653 #[test]
654 fn short_only_accepts_unknown_dash_letter() {
655 assert!(check(&toks(&["sample", "-mayDie"]), &SHORT_ONLY_POLICY));
656 }
657
658 #[test]
659 fn short_only_accepts_single_dash_long_word() {
660 assert!(check(&toks(&["pdftotext", "-layout"]), &SHORT_ONLY_POLICY));
662 }
663
664 #[test]
665 fn short_only_denies_unknown_double_dash() {
666 assert!(!check(&toks(&["sample", "--evil-flag"]), &SHORT_ONLY_POLICY));
669 }
670
671 #[test]
672 fn short_only_denies_unknown_eq_form() {
673 assert!(!check(&toks(&["sample", "--evil=value"]), &SHORT_ONLY_POLICY));
674 }
675
676 #[test]
677 fn short_only_known_long_flag_still_works() {
678 assert!(check(&toks(&["sample", "--help"]), &SHORT_ONLY_POLICY));
679 }
680
681 static LONG_ONLY_POLICY: FlagPolicy = FlagPolicy {
687 standalone: WordSet::flags(&["--help"]),
688 valued: WordSet::flags(&[]),
689 bare: false,
690 max_positional: None,
691 tolerance: FlagTolerance { unknown: UnknownTolerance::Long, numeric_dash: false, single_dash_words: false },
692 };
693
694 #[test]
695 fn long_only_accepts_unknown_double_dash() {
696 assert!(check(&toks(&["aws", "--some-aws-flag"]), &LONG_ONLY_POLICY));
697 }
698
699 #[test]
700 fn long_only_accepts_unknown_eq_form() {
701 assert!(check(&toks(&["aws", "--filter=Name=tag,Values=foo"]), &LONG_ONLY_POLICY,));
702 }
703
704 #[test]
705 fn long_only_denies_unknown_short_dash() {
706 assert!(!check(&toks(&["aws", "-x"]), &LONG_ONLY_POLICY));
707 }
708
709 static STRICT_POLICY: FlagPolicy = FlagPolicy {
712 standalone: WordSet::flags(&["--help"]),
713 valued: WordSet::flags(&[]),
714 bare: false,
715 max_positional: None,
716 tolerance: FlagTolerance::strict(),
717 };
718
719 #[test]
720 fn strict_denies_unknown_short() {
721 assert!(!check(&toks(&["foo", "-evil"]), &STRICT_POLICY));
722 }
723
724 #[test]
725 fn strict_denies_unknown_long() {
726 assert!(!check(&toks(&["foo", "--evil"]), &STRICT_POLICY));
727 }
728
729 #[test]
730 fn strict_known_flag_passes() {
731 assert!(check(&toks(&["foo", "--help"]), &STRICT_POLICY));
732 }
733
734 #[test]
735 fn both_tolerances_with_max_positional() {
736 let policy = FlagPolicy {
737 standalone: WordSet::flags(&["-n"]),
738 valued: WordSet::flags(&[]),
739 bare: true,
740 max_positional: Some(2),
741 tolerance: FlagTolerance { unknown: UnknownTolerance::Both, numeric_dash: false, single_dash_words: false },
742 };
743 assert!(check(&toks(&["echo", "--unknown", "hello"]), &policy));
744 assert!(!check(&toks(&["echo", "--a", "--b", "--c"]), &policy));
745 }
746
747 static NUMERIC_DASH_POLICY: FlagPolicy = FlagPolicy {
748 standalone: WordSet::flags(&["--help", "--quiet", "--verbose", "--version", "-V", "-h", "-q", "-v", "-z"]),
749 valued: WordSet::flags(&["--bytes", "--lines", "-c", "-n"]),
750 bare: true,
751 max_positional: None,
752 tolerance: FlagTolerance { numeric_dash: true, ..FlagTolerance::strict() },
753 };
754
755 #[test]
756 fn numeric_dash_single_digit() {
757 assert!(check(&toks(&["head", "-5"]), &NUMERIC_DASH_POLICY));
758 }
759
760 #[test]
761 fn numeric_dash_multi_digit() {
762 assert!(check(&toks(&["head", "-20"]), &NUMERIC_DASH_POLICY));
763 }
764
765 #[test]
766 fn numeric_dash_large_number() {
767 assert!(check(&toks(&["head", "-1000"]), &NUMERIC_DASH_POLICY));
768 }
769
770 #[test]
771 fn numeric_dash_with_file_arg() {
772 assert!(check(&toks(&["head", "-20", "file.txt"]), &NUMERIC_DASH_POLICY));
773 }
774
775 #[test]
776 fn numeric_dash_with_other_flags() {
777 assert!(check(&toks(&["head", "-q", "-20", "file.txt"]), &NUMERIC_DASH_POLICY));
778 }
779
780 #[test]
781 fn numeric_dash_zero() {
782 assert!(check(&toks(&["head", "-0"]), &NUMERIC_DASH_POLICY));
783 }
784
785 #[test]
786 fn numeric_dash_still_rejects_unknown_flags() {
787 assert!(!check(&toks(&["head", "-x"]), &NUMERIC_DASH_POLICY));
788 }
789
790 #[test]
791 fn numeric_dash_rejects_mixed_alpha_num() {
792 assert!(!check(&toks(&["head", "-20x"]), &NUMERIC_DASH_POLICY));
793 }
794
795 #[test]
796 fn numeric_dash_disabled_rejects_multi_digit() {
797 assert!(!check(&toks(&["grep", "-20", "pattern"]), &TEST_POLICY));
798 }
799
800 static WORDS_POLICY: FlagPolicy = FlagPolicy {
801 standalone: WordSet::flags(&["-a", "-f", "-i", "-ifd0"]),
802 valued: WordSet::flags(&["-ext"]),
803 bare: false,
804 max_positional: None,
805 tolerance: FlagTolerance { single_dash_words: true, ..FlagTolerance::strict() },
806 };
807
808 #[test]
809 fn single_dash_words_never_split_a_word_into_letters() {
810 assert!(!check(&toks(&["exiftool", "-if", "system(1)", "a.jpg"]), &WORDS_POLICY));
811 assert!(!check(&toks(&["exiftool", "-fa", "a.jpg"]), &WORDS_POLICY));
812 assert!(check(&toks(&["exiftool", "-fa", "a.jpg"]), &FlagPolicy { tolerance: FlagTolerance::strict(), ..WORDS_POLICY }));
813 }
814
815 #[test]
816 fn single_dash_words_accept_listed_words_values_and_stdin() {
817 assert!(check(&toks(&["exiftool", "-ifd0", "-a", "-ext", "jpg", "a.jpg"]), &WORDS_POLICY));
818 assert!(check(&toks(&["exiftool", "-i", "-f", "-"]), &WORDS_POLICY));
819 }
820
821 #[test]
822 fn single_dash_words_under_short_tolerance_count_unknowns_as_positionals() {
823 let policy = FlagPolicy {
824 max_positional: Some(1),
825 tolerance: FlagTolerance { unknown: UnknownTolerance::Short, single_dash_words: true, numeric_dash: false },
826 ..WORDS_POLICY
827 };
828 assert!(check(&toks(&["exiftool", "-if"]), &policy));
829 assert!(!check(&toks(&["exiftool", "-if", "-zz"]), &policy));
830 }
831
832 #[test]
833 fn looks_like_path_accepts_relative() {
834 assert!(looks_like_path("./Tiltfile"));
835 assert!(looks_like_path("path/to/file"));
836 }
837
838 #[test]
839 fn looks_like_path_accepts_dotted() {
840 assert!(looks_like_path("Tiltfile.dev"));
841 assert!(looks_like_path("file.rb"));
842 }
843
844 #[test]
845 fn looks_like_path_accepts_stdin_dash() {
846 assert!(looks_like_path("-"));
847 }
848
849 #[test]
850 fn looks_like_path_rejects_flag() {
851 assert!(!looks_like_path("--help"));
852 assert!(!looks_like_path("-x"));
853 }
854
855 #[test]
856 fn looks_like_path_rejects_bare_word() {
857 assert!(!looks_like_path("Tiltfile"));
858 assert!(!looks_like_path("up"));
859 }
860
861 #[test]
862 fn looks_like_path_rejects_empty() {
863 assert!(!looks_like_path(""));
864 }
865
866 #[test]
867 fn positional_shape_path_matches() {
868 assert!(PositionalShape::Path.matches("./file.rb"));
869 assert!(!PositionalShape::Path.matches("--flag"));
870 }
871
872 #[test]
873 fn positional_shape_from_name() {
874 assert_eq!(PositionalShape::from_name("path"), Some(PositionalShape::Path));
875 assert_eq!(PositionalShape::from_name("nope"), None);
876 }
877
878 #[test]
879 fn a_vec_of_flags_answers_short_lookups_as_its_slice_does() {
880 let lists: [&[&str]; 4] = [&[], &["-x", "--long", "-y"], &["--x", "-", "-xy"], &["id", "if", "-i"]];
881 for list in lists {
882 let flags: Vec<String> = list.iter().map(|s| (*s).to_string()).collect();
883 for byte in 0..=u8::MAX {
884 let expected = list.iter().any(|f| f.len() == 2 && f.as_bytes()[0] == b'-' && f.as_bytes()[1] == byte);
885 assert_eq!(flags.contains_short(byte), expected, "{list:?} byte {byte}");
886 assert_eq!(flags.as_slice().contains_short(byte), expected, "{list:?} byte {byte}");
887 }
888 }
889 }
890
891 #[test]
892 fn an_opaque_probe_is_consumed_as_a_flag_value_where_other_options_are_not() {
893 let next = |w: &str| consumes_next_value(Some(&Token::from_test(w)));
894 assert!(next(crate::cst::opaque::FLAG_PROBE));
895 assert!(next(crate::cst::opaque::SHORT_PROBE));
896 assert!(!next("--require=evil.js"));
897 assert!(!next("-%x"));
898 assert!(next("-5"));
899 assert!(next("-"));
900 assert!(!consumes_next_value(None));
901 }
902
903 fn described(standalone: &'static [&'static str], valued: &'static [&'static str], bare: bool, tolerance: FlagTolerance) -> String {
904 FlagPolicy { standalone: WordSet::flags(standalone), valued: WordSet::flags(valued), bare, max_positional: None, tolerance }
905 .describe()
906 }
907
908 #[test]
909 fn describe_lists_each_flag_group_on_its_own_line() {
910 assert_eq!(
911 described(&["--all"], &["--max"], true, FlagTolerance::strict()),
912 "- Allowed standalone flags: --all\n- Allowed valued flags: --max\n- Bare invocation allowed"
913 );
914 }
915
916 #[test]
917 fn describe_names_every_flag_of_a_group() {
918 let text = described(&["--all", "-a"], &[], false, FlagTolerance::strict());
919 assert!(text.starts_with("- Allowed standalone flags: "));
920 assert!(text.contains("--all") && text.contains("-a"));
921 assert!(!text.contains("valued"));
922 }
923
924 #[test]
925 fn describe_an_empty_strict_policy_says_positional_only() {
926 assert_eq!(described(&[], &[], false, FlagTolerance::strict()), "- Positional arguments only");
927 }
928
929 #[test]
930 fn describe_an_empty_bare_policy_says_bare_only() {
931 assert_eq!(described(&[], &[], true, FlagTolerance::strict()), "- Bare invocation allowed");
932 }
933
934 #[test]
935 fn describe_reports_tolerances() {
936 let lenient = FlagTolerance { unknown: UnknownTolerance::Short, numeric_dash: true, single_dash_words: false };
937 assert_eq!(
938 described(&[], &[], false, lenient),
939 "- Hyphen-prefixed positional arguments accepted\n- Numeric shorthand accepted (e.g. -20 for -n 20)"
940 );
941 let numeric_only = FlagTolerance { numeric_dash: true, ..FlagTolerance::strict() };
942 assert_eq!(described(&[], &[], false, numeric_only), "- Numeric shorthand accepted (e.g. -20 for -n 20)");
943 }
944
945 #[test]
946 fn describe_of_the_shared_test_policy_names_its_flags() {
947 let text = TEST_POLICY.describe();
948 let lines: Vec<&str> = text.lines().collect();
949 assert_eq!(lines.len(), 2);
950 assert!(lines[0].starts_with("- Allowed standalone flags: ") && lines[0].contains("--recursive"));
951 assert!(lines[1].starts_with("- Allowed valued flags: ") && lines[1].contains("--max-count"));
952 }
953}