Skip to content

Argument Parsing

Jan Michelfeit edited this page Feb 2, 2016 · 1 revision

Parsing arguments

In order to parse command line arguments, pass them as a string array to EasyOpt.Parse().

EasyOpt parser = new EasyOpt();
// ... set up options ... 
parser.Parse(args);

For each option in args, EasyOpt parser sets IsPresent of the corresponding Option<T> instance to true. Option parameters are stored in the corresponding Parameter<T> instance. Non-option arguments can be retrieved with EasyOpt.GetArguments() method. For more information how to access these values, see Retrieving option values & arguments.

Option formats

Options are accepted in the following formats:

  -s[PARAMETER]
  -s{SPACE}[PARAMETER]
  --long
  --long=[PARAMETER]
  --long{SPACE}[PARAMETER]
  -xyz
  -xyzs[PARAMETER]
  -xyzs{SPACE}[PARAMETER]

Arguments that start with - are classified as short options, argumeths that start with -- are classified as long options. The other arguments are interpreted as option parameters if an option with a required parameter precedes or as non-option arguments otherwise. Option list can be terminated with a single -- argument and all arguments after that are treated as non-option even when they start with -.

It is possible to list more short option after - as long as all (except possibly the last one) do not have a parameter.

Options names are case-sensitive.

Since with EasyOpt you can specify an option parameter as optional, there would be ambiguity about whether an argument following such an option is its parameter or a non-option agument. Due to this, optional parameters have to be written directly after the option (separated by = for long options):

  -s[OPTIONAL PARAMETER]
  --long=[OPTIONAL PARAMETER]
  -xyzs[OPTIONAL PARAMETER]

An option can be listed multiple times (e.g. -a -v -a). An exception to this rule is that an option parameter can not be redefined (e.g. --long=1 --long=2 is invalid).

Invalid input

If the parsed options do not comply with option settings, an exception derived from EasyOptException is thrown. Values of registered Option<T> objects and their parameters are then undefined.

There are several different exceptions for different parsing errors that provide more detailed information.

  • OptionMissingException is thrown when a required option is missing.
  • ParameterMissingException is thrown when a required option parameter is missing.
  • OptionParameterException is thrown when option parameter is invalid. This happens when parameter conversion fails, some constraints were not satisfied or parameter value is being redefined. Details about the error can be retrieved from OptionParameterException.InnerParameterException.
Clone this wiki locally