File tree Expand file tree Collapse file tree 3 files changed +31
-2
lines changed
System.CommandLine/Parsing Expand file tree Collapse file tree 3 files changed +31
-2
lines changed Original file line number Diff line number Diff line change @@ -512,5 +512,24 @@ public void Custom_parser_can_be_used_to_implement_int_binding_based_on_token_co
512512
513513 result . GetValue ( option ) . Should ( ) . Be ( 3 ) ;
514514 }
515+
516+ [ Fact ] // https://github.com/dotnet/command-line-api/issues/2257
517+ public void Default_value_is_used_when_option_with_ZeroOrOne_arity_is_parsed_without_an_argument ( )
518+ {
519+ var option = new Option < int > ( "-o" )
520+ {
521+ Arity = ArgumentArity . ZeroOrOne ,
522+ DefaultValueFactory = _ => 42
523+ } ;
524+
525+ var rootCommand = new RootCommand
526+ {
527+ option
528+ } ;
529+
530+ var parseResult = rootCommand . Parse ( "-o" ) ;
531+
532+ parseResult . GetValue ( option ) . Should ( ) . Be ( 42 ) ;
533+ }
515534 }
516535}
Original file line number Diff line number Diff line change @@ -153,7 +153,7 @@ private ArgumentConversionResult ValidateAndConvert(bool useValidators)
153153 }
154154 }
155155
156- if ( Parent ! . UseDefaultValueFor ( this ) )
156+ if ( Argument . HasDefaultValue && Parent ! . UseDefaultValueFor ( this ) )
157157 {
158158 var defaultValue = Argument . GetDefaultValue ( this ) ;
159159
Original file line number Diff line number Diff line change @@ -64,6 +64,16 @@ internal bool IsArgumentLimitReached
6464 internal ArgumentConversionResult ArgumentConversionResult
6565 => _argumentConversionResult ??= GetResult ( Option . Argument ) ! . GetArgumentConversionResult ( ) ;
6666
67- internal override bool UseDefaultValueFor ( ArgumentResult argument ) => Implicit ;
67+ internal override bool UseDefaultValueFor ( ArgumentResult argumentResult )
68+ {
69+ if ( Implicit )
70+ {
71+ return true ;
72+ }
73+
74+ return Tokens . Count is 0 &&
75+ Option . Arity is { MinimumNumberOfValues : 0 , MaximumNumberOfValues : > 0 } &&
76+ ! argumentResult . Argument . IsBoolean ( ) ;
77+ }
6878 }
6979}
You can’t perform that action at this time.
0 commit comments