GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — feat(parse): add scalar repeat policy · jdx/usage@a9becee

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • PLAN.md
  • argv/src
    • spec.rs
  • benches/gate/tests
    • differential.rs
  • clap_usage
    • src
      • report.rs
    • tests/snapshots
      • simple__simple.snap
  • conformance
    • src
      • tables.rs
    • tests
      • args_override_self.rs
      • global_given_twice.rs
      • post_binding.rs
  • derive/src
    • codegen.rs
    • lib.rs
    • model.rs
  • docs
    • cli/reference
      • commands.json
    • rust
      • clap-compatibility.md
      • migrating-from-clap.md
    • spec/reference
      • cmd.md
  • go
    • argv
      • argv.go
      • post.go
      • post_test.go
      • render.go
      • render_test.go
    • internal/spec
      • spec.go
  • lib/src
    • docs
      • models.rs
    • error.rs
    • go
      • mod.rs
      • structs.rs
    • parse.rs
    • spec
      • builder.rs
      • cmd.rs
      • mod.rs
  • usage-rs/tests
    • facade.rs
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎PLAN.md‎

Copy file name to clipboardExpand all lines: PLAN.md
+16-15Lines changed: 16 additions & 15 deletions
  • Display the source diff
  • Display the rich diff
Original file line numberDiff line numberDiff line change
@@ -503,8 +503,12 @@ Groups are the opposite case: `Command::get_groups`, `ArgGroup::get_args` and
503503
empty command line still means help.
504504
- [ ] **Remaining command parsing policy** —
505505
`args_conflicts_with_subcommands`, `subcommand_negates_reqs`,
506-
`subcommand_precedence_over_arg`, `allow_missing_positional`, and
507-
`args_override_self`.
506+
`subcommand_precedence_over_arg`, and `allow_missing_positional`.
507+
- [x] **`args_override_self`.** Repeated scalar flags are corrections by default;
508+
the later value wins. `args_override_self=false` opts a command into duplicate
509+
errors. KDL, usage-lib, the typed derive/static metadata, generated Go, and the
510+
clap bridge carry the policy. Repeatable, variadic, and count flags retain their
511+
collecting behavior.
508512

509513
**Help output**
510514

