Parse command line arguments - adamadair/NCmd GitHub Wiki
NCmd provides the ArgumentParser class to help with handling arguments passed from the command line to the program. There are a number of different ways of doing arguments and NCmd tries to keep it simple, and as such it may not be suitable for all purposes.
Argument format strings
Regex-like BNF Grammar:
name: .+
type: [=:]
sep: ( [^{}]+ | '{' .+ '}' )?
aliases: ( name type sep ) ( '|' name type sep )*
Each '|'-delimited name is an alias for the associated action. If the format string ends in a '=', it has a required value. If the format string ends in a ':', it has an optional value. If neither '=' or ':' is present, no value is supported. '=' or ':' need only be defined on one alias, but if they are provided on more than one they must be consistent.
Each alias portion may also end with a "key/value separator", which is used to split Argument values if the Argument accepts > 1 value. If not specified, it defaults to '=' and ':'. If specified, it can be any character except '{' and '}' OR the string between '{' and '}'. If no separator should be used (i.e. the separate values should be distinct arguments), then "{}" should be used as the separator.
Options are extracted either from the current Argument by looking for the Argument name followed by an '=' or ':', or is taken from the following Argument IFF:
- The current Argument does not contain a '=' or a ':'
- The current Argument requires a value (i.e. not a Argument type of ':')
The 'name' used in the Argument format string does NOT include any leading Argument indicator, such as '-', '--', or '/'. All three of these are permitted/required on any named Argument.
Argument bundling is permitted so long as:
- '-' is used to start the Argument group
- all of the bundled options are a single character
- at most one of the bundled options accepts a value, and the value provided starts from the next character to the end of the string.
This allows specifying '-a -b -c' as '-abc', and specifying '-D name=value' as '-Dname=value'.
Argument processing is disabled by specifying "--". All options after "--" are returned by ArgumentParser.Parse() unchanged and unprocessed.
Unprocessed options are returned from ArgumentParser.Parse().
Examples
int verbose = 0;
ArgumentParser p = new ArgumentParser ()
.Add ("v", v => ++verbose)
.Add ("name=|value=", v => Console.WriteLine (v));
p.Parse (new string[]{"-v", "--v", "/v", "-name=A", "/name", "B", "extra"});
The above would parse the argument string array, and would invoke the lambda expression three times, setting `verbose' to 3 when complete. It would also print out "A" and "B" to standard output.
The returned array would contain the string "extra".
C# 3.0 collection initializers are supported and encouraged:
var p = new ArgumentParser () {
{ "h|?|help", v => ShowHelp () },
};