Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reporting unknown arguments using CommandLineParser

Is there any way to make the Command Line Parser library report unknown arguments?

Given the following options class:

public class Options
{
    [Option('i', "int-option", DefaultValue = 10, HelpText = "Set the int")]
    public int IntOption { get; set; }

    [ParserState]
    public IParserState LastParserState { get; set; }

    [HelpOption]
    public string GetUsage()
    {
        return HelpText.AutoBuild(this, 
            HelpText.DefaultParsingErrorsHandler(this, current));
    }
}

And the following program:

var options = new Options();
var parser = new Parser(settings =>
{
    settings.HelpWriter = Console.Error;
    settings.IgnoreUnknownArguments = false;
});

if (parser.ParseArgumentsStrict(args, options))
{
    Console.WriteLine("Int value set: {0}", options.IntOption);
}

When calling the program with "MyProgram.exe --unknown" I just get the default usage information, but no mention of what error made the parsing fail. I'd like to get some kind of indication to the user what went wrong.

like image 491
PHeiberg Avatar asked Oct 22 '22 15:10

PHeiberg


1 Answers

Long story short: with the current implementation you can't get any info about the unknown options.

The long story:

If you put a brakepoint into your GetUsage method you will see that the LastParserState is not null but contains 0 element.

LastParserState is basically filled from the ArgumentParser.PostParsingState but the the LongOptionParser (which in your case is involved because of the -- double dash) is not adding anything to the PostParsingState collection inside its parse method:

Source from Github:

var parts = argumentEnumerator.Current.Substring(2).Split(new[] { '=' }, 2);
var option = map[parts[0]];

if (option == null)
{
    return _ignoreUnkwnownArguments ? PresentParserState.MoveOnNextElement : 
                                      PresentParserState.Failure;
}

So internally the parser doesn't store any info about what went wrong just record that fact.

like image 111
nemesv Avatar answered Nov 03 '22 19:11

nemesv