@@ -852,12 +856,10 @@ checked-in `mise.usage.kdl` for both parsers.
852856
tree, ~160µs validating it, and ~24µs actually parsing — so even against clap's
853857
parse alone, with the tree already built and paid for, this is 12× faster.
854858
- [x] **Differential fuzzing** — proptest over argv on the mise spec, against
855-
usage-lib **and clap**. Two parsers was the wrong design and the first run showed
856-
it: every disagreement had usage-argv stricter than usage-lib, which reads as a
857-
pile of usage-argv bugs until clap is asked the same question and sides with
858-
usage-argv. usage-lib is lax — it accepts a missing subcommand, a missing flag
859-
value, and a repeated non-repeatable flag. So clap is the standard for
860-
_accepting_, being what mise ships, while usage-lib stays the standard for
859+
usage-lib **and clap**. The three-way comparison distinguishes intentional usage
860+
defaults from regressions: unknown flags and scalar repeats are permissive unless a
861+
command opts into strictness, while missing subcommands and flag values remain errors.
862+
Fleet commands can request clap parity explicitly; usage-lib stays the standard for
861863
rendering.
862864
It found one real usage-argv bug — a lone `-` selecting the root's default
863865
subcommand instead of binding as a value — now fixed.
@@ -1394,10 +1396,9 @@ including telling you to delete the label afterwards.
13941396
("a repeat is a correction… the later occurrence wins") and `long-unknown` ("more likely
13951397
data in transit than a mistake", with `unknown_flags "error"` as the opt-in). Acting on
13961398
the wrong reading got as far as three failing conformance vectors.
1397-
One refusal comes from a different layer: for repeated command-line occurrences,
1398-
`Error::DuplicateFlag` is constructed only in `derive/src/codegen.rs`, never by
1399-
usage-argv's parser, so a derive-generated binary still rejects a repeated flag as clap
1400-
does. Separately, `Spec::to_kdl` validates `duplicate_flag_form` at the spec boundary so
1399+
Repeated command-line occurrences now follow the same permissive principle: a later
1400+
scalar corrects an earlier one, while `args_override_self=false` opts a command into
1401+
strict duplicate errors. Separately, `Spec::to_kdl` validates `duplicate_flag_form` at the spec boundary so
14011402
two declarations cannot claim the same spelling. Unknown flags are intentionally different: usage parsers
14021403
are permissive by default and a command opts into `unknown_flags="error"` when it owns the
14031404
whole grammar. That is what fleet adopters should declare for clap parity, while forwarding
@@ -1410,9 +1411,9 @@ including telling you to delete the label afterwards.
14101411
a position, not a compatibility concession: clap's strict default is held
14111412
to be the wrong one — a wrapper appending to a command line it did not
14121413
write is ordinary, which is the grammar's "data in transit" rationale —
1413-
and what `mise run` tasks accept does not change. The derive's strictness
1414-
about a _repeated_ non-repeatable flag is a separate rule and unchanged.
1415-
The migration guide presents the difference as intentional, with strict
1414+
and what `mise run` tasks accept does not change. Repeated scalar flags follow the same
1415+
default and have their own `args_override_self=false` strict opt-in.
1416+
The migration guide presents both differences as intentional, with strict
14161417
one root-level line away, as communique's rewrite already declares it.
14171418
- [x] A flag missing its value is dropped silently — now an error, in `parse` but
14181419
not `parse_partial`, since a half-typed flag is exactly what a completion is
Collapse file

‎argv/src/spec.rs‎

Copy file name to clipboardExpand all lines: argv/src/spec.rs
+22Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -708,6 +708,8 @@ pub struct CommandMeta<'a> {
708708
/// everything reading that spec — help, docs, completions — otherwise describes a
709709
/// command as runnable when it is not.
710710
pub subcommand_required: bool,
711+
/// Whether later single-valued occurrences replace earlier ones.
712+
pub args_override_self: bool,
711713
/// Text printed above the usage line, and below everything else.
712714
///
713715
/// The spec's `before_help`/`after_help` and their long forms. mise puts an Examples
@@ -743,6 +745,7 @@ impl CommandMeta<'_> {
743745
mount: None,
744746
restart_token: None,
745747
subcommand_required: false,
748+
args_override_self: true,
746749
before_help: None,
747750
before_long_help: None,
748751
after_help: None,
@@ -1122,6 +1125,9 @@ impl Spec<'_> {
11221125
if self.root.cmd.dont_delimit_trailing_values {
11231126
writeln!(out, "dont_delimit_trailing_values #true")?;
11241127
}
1128+
if !self.root.args_override_self {
1129+
writeln!(out, "args_override_self #false")?;
1130+
}
11251131
// A `complete` block for every completer this CLI declares, naming the command that
11261132
// asks the binary itself. Written rather than declared, so there is one place a
11271133
// completer is said to exist: the Rust function. Everything that reads a spec — the
@@ -1368,6 +1374,9 @@ fn write_command<'a>(
13681374
if meta.cmd.dont_delimit_trailing_values {
13691375
out.push_str(" dont_delimit_trailing_values=#true");
13701376
}
1377+
if !meta.args_override_self {
1378+
out.push_str(" args_override_self=#false");
1379+
}
13711380
out.push_str(" {\n");
13721381

13731382
let inner = depth + 1;
@@ -2429,6 +2438,19 @@ pub trait CommandArgs: Sized {
24292438
Ok(())
24302439
}
24312440

2441+
/// Run checks under the repeat policy of the command that composed these args.
2442+
///
2443+
/// A flattened argument group is part of its parent's command, so the parent's
2444+
/// `args_override_self` setting governs repeats in the group as well. Hand-written
2445+
/// implementations keep their existing behavior through this default.
2446+
fn check_with_args_override_self<'t, 'v>(
2447+
partial: &mut Self::Partial,
2448+
args_override_self: bool,
2449+
) -> Result<(), crate::Error<'t, 'v>> {
2450+
let _ = args_override_self;
2451+
Self::check(partial)
2452+
}
2453+
24322454
/// Build the struct from what was collected.
24332455
///
24342456
/// Fallible because a command can require a subcommand of its own, and "none was
Collapse file

‎benches/gate/tests/differential.rs‎

Copy file name to clipboardExpand all lines: benches/gate/tests/differential.rs
+22-24Lines changed: 22 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -25,30 +25,27 @@
2525
//! surfaced. The third was real and is fixed: `subcommand_required` was in the spec and no
2626
//! parser read it (#992).
2727
//!
28-
//! So where do the refusals come from? `Error::DuplicateFlag` is constructed in exactly one
29-
//! place — `derive/src/codegen.rs` — and never by usage-argv's parser. The layers differ, not
30-
//! the parsers:
28+
//! Repeats are permissive in usage by default, including at the derive layer. A command that
29+
//! owns its entire grammar can opt into clap's rule with `args_override_self=false`:
3130
//!
3231
//! | | a flag given twice |
3332
//! |---|---|
3433
//! | usage-argv, the parser | accepts, last wins — conformant |
3534
//! | usage-lib | accepts, last wins — conformant |
36-
//! | usage-derive's post-binding check | refuses |
35+
//! | usage-derive, by default | accepts, last wins — conformant |
3736
//! | clap | refuses |
3837
//!
39-
//! Both are right in their own domain. A derive-generated binary is what an adopter compares to
40-
//! clap, and there the two agree. A spec-driven parse is what mise runs *task* arguments
41-
//! through, and there a wrapper appending `--jobs 2` to a command line it did not write is the
42-
//! documented case. So a disagreement of this shape is a fact about the layers, not a defect,
43-
//! and the arm below says so — do not "fix" usage-lib to close it.
38+
//! The deliberate default keeps wrappers and task runners from rejecting corrections. Fleet
39+
//! commands that need clap parity declare strictness explicitly; the gate's generated shadow
40+
//! leaves the default visible here so tightening it cannot happen accidentally.
4441
//!
4542
//! # A verdict is not enough
4643
//!
4744
//! Each class below names the *reason* a parser refused, not only that it did. Three booleans
48-
//! would allow-list every line of a known shape whatever caused it — and one such line is
49-
//! `mise -y config ls -y`, where usage-argv alone refuses a global given at two levels. It wore
50-
//! the same three booleans as the bare-`-` divergence and rode through on them until the reasons
51-
//! were compared. usage-lib's failures are `miette::Error`, a message with no class behind it,
45+
//! would allow-list every line of a known shape whatever caused it. This previously caught a
46+
//! global flag incorrectly rejected across a command boundary; the regression test remains even
47+
//! though permissive repeats have since made that particular line valid more broadly.
48+
//! usage-lib's failures are `miette::Error`, a message with no class behind it,
5249
//! so it stays a yes-or-no and the narrowing leans on the two parsers that can say why.
5350
//!
5451
//! # Mounts are stripped, and must be
@@ -505,11 +502,11 @@ fn a_bare_word_diverges_because_of_the_mount_not_the_parser() {
505502
}
506503

507504
#[test]
508-
fn a_global_may_be_given_once_per_level() {
509-
// Found by the generator once `head` let it put tokens before the command path, and fixed
510-
// in the commit this test came with. `-y` is `global=#true`; clap lets it be given again on
511-
// a subcommand — the inner occurrence wins — and refuses a repeat at one level. usage-argv
512-
// now draws the same line, which matters because `mise -y install -y` works today.
505+
fn a_global_repeat_is_permissive_unless_the_command_opts_into_strictness() {
506+
// Found by the generator once `head` let it put tokens before the command path. `-y` is
507+
// `global=#true`; clap lets it be given again on
508+
// a subcommand — the inner occurrence wins — and refuses a repeat at one level. Usage keeps
509+
// the last occurrence at either level unless that command opts into strictness.
513510
let spec = spec();
514511
let go = |words: &[&str]| {
515512
run(
@@ -527,15 +524,16 @@ fn a_global_may_be_given_once_per_level() {
527524
assert_eq!(o.accepted(), (true, true, true), "{words:?} {o:?}");
528525
}
529526

530-
// Twice at one level: refused, and refused by clap too — whether that level is the root or
531-
// a command three words in. This is the half a blanket exemption for globals would lose.
527+
// Twice at one level: usage's permissive default keeps the later occurrence, while clap's
528+
// strict default refuses it.
532529
for words in [
533530
&["-y", "-y"][..],
534531
&["config", "ls", "-y", "-y"][..],
535532
&["-y", "config", "ls", "-y", "-y"][..],
536533
] {
537534
let o = go(words);
538-
assert_eq!(o.argv, Verdict::Conflict, "{words:?} {o:?}");
535+
assert_eq!(o.argv, Verdict::Accept, "{words:?} {o:?}");
536+
assert!(o.lib, "{words:?} {o:?}");
539537
assert_eq!(o.clap, Verdict::Conflict, "{words:?} {o:?}");
540538
}
541539
}
@@ -682,9 +680,9 @@ fn usage_lib_accepting_a_repeat_is_the_grammar_not_a_defect() {
682680
"usage-lib must accept an unknown flag: `long-unknown` specifies it. {unknown:?}"
683681
);
684682

685-
// And the refusal that does exist comes from the layer above the parser: the derive's
686-
// post-binding check, which is what an adopter compares against clap.
687-
assert_eq!(repeated.argv, Verdict::Conflict, "{repeated:?}");
683+
// The typed derive follows the grammar's permissive default too. A CLI that owns the grammar
684+
// opts into strictness explicitly; clap starts strict.
685+
assert_eq!(repeated.argv, Verdict::Accept, "{repeated:?}");
688686
assert_eq!(repeated.clap, Verdict::Conflict, "{repeated:?}");
689687
}
690688

Collapse file

‎clap_usage/src/report.rs‎

Copy file name to clipboardExpand all lines: clap_usage/src/report.rs
-6Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@ pub enum FidelityFeature {
1515
GranularHide,
1616
AllowMissingPositional,
1717
ArgsConflictWithSubcommands,
18-
ArgsOverrideSelf,
1918
SubcommandPrecedenceOverArg,
2019
SubcommandNegatesRequirements,
2120
FlattenHelp,
@@ -93,11 +92,6 @@ fn visit(cmd: &Command, ancestors: &[String], losses: &mut BTreeSet<FidelityLoss
9392
FidelityFeature::ArgsConflictWithSubcommands,
9493
"args_conflicts_with_subcommands",
9594
);
96-
command_loss(
97-
cmd.is_args_override_self(),
98-
FidelityFeature::ArgsOverrideSelf,
99-
"args_override_self",
100-
);
10195
command_loss(
10296
cmd.is_subcommand_precedence_over_arg_set(),
10397
FidelityFeature::SubcommandPrecedenceOverArg,
Collapse file

‎clap_usage/tests/snapshots/simple__simple.snap‎

Copy file name to clipboardExpand all lines: clap_usage/tests/snapshots/simple__simple.snap
+1Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ expression: output
66
name example
77
bin example
88
unknown_flags error
9+
args_override_self #false
910
usage "Usage: example [OPTIONS]"
1011
flag --file help="some input file" {
1112
arg <FILE>
Collapse file

‎conformance/src/tables.rs‎

Copy file name to clipboardExpand all lines: conformance/src/tables.rs
+1Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,7 @@ pub fn build(
145145
mount: cmd.mounts.first().map(|m| leak(&m.run)),
146146
restart_token: opt(&cmd.restart_token),
147147
subcommand_required: cmd.subcommand_required,
148+
args_override_self: cmd.args_override_self,
148149
before_help: opt(&cmd.before_help),
149150
before_long_help: opt(&cmd.before_help_long),
150151
after_help: opt(&cmd.after_help),
Collapse file

‎conformance/tests/args_override_self.rs‎

Copy file name to clipboard
+63Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
//! Repeating a scalar is a correction by default, with strictness available per command.
2+
3+
use std::ffi::OsStr;
4+
5+
use usage_derive::Cli;
6+
7+
#[derive(Cli, Debug)]
8+
#[usage(bin = "permissive")]
9+
struct Permissive {
10+
#[usage(long)]
11+
jobs: Option<u32>,
12+
#[usage(long)]
13+
verbose: bool,
14+
}
15+
16+
#[derive(Cli, Debug)]
17+
#[usage(bin = "strict", args_override_self = false)]
18+
struct Strict {
19+
#[usage(long)]
20+
jobs: Option<u32>,
21+
#[usage(long)]
22+
verbose: bool,
23+
}
24+
25+
fn argv<'a>(words: &'a [&'a str]) -> Vec<&'a OsStr> {
26+
words.iter().map(OsStr::new).collect()
27+
}
28+
29+
#[test]
30+
fn a_later_scalar_wins_by_default() {
31+
let parsed = Permissive::parse_from(&argv(&["--jobs", "1", "--jobs", "2"]))
32+
.expect("repeating a scalar is permitted by default");
33+
assert_eq!(parsed.jobs, Some(2));
34+
35+
let parsed = Permissive::parse_from(&argv(&["--verbose", "--verbose"]))
36+
.expect("the same policy applies to switches");
37+
assert!(parsed.verbose);
38+
}
39+
40+
#[test]
41+
fn a_command_can_reject_duplicate_scalars() {
42+
let parsed = Strict::parse_from(&argv(&["--jobs", "1", "--verbose"]))
43+
.expect("one occurrence remains valid");
44+
assert_eq!(parsed.jobs, Some(1));
45+
assert!(parsed.verbose);
46+
47+
for words in [
48+
&["--jobs", "1", "--jobs", "2"][..],
49+
&["--verbose", "--verbose"][..],
50+
] {
51+
let err = Strict::parse_from(&argv(words)).expect_err("strict commands reject repeats");
52+
assert!(format!("{err:?}").contains("DuplicateFlag"), "{err:?}");
53+
}
54+
}
55+
56+
#[test]
57+
fn only_the_non_default_policy_is_emitted() {
58+
let permissive = Permissive::to_kdl();
59+
assert!(!permissive.contains("args_override_self"), "{permissive}");
60+
61+
let strict = Strict::to_kdl();
62+
assert!(strict.contains("args_override_self #false"), "{strict}");
63+
}
Collapse file

‎conformance/tests/global_given_twice.rs‎

Copy file name to clipboardExpand all lines: conformance/tests/global_given_twice.rs
+4-1Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ use usage_derive::{Args, Cli, Subcommands};
1717

1818
/// Do the thing
1919
#[derive(Args)]
20+
#[usage(args_override_self = false)]
2021
struct Sub {
2122
/// Its own flag
2223
#[usage(long)]
@@ -27,6 +28,7 @@ struct Sub {
2728

2829
/// Deeper still
2930
#[derive(Args)]
31+
#[usage(args_override_self = false)]
3032
struct Leaf {
3133
#[usage(long)]
3234
leafy: bool,
@@ -46,6 +48,7 @@ enum Commands {
4648

4749
/// What every level shares, spliced in rather than declared again
4850
#[derive(Args)]
51+
#[usage(args_override_self = false)]
4952
struct Shared {
5053
/// Global, and living in a flattened group — whose partial is its own, so the
5154
/// level markers have to be cleared through it rather than around it
@@ -57,7 +60,7 @@ struct Shared {
5760
}
5861

5962
#[derive(Cli)]
60-
#[usage(bin = "ex")]
63+
#[usage(bin = "ex", args_override_self = false)]
6164
struct Ex {
6265
/// Say yes to everything
6366
#[usage(long, short = 'y', global)]
Collapse file

‎conformance/tests/post_binding.rs‎

Copy file name to clipboardExpand all lines: conformance/tests/post_binding.rs
+2-2Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -391,7 +391,7 @@ fn required_unless_is_satisfied_by_the_other_flag() {
391391
/// Only `--file` declares the override, which is enough: the relationship holds
392392
/// between the two flags, so the later one wins whichever way round they are given.
393393
#[derive(Cli)]
394-
#[usage(bin = "ovr")]
394+
#[usage(bin = "ovr", args_override_self = false)]
395395
struct Ovr {
396396
/// Read from a file
397397
#[usage(long, overrides("--stdin", "--url"))]
@@ -544,7 +544,7 @@ fn each_occurrence_of_a_bounded_flag_counts_for_itself() {
544544
/// holds something when nobody gives it one. Its spec said so and the derive could not, so it
545545
/// was the last thing mise's 211-command spec could express that the derive could not.
546546
#[derive(Cli)]
547-
#[usage(bin = "ex")]
547+
#[usage(bin = "ex", args_override_self = false)]
548548
struct Defaulted {
549549
/// Filesystem events to filter to
550550
#[usage(long, var, default = "create", default = "remove", default = "modify")]

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.