gsscoder / commandline

Terse syntax C# command line parser for .NET with F# support
1.63k stars 293 forks source link

Getting the "current" verb #471

Open jeffeld opened 7 years ago

jeffeld commented 7 years ago

In the code below, I'd like to be able to either:

Is either one or both possible using 2.1.1-beta?

Thanks, Jeff

` static int Main(string[] args) {

        int exitCode = CommandLine.Parser.Default.ParseArguments<AuditorOpinionScanOptions, TestTaskOptions>(args)
            .MapResult(
                (AuditorOpinionScanOptions options) => RunTask<AuditorOpinionScanTask, AuditorOpinionScanOptions>(options),
                (TestTaskOptions options) => RunTask<TestTask, TestTaskOptions>(options),
                errs => 1
            );

        return exitCode;

    }

    private static int RunTask<TTask, TOptions>(TOptions options) where TTask: ITask<TOptions>, new()
    {
        TTask task = new TTask()
        {
            Log = CreateLogger(),
            Options = options
        };

        return task.Execute();
    }

`

jeffeld commented 7 years ago

So after a little thinking, it dawned on me the verb is an attribute on the options class. A little Googleing turned up this little gem.

Adding the extention method in Darin Dimitrov's answer (dated April 16 2010) allowed me to add this line to RunTask()...

string verb = typeof(TOptions).GetAttributeValue((VerbAttribute verbAttribute) => verbAttribute.Name); ...and use it where required.

Would be interested to know if there is a better way, but if not please go ahead and close this.

Cheers, Jeff