natemcmaster/CommandLineUtils

[Question] Changes to DirectoryExists from 3.1.0 to 4.1.0

christophwille opened this issue · 1 comments

https://github.com/icsharpcode/ILSpy/blob/1100d64e4bbd878164e3cbf17d8b741ad11bdb44/ICSharpCode.ILSpyCmd/IlspyCmdProgram.cs#L93

[DirectoryExists]
[Option("-r|--referencepath <path>", "Path to a directory containing dependencies of the assembly that is being decompiled.", CommandOptionType.MultipleValue)]
public string[] ReferencePaths { get; } = new string[0];

Sample call: .\ilspycmd ilspycmd.dll

The old behavior: if the option isn't specified it won't be checked
The new behavior: "check always even if not specified"

Didn't see that in the release notes. What would be the way to specify "Check directory exists only if parameter is supplied" in 4? Thanks.

The bug appears to be a result of the default = new string[0];. When no value is provided, the framework is generating an instance of CommandOption with CommandOption.DefaultValue set to "".

image

Test case

These tests pass.

        private class OptionalFileChecks
        {
            [DirectoryExists]
            [Option]
            public string[] Dir { get; }

            [FileExists]
            [Option]
            public string? File { get; }

            private void OnExecute() { }
        }

        [Theory]
        [InlineData(0, new string[0])]
        [InlineData(1, new[] { "-f", "file.txt" })]
        [InlineData(1, new[] { "-d", "dir1" })]
        public void OnlyValidatesOptionsIfSpecified(int exitCode, string[] args)
        {
            var context = new DefaultCommandLineContext(
                new TestConsole(_output),
                AppContext.BaseDirectory,
                args);

            Assert.Equal(exitCode, CommandLineApplication.Execute<OptionalFileChecks>(context));
        }

But it fails if I specify a default value.

-             public string[] Dir { get; }
+             public string[] Dir { get; } = new string[0];
 Expected: 0
Actual:   1
    Stack Trace:
       at McMaster.Extensions.CommandLineUtils.Tests.FilePathExistsAttributeTests.OnlyValidatesOptionsIfSpecified(Int32 exitCode, String[] args) in ./src/natemcmaster/CommandLineUtils/test/CommandLineUtils.Tests/FilePathExistsAttributeTests.cs:line 202
   at InvokeStub_FilePathExistsAttributeTests.OnlyValidatesOptionsIfSpecified(Object, Object, IntPtr*)
   at System.Reflection.MethodInvoker.Invoke(Object obj, IntPtr* args, BindingFlags invokeAttr)
    Standard Output Messages:
    The directory '' does not exist.