spectre.console icon indicating copy to clipboard operation
spectre.console copied to clipboard

Validate is not called if a CommandSettings class defines a constructor

Open fgimian opened this issue 3 years ago • 0 comments

Information

  • OS: Windows 11 Pro
  • Version: 0.44.0
  • Terminal: Windows Terminal / PowerShell 7

Describe the bug Spectre CLI doesn't seem to call Validate if a constructor is provided for a CommandSettings class.

To Reproduce

namespace TestingSpectre;

using System.Diagnostics.CodeAnalysis;
using Spectre.Console;
using Spectre.Console.Cli;

internal class Program
{
    public class DogCommand : Command<DogCommand.DogSettings>
    {
        public sealed class DogSettings : CommandSettings
        {
            public DogSettings(string name)
            {
                Name = name;
            }

            [CommandOption("-n|--name <VALUE>")]
            public string Name { get; }

            public override ValidationResult Validate()
            {
                if (Name == "Tiger")
                {
                    return ValidationResult.Error("Tiger is not a dog name!");
                }

                return ValidationResult.Success();
            }
        }

        public override int Execute([NotNull] CommandContext context, [NotNull] DogSettings settings)
        {
            AnsiConsole.WriteLine($"The dog's name is {settings.Name}");
            return 0;
        }
    }

    static int Main()
    {
        CommandApp app = new();
        app.Configure(config =>
        {
            config.AddCommand<DogCommand>("dog");
        });
        return app.Run(new[] { "dog", "-n", "Tiger" });
    }
}

Expected behavior In the example above, invocation when calling Run should fail with an error but it runs without error. When removing the constructor and setting the Name property to { get; set; }, the validator is called as expected.

Using constructors for such classes is important when nullable is enabled or the compiler will throw a warning stating that all non-nullable properties must be set by the constructor of the class.

Screenshots N/A

Additional context N/A

Thanks heaps in advance! Fotis

fgimian avatar Aug 06 '22 02:08 fgimian