Skip to content

Should option tokens be greedy with regard to subsequent bundled option or subcommand tokens? #1380

Open

Description

@jonsequitur

Currently, the token following a known option token is not treated as an argument. This means that if the subsequent token matches a subcommand, it will be treated as a subcommand

var optionA = new Option<string>("-a") { Arity = ArgumentArity.ZeroOrOne };
var optionB = new Option<bool>("-b");
var optionC = new Option<bool>("-c");

var command = new RootCommand
{
    optionA,
    optionB,
    optionC
};

var result = command.Parse("-a -bc"); // -> [ root [ -a ] [ -b <True> ] [ -c <True> ] ]
var optionA = new Option<string>("-a");
var root = new RootCommand
{
    new Command("subcommand"),
    optionA
};

var result = root.Parse("-a subcommand"); // -> [ root [ -a ] [ subcommand ] ]

Should this behavior be changed so that the subsequent token would be considered an argument to the option, producing the following results, respectively, for the above examples?

[ root [ -a <-bc> ]
[ root [ -a <subcommand> ]

Activity

  1. changed the title [-]Make option tokens greedy[/-] [+]Should option tokens be greedy?[/+] on Aug 18, 2021
  2. changed the title [-]Should option tokens be greedy?[/-] [+]Should option tokens be greedy with regard to subsequent bundled option or subcommand tokens?[/+] on Aug 18, 2021
  3. added
    needs discussion
    on Aug 18, 2021
  4. elgonzo commented on Aug 18, 2021

    @elgonzo
    Contributor

    In my opion the "greedy" behavior should be default.

    Otherwise, this has to be documented, including in the help text as generated by System.CommandLine. Imagine having to document/explain that the argument following an option has to be different from any other option/subcommand name, otherwise you, the user, has to invoke the commandline of the program in this or that other way. This not only can become akward and confusing. but it also makes the user responsible for checking whether the argument value they provided matches by chance a subcommand or another option. It might perhaps even make otherwise valid commandline invocations impossible.

    What if the user actually wants to assign the value "-b" to the option -a? What if the CLI in question should allow program invocation without invoking a subcommand (in other words, the root command has a handler) and the user wants to provide -a with a "subcommand" value? How could they do this if options are non-greedy?

    The greedy approach avoids all this. Documentation and help text remain relatively simple and there are no special cases involved where an argument value by chance collides with other option or subcommand names.

    For those who prefer the "special case"-ness of the non-greedy behavior, perhaps there could be a setting offered by System.CommandLine to enable non-greedy behavior if desired. (Perhaps as an extension method applicable to RootCommand instances which effects this setting on the root command, all its descendent sub commands and options.)

  5. ViktorHofer commented on Oct 29, 2026

    @ViktorHofer
    Member

    Data point from a real migration, plus an update on where this landed.

    Current behaviour is mixed

    Re-running both examples from the original post against 3.0.0-rc.3.26522.148 on .NET 10:

    [-a -bc]           -a=''                    errors=0
    [-a subcommand]    -a='subcommand'  cmd=<root>  errors=[Required command was not provided.]
    

    So the second example did change to the greedy behaviour proposed here, while the first did not — bundled short options are still not consumed. Worth noting since this issue is still open and reads as though neither had changed.

    Greediness also extends to registered options of the same command, including --help:

    var targetRepo = new Option<string>("--target-repo");
    var root = new RootCommand { targetRepo, new Option<bool>("--disabled") };
    [--target-repo --disabled]   --target-repo='--disabled'   errors=0
    [--target-repo --help]       --target-repo='--help'       errors=0
    [--target-repo --bogus]      --target-repo='--bogus'      errors=0
    

    Why this is a problem in practice

    We are migrating the darc CLI off CommandLineParser as a prerequisite for Native AOT (dotnet/arcade-services#6825). CommandLineParser rejected option-like values unless they were explicitly assigned with =:

    [--search=--foo]   OK  Search='--foo'
    [--search --foo]   ERR CommandLine.UnknownOptionError
    

    Under the current greedy behaviour, darc get-subscriptions --target-repo --help silently binds "--help" as a repository name and queries for it, rather than printing help. A user who forgets an argument gets a confusing empty result set instead of an error.

    I agree with @elgonzo that greedy is the right default — it is the only way to pass a value that happens to look like an option. But the all-or-nothing nature of it is the issue. There is currently no way to opt into stricter handling, so a CLI migrating from a stricter parser has to accept the regression.

    Request

    An opt-in strict mode, ideally settable per-option as well as inherited from the root command, that reports an error when a scalar option's value starts with a prefix character and was not explicitly assigned with =.

    That second half is the key qualifier, and it is currently impossible to express: the = is erased during tokenization, so --search=--foo and --search --foo are byte-identical in ArgumentResult.Tokens, OptionResult.IdentifierToken, and ParseResult.Tokens. I filed #2868 for that specific gap, since preserving the distinction is a prerequisite for any strict mode that is not also a usability regression.

  6. ViktorHofer commented on Oct 30, 2026

    @ViktorHofer
    Member

    Filed #2870 for a distinct bug that surfaced while applying the ZeroOrOne workaround @adamsitnik suggested in #2869, since it is independent of the policy question in this issue and worth fixing on its own.

    Short version: Option.Greedy answers two different questions with one predicate, so Arity = ZeroOrOne silently breaks bundled/attached short-option values as a side effect of disabling lookahead.

    --- ExactlyOne (default) ---
      [-npreview  ] --name='preview'  --preview=False  errors: none
    
    --- ZeroOrOne ---
      [-npreview  ] --name=<null>     --preview=True   errors: Unrecognized command or argument 'review'.
    

    (3.0.0-rc.3.26522.148, .NET 10; --name/-n is Option<string>, --preview/-p is Option<bool>. The only difference between the two runs is Arity.)

    Both consumers of Greedy are in StringExtensions.cs, but they ask different things:

    • PreviousTokenIsAnOptionExpectingAnArgument — "should the next separate token become my value?" — legitimately depends on whether the value is required.
    • TryUnbundle — "does the remainder of this token belong to me?" — should only depend on whether the option takes a value at all.

    Why this matters for the question in this issue

    The POSIX guidance actually answers the two halves differently, which I think sharpens the design question here (§12.2, Guideline 7 commentary):

    2. If the SYNOPSIS shows an optional option-argument […] a conforming application shall place any option-argument for that option directly adjacent to the option in the same argument string, without intervening <blank> characters. […] it shall not treat the next argument (if any) as the option-argument for that option.

    For a mandatory option-argument POSIX imposes no restriction on content, and glibc's getopt.c consumes argv[optind++] unconditionally — no check that the next element starts with -. So the greedy default for ExactlyOne/OneOrMore is well-grounded, and @elgonzo's argument above holds.

    But for an optional option-argument POSIX says the opposite: don't take the next argument, and the attached form is the only conforming spelling. System.CommandLine's ZeroOrOne currently gets the first half right and breaks the second — so that case isn't a policy choice at all, just a bug (#2870).

    That also means ZeroOrOne cannot serve as the opt-in strict mode for mandatory-argument options that #2869's workaround leans on: it changes bundling semantics at the same time, so adopting it requires re-implementing TryUnbundle in user code. We ended up doing exactly that in darc (dotnet/arcade-services#6834) — along with five other compensating workarounds — which is what prompted me to look at where the real fix belongs.

    Prior art, for whoever picks this up

    Surveying other parsers, the split is not arbitrary — it tracks whether the library is getopt-descended or a later reaction to it:

    Behaviour for --name --help Parsers
    Swallowed (greedy) glibc getopt_long, Go pflag/cobra, CommandLineUtils, commander.js (mandatory arg)
    Refused Python argparse, Rust clap v4, yargs, CommandLineParser (what darc migrated from)

    Notably commander.js already implements precisely the Greedy split proposed in #2870: "Options with an expected option-argument are greedy and will consume the following argument whatever the value […] Options with an optional option-argument are not greedy and will ignore arguments starting with a dash" — while still honouring the attached form (--id=-ABCD) for those same options.

    And every library in the "refused" column ships a named opt-in to restore greediness (clap's per-arg allow_hyphen_values, yargs' nargs-eats-options), which seems like the right shape for this issue: keep greedy as the default, add an explicit knob rather than making callers bend Arity.

    Related threads

    This bug class has a longer history than I realised. #164 (2018-07-31) is the earliest report — "It could be reasonable and probably intuitive to return an error when someone specifies something that looks like an option" — three years before this issue. #2395, "[Design] Does Posix bundling lose to explicit options?", was opened with an empty body and closed NOT_PLANNED in 2025 with no recorded answer. So the question in this title still appears to be genuinely open.

    I have the Greedy-split change working locally and am happy to put up a PR for #2870 if the direction looks right. I also prototyped making the tokenizer stop reinterpreting recognized tokens as values; that one removes all of darc's workarounds, but it fails 4 of System.CommandLine's own 942 tests — and all 4 assert the behaviour deliberately — so it clearly needs to be opt-in rather than a default change. Happy to share that data if it's useful here.

  7. ViktorHofer commented on Oct 30, 2026

    @ViktorHofer
    Member

    Following up on my comment above: I've filed #2871 with a concrete, opt-in proposal for the question in this title, plus measurements.

    Summary of what's there:

    Proposed shape is AllowOptionTokensAsValues on Option with a ParserConfiguration-level default, mirroring EnablePosixBundling and clap's per-arg allow_hyphen_values.

    Happy to close this issue in favour of #2871 if that's tidier, or keep this one as the design discussion.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    needs discussion

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions