You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Should option tokens be greedy with regard to subsequent bundled option or subcommand tokens? #1380
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
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?
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
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.)
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:
[--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.
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.
(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)
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.
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:
A 27-case matrix built from two builds of eef106df differing only by the patch: 20 identical, 7 differ, all improvements (--target-repo --help prints help instead of binding "--help").
The prototype patch is a single branch in StringExtensions.cs; OptionArgument becomes unreferenced once it's gone, which suggests that branch is the only place a recognized token is reinterpreted as a value.
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.
Activity
[-]Make option tokens greedy[/-][+]Should option tokens be greedy?[/+][-]Should option tokens be greedy?[/-][+]Should option tokens be greedy with regard to subsequent bundled option or subcommand tokens?[/+]elgonzo commentedon Aug 18, 2021
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-awith 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.)
ViktorHofer commentedon Oct 29, 2026
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.148on .NET 10: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:Why this is a problem in practice
We are migrating the
darcCLI off CommandLineParser as a prerequisite for Native AOT (dotnet/arcade-services#6825). CommandLineParser rejected option-like values unless they were explicitly assigned with=:Under the current greedy behaviour,
darc get-subscriptions --target-repo --helpsilently 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=--fooand--search --fooare byte-identical inArgumentResult.Tokens,OptionResult.IdentifierToken, andParseResult.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.ViktorHofer commentedon Oct 30, 2026
Filed #2870 for a distinct bug that surfaced while applying the
ZeroOrOneworkaround @adamsitnik suggested in #2869, since it is independent of the policy question in this issue and worth fixing on its own.Short version:
Option.Greedyanswers two different questions with one predicate, soArity = ZeroOrOnesilently breaks bundled/attached short-option values as a side effect of disabling lookahead.(
3.0.0-rc.3.26522.148, .NET 10;--name/-nisOption<string>,--preview/-pisOption<bool>. The only difference between the two runs isArity.)Both consumers of
Greedyare inStringExtensions.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):
For a mandatory option-argument POSIX imposes no restriction on content, and glibc's
getopt.cconsumesargv[optind++]unconditionally — no check that the next element starts with-. So the greedy default forExactlyOne/OneOrMoreis 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
ZeroOrOnecurrently 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
ZeroOrOnecannot 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-implementingTryUnbundlein user code. We ended up doing exactly that indarc(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:
--name --helpgetopt_long, Gopflag/cobra,CommandLineUtils, commander.js (mandatory arg)argparse, Rustclapv4,yargs,CommandLineParser(whatdarcmigrated from)Notably commander.js already implements precisely the
Greedysplit 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-argallow_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 bendArity.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_PLANNEDin 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 ofdarc'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.ViktorHofer commentedon Oct 30, 2026
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:
eef106dfdiffering only by the patch: 20 identical, 7 differ, all improvements (--target-repo --helpprints help instead of binding"--help").StringExtensions.cs;OptionArgumentbecomes unreferenced once it's gone, which suggests that branch is the only place a recognized token is reinterpreted as a value.Option_arguments_can_match_subcommands, etc.), tracing back to Fix 1351 and 1365 #1361 which added greediness to fix When option argument matches an option token, it's not parsed as an argument #1351/Allow respecifying an option with a maximum arity of 1 #1083/Incorrect binding of options with similar names #1365. So both behaviours have real users and the default should stay as-is.Proposed shape is
AllowOptionTokensAsValuesonOptionwith aParserConfiguration-level default, mirroringEnablePosixBundlingandclap's per-argallow_hyphen_values.Happy to close this issue in favour of #2871 if that's tidier, or keep this one as the design discussion.