2

I've defined

var p = new OptionSet () {
 // various options defined
};

Then I

p.Parse(args)

If I call my program with

myprogram --thisOptionIsNotDefined

I would like to display a help message, and NOT continue. But Parse() doesn't throw an OptionException when it encounters an invalid option. What do I do?

Daniel
  • 2,032
  • 5
  • 21
  • 27

2 Answers2

5

You can interrogate the return of OptionSet.Parse() to find any invalid parameters.

From the NDesk OptionSet documentation:

OptionSet.Parse(IEnumerable), returns a List of all arguments which were not matched by a registered NDesk.Options.Option.

goric
  • 11,491
  • 7
  • 53
  • 69
1

OptionSet.Parse() returns any unprocessed arguments. However, note that this may also includes any actual (non-option) argument of your program, e.g. input files. In that case you can't just check that nothing is returned.

E.g. parsing the below args will return ["input.txt", "--thisOptionIsNotDefined"].

myprogram input.txt --thisOptionIsNotDefined

To solve this particular problem, I wrote an extension method p.ParseStrict(args). It simply checks that no options remain unprocessed after parsing (taking -- into account).

public static class MonoOptionsExtensions
{
    public static List<string> ParseStrict(this OptionSet source, IEnumerable<string> arguments)
    {
        var args = arguments.ToArray();
        var beforeDoubleDash = args.TakeWhile(x => x != "--");

        var unprocessed = source.Parse(beforeDoubleDash);

        var firstUnprocessedOpt = unprocessed.Find(x => x.Length > 0 && (x[0] == '-' || x[0] == '/'));
        if (firstUnprocessedOpt != null)
            throw new OptionException("Unregistered option '" + firstUnprocessedOpt + "' encountered.", firstUnprocessedOpt);

        return unprocessed.Concat(args.SkipWhile(x => x != "--").Skip(1)).ToList();
    }
}
johv
  • 4,424
  • 3
  • 26
  • 42