Skip to content

Commit 3fef055

Browse files
Present error instead of throwing exception for empty argument to FileSystemInfo type (#1704)
* Error instead of exception for FileSystemInfo null paths * Revert autoformat
1 parent 70d72f0 commit 3fef055

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

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

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,21 @@ public void Command_argument_of_FileInfo_returns_null_when_argument_is_not_provi
6565
.BeNull();
6666
}
6767

68+
[Fact]
69+
public void Argument_of_FileInfo_that_is_empty_results_in_an_informative_error()
70+
{
71+
var option = new Option<FileInfo>("--file");
72+
var result = option.Parse(new string[] { "--file", "" });
73+
74+
result.Errors
75+
.Should()
76+
.ContainSingle()
77+
.Which
78+
.Message
79+
.Should()
80+
.Contain("Cannot parse argument '' for option '--file'");
81+
}
82+
6883
[Fact]
6984
public void Argument_of_array_of_FileInfo_can_be_called_without_custom_conversion_logic()
7085
{

src/System.CommandLine/Binding/ArgumentConverter.StringConverters.cs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,11 @@ internal static partial class ArgumentConverter
6262

6363
[typeof(DirectoryInfo)] = (string path, out object? value) =>
6464
{
65+
if (String.IsNullOrEmpty(path))
66+
{
67+
value = default;
68+
return false;
69+
}
6570
value = new DirectoryInfo(path);
6671
return true;
6772
},
@@ -80,12 +85,22 @@ internal static partial class ArgumentConverter
8085

8186
[typeof(FileInfo)] = (string path, out object? value) =>
8287
{
88+
if (String.IsNullOrEmpty(path))
89+
{
90+
value = default;
91+
return false;
92+
}
8393
value = new FileInfo(path);
8494
return true;
8595
},
8696

8797
[typeof(FileSystemInfo)] = (string path, out object? value) =>
8898
{
99+
if (String.IsNullOrEmpty(path))
100+
{
101+
value = default;
102+
return false;
103+
}
89104
if (Directory.Exists(path))
90105
{
91106
value = new DirectoryInfo(path);

0 commit comments

Comments
 (0)