0

I want to add an option like -D=Id1:Id2:Id3 in my command line options set. How can I do this ? This option has to be mandatory.

I tried to do this:

var optSet = new OptionSet() 
{
    { "D:", "Device to communicate with.",
        (int id1, int id2, int id3) => {
            if (id1 == null)
                throw new OptionException ("Missing Id1 for option -D.", "-D");
            if(id2 == null)
                throw new OptionException ("Missing Id2 for option -D.",  "-D");
            if(id3 == null)
                throw new OptionException ("Missing Id3 for option -D.",  "-D"); 
} },

But I get error saying the action takes only 2 arguments.

Monku
  • 2,440
  • 4
  • 33
  • 57
  • ndesk.options doesn't seem to support that. what you could do is use a function that takes only 1 string and parse it yourself(split by ':' then parse each substring to an int). also int can't be null. – Mor A. May 30 '18 at 05:18
  • Yea that’s what I ended up doing. Thanks anyways :) – Monku May 30 '18 at 06:08

1 Answers1

0

Use a CSV/SSV-like syntax instead e.g. -D=Id1,Id2,Id3 or -D=Id1;Id2;Id etc. Then use NDesk.Options to parse to a single combined result Id1,Id2,Id3 then with a .Split(',') afterwards verify the length or count is 3 or print a usage message.

It should be easy enough to modify NDesk.Options - which is only a single file - to handle this for you by splitting the array internally and returning it.

I also had to do so for something like I think illegal empty options e.g. - if I remember since I didn't like the default behavior. It has now become my preferred C# command-line option handler along with the following {--/}key=value parser in C# (and in Python) with or without the leading options chars:

public static Dictionary<string, string> KVs2Dict(IEnumerable<string> args, Dictionary<string, string> defaults = null)
{
    Dictionary<string, string> d = defaults ?? new Dictionary<string, string>();
    foreach (string arg in args)
    {
        string s = arg.TrimStart(new[] { '-', '/' });
        string[] sa = s.Split(new[] { '=' }, 1);
        string k = sa[0].Trim('"');
        if (s.Contains('='))
        {
            string v = sa[1].Trim('"');
            d[k] = v;
        }
        else
            d[k] = null;
    }
    return d;
}

Keep it simple: with this one you don't even need NDesk.Options for simple Apps.

And how easy would it be to add your multiple values? Easy: just add another conditional and return Dictionary<string, object> instead!

mattjs
  • 144
  • 1
  • 5