-
Notifications
You must be signed in to change notification settings - Fork 404
Description
System.CommandLine version: 2.0.0-beta6.25320.118
When setting up an option with an arity of ArgumentArity.ZeroOrOne
or ArgumentArity.ZeroOrMore
, it allows to provide the option without a value on the CLI. When no value is given for such an option, i would expect the DefaultValueFactory
of the option to be called for providing the default value to fill in for the missing option value in the CLI invocation.
As an example, take this int
option and command specification:
var opt = new Option<int>("-o")
{
Arity = ArgumentArity.ZeroOrOne,
DefaultValueFactory = _ =>
{
Console.WriteLine("DefaultValueFactory called");
return 42;
}
};
var rootCmd = new RootCommand
{
opt
};
rootCmd.SetAction(
parseResult =>
{
var optResult = parseResult.GetResult(opt)!;
Console.WriteLine($"Value: {optResult.GetValueOrDefault<int>()}");
}
);
Providing the option -o
but without a value in the CLI invocation (which is legal, because the option's arity is ZeroOrOne),
rootCmd.Parse(new string[] {"-o"}).Invoke();
will lead to the following unexpected behavior
Actual behavior
The DefaultValueFactory
is not being executed, rather the int
type default value is being assumed, resulting in the output:
Value: 0
Expected behavior
I would expect the DefaultValueFactory
being executed to provide the default value also in case the -o
option is given without a value in the CLI, giving the following output:
DefaultValueFactory called
Value: 42
(My apologies to anyone that got the first incomplete and broken version of my issue report. It seems to be a good idea to not let me be near Enter keys...)