Skip to content

Commit 9117a09

Browse files
hoyosjsJuan Sebastian Hoyos Ayala
andauthored
Fix ArgumentConverted for nullable args (#2524)
* Fix ArgumentConverted for nullable args This fixes cases where conversion of tokens in options of nullable scalar-bindable values with Artities that are not {1,1} like `Option<bool?>` but conversion is still well known. * Add test for nullable bool option validation --------- Co-authored-by: Juan Sebastian Hoyos Ayala <[email protected]>
1 parent 65678ea commit 9117a09

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

src/System.CommandLine.Tests/Binding/TypeConversionTests.cs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -270,6 +270,23 @@ public void Nullable_bool_parses_as_null_when_the_option_has_not_been_applied()
270270
.Be(null);
271271
}
272272

273+
[Theory]
274+
[InlineData("-x", true)]
275+
[InlineData("-x:true", true)]
276+
[InlineData("-x:false", false)]
277+
public void Nullable_bool_option_result_casts_to_nullable_bool(string command, bool expectedValue)
278+
{
279+
var option = new Option<bool?>("-x");
280+
281+
var value = new RootCommand { option }
282+
.Parse(command)
283+
.GetResult(option)
284+
.GetValueOrDefault<object>();
285+
286+
value.Should().BeAssignableTo<bool?>();
287+
value.Should().Be(expectedValue);
288+
}
289+
273290
[Fact]
274291
public void When_exactly_one_argument_is_expected_and_none_are_provided_then_getting_value_throws()
275292
{

src/System.CommandLine/Binding/ArgumentConverter.cs

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -172,6 +172,12 @@ private static bool CanBeBoundFromScalarValue(this Type type)
172172
continue;
173173
}
174174

175+
if (type.TryGetNullableType(out Type? nullableType))
176+
{
177+
type = nullableType;
178+
continue;
179+
}
180+
175181
return false;
176182
}
177183
}
@@ -189,7 +195,7 @@ internal static ArgumentConversionResult ConvertIfNeeded(
189195

190196
ArgumentConversionResultType.NoArgument when conversionResult.ArgumentResult.Argument.IsBoolean() =>
191197
Success(conversionResult.ArgumentResult, true),
192-
198+
193199
_ => conversionResult
194200
};
195201
}

0 commit comments

Comments
 (0)