commandline icon indicating copy to clipboard operation
commandline copied to clipboard

Consider custom parsers/converters/handler for types?

Open RobThree opened this issue 4 years ago • 1 comments

I would love to be able to do:

public class Options
{
    [Option('o', "out", Required = true, HelpText = "Output file")]
    public string OutFile { get; set; }
    [Option('d', "duration", Required = false, Default = "1:00:00", HelpText = "Duration")]
    public TimeSpan Duration { get; set; }
    [Option('e', "endpoint", Required = true, HelpText = "IP Endpoint (<ip>:<port>)")]
    public IPEndPoint Endpoint { get; set; }
}

Where I can use types like TimeSpan and IPEndPoint or any other type. Ofcourse, we would need to be able to specify a parser/converter/handler/whatever that takes the value and converts it to the desired type. I imagine it be like:

public class Options
{
    [Option('o', "out", Required = true, HelpText = "Output file")]
    public string OutFile { get; set; }
    [Option('d', "duration", Required = false, Default = "1:00:00", HelpText = "Duration", Converter = typeof(MyTimeSpanConverter))]
    public TimeSpan Duration { get; set; }
    [Option('e', "endpoint", Required = true, HelpText = "IP Endpoint (<ip>:<port>)", Converter = typeof(MyIPEndpointConverter))]
    public IPEndPoint Endpoint { get; set; }
}

Next these 'converters' should implement something like an IConvert<T> that defines a method T Convert(string value) where they take a string (the commandline argument) and convert to the desired type. Another option would be to not use the attributes but be able to specify handlers like:

Parser.Default
    .Register<TimeSpan, MyTimeSpanConverter>()
    .Register<IPEndPoint, MyIPEndPointConverter>()
    .ParseArguments<Options>(args)
    ....

Would that be something that you would consider? (Maybe not exactly following the idea given above, but the broader idea of being able to handle custom types).

RobThree avatar Nov 18 '20 10:11 RobThree

Some ideas to solve this:

znakeeye avatar May 19 '22 09:05 znakeeye