Command-line-api: [Question] Defining a custom parser?

Created on 29 Sep 2019  路  3Comments  路  Source: dotnet/command-line-api

I'd like to keep a clean main method, and have support for a custom parser - eg.

public class MyCoolParser : IParser<IEnumerable<KeyValuePair<int, int>>>
{
    public IEnumerable<KeyValuePair<int, int>> Parse(string input)
    {
        yield // pretend there's code here to convert "1:2,3:4,6:3" or whatever syntax to multiple KVPs.
    }
}

public class Program
{
    /// ... fancy xml docs here ...
    public static async Task<int> Main(IEnumerable<KeyValuePair<int, int>> pairs)
    {
        // enumerate through pairs
    }
}

without having to write a bunch of boilerplate to configure a pipeline or the likes - is this currently possible, or do I need to write some boilerplate to achieve this?

question waiting-on-feedback

Most helpful comment

Currently the best reference for binding behaviors is the Try .NET interactive tutorial: https://github.com/dotnet/command-line-api#interactive-tutorials

All 3 comments

If you want to do custom parsing of an argument such as 1:2,3:4,6:3, one approach that will work is to use a custom type like the following. The presence of a constructor taking a single string tells System.CommandLine's model binder to pass in the raw value from the command line.

public class MyCoolArgument : IEnumerable<KeyValuePair<int, int>>
{
    public MyCoolArgument(string rawCommandLineValue) 
    {
        // implement custom parsing here
    }
}

Your Main method can now depend on this type rather than the interface:

public class Program
{
    /// ... fancy xml docs here ...
    public static async Task<int> Main(MyCoolArgument argument)
    {
        // enumerate through pairs
    }
}

That looks like exactly what I wanted, thanks!

For future reference, is this detail documented somewhere? It'd be nice if I knew where to go when looking for stuff like this in the future.

Currently the best reference for binding behaviors is the Try .NET interactive tutorial: https://github.com/dotnet/command-line-api#interactive-tutorials

Was this page helpful?
0 / 5 - 0 ratings

Related issues

pjmagee picture pjmagee  路  7Comments

rgueldenpfennig picture rgueldenpfennig  路  4Comments

shaggygi picture shaggygi  路  5Comments

ibigbug picture ibigbug  路  3Comments

gitfool picture gitfool  路  3Comments