Search code examples
c#.netcommand-line-interfacespectre.console

How can I have runtime calculated DefaultValue for a [CommandOption]?


I am using spectre.console. I have the following CommandSettings:

public class LogCommandSettings : CommandSettings
{
    [CommandOption("--logFile")]
    [Description("Path and file name for logging")]
    [DefaultValue("application.log")]
    public string LogFile { get; set; }
}

I can set the default value for a CommandOption using [DefaultValue] attribute. However this case I would like to calculate the default path runtime, say the current user's temp folder

Sure, I can do this somewhere in the application, but how will be its actual default value will be displayed by the built in help?


Solution

  • You can try looking into implementing ParameterValueProviderAttribute:

    class MyDynamicParameterValueProviderAttribute : ParameterValueProviderAttribute
    {
        public override bool TryGetValue(CommandParameterContext context, out object? result)
        {
            result = context.Value ?? "some generated dynamic value";
            return true;
        }
    }
    
    public class LogCommandSettings : CommandSettings
    {
        [CommandOption("--logFile")]
        [Description("Path and file name for logging")]
        [MyDynamicParameterValueProvider]
        public string LogFile { get; set; }
    }