Processing of command line options.
The getopt
module implements a getopt
function, which adheres to the POSIX syntax for command line options. GNU extensions are supported in the form of long options introduced by a double dash ("--"). Support for bundling of command line options, as was the case with the more traditional single-letter approach, is provided but not enabled by default.
getopt
is simpler than its Perl counterpart because getopt
infers the expected parameter types from the static types of the passed-in pointers. Thrown on one of the following conditions:
std.getopt.config.passThrough
was not present.std.getopt.config.required
was present.Parse and remove command line options from a string array.
import std.getopt; string data = "file.dat"; int length = 24; bool verbose; enum Color { no, yes }; Color color; void main(string[] args) { auto helpInformation = getopt( args, "length", &length, // numeric "file", &data, // string "verbose", &verbose, // flag "color", "Information about this color", &color); // enum ... if (helpInformation.helpWanted) { defaultGetoptPrinter("Some information about the program.", helpInformation.options); } }The
getopt
function takes a reference to the command line (as received by main
) as its first argument, and an unbounded number of pairs of strings and pointers. Each string is an option meant to "fill" the value referenced by the pointer to its right (the "bound" pointer). The option string in the call to getopt
should not start with a dash. In all cases, the command-line options that were parsed and used by getopt
are removed from args
. Whatever in the arguments did not look like an option is left in args
for further processing by the program. Values that were unaffected by the options are not touched, so a common idiom is to initialize options to their defaults and then invoke getopt
. If a command-line argument is recognized as an option with a parameter and the parameter cannot be parsed properly (e.g., a number is expected but not present), a ConvException
exception is thrown. If std.getopt.config.passThrough
was not passed to getopt
and an unrecognized command-line argument is found, a GetOptException
is thrown. Depending on the type of the pointer being bound, getopt
recognizes the following kinds of options: true
. Additionally true
or false
can be set within the option separated with an "=" sign: bool verbose = false, debugging = true; getopt(args, "verbose", &verbose, "debug", &debugging);To set
verbose
to true
, invoke the program with either --verbose
or --verbose=true
. To set debugging
to false
, invoke the program with --debugging=false
. uint timeout; getopt(args, "timeout", &timeout);To set
timeout
to 5
, invoke the program with either --timeout=5
or --timeout 5
. uint paranoid; getopt(args, "paranoid+", ¶noid);Invoking the program with "--paranoid --paranoid --paranoid" will set
paranoid
to 3. Note that an incremental option never expects a parameter, e.g., in the command line "--paranoid 42 --paranoid", the "42" does not set paranoid
to 42; instead, paranoid
is set to 2 and "42" is not considered as part of the normal program arguments. enum Color { no, yes }; Color color; // default initialized to Color.no getopt(args, "color", &color);To set
color
to Color.yes
, invoke the program with either --color=yes
or --color yes
. string outputFile; getopt(args, "output", &outputFile);Invoking the program with "--output=myfile.txt" or "--output myfile.txt" will set
outputFile
to "myfile.txt". If you want to pass a string containing spaces, you need to use the quoting that is appropriate to your shell, e.g. --output='my file.txt'. string[] outputFiles; getopt(args, "output", &outputFiles);Invoking the program with "--output=myfile.txt --output=yourfile.txt" or "--output myfile.txt --output yourfile.txt" will set
outputFiles
to [ "myfile.txt", "yourfile.txt" ]
. Alternatively you can set arraySep
as the element separator: string[] outputFiles; arraySep = ","; // defaults to "", separation by whitespace getopt(args, "output", &outputFiles);With the above code you can invoke the program with "--output=myfile.txt,yourfile.txt", or "--output myfile.txt,yourfile.txt".
double[string] tuningParms; getopt(args, "tune", &tuningParms);Invoking the program with e.g. "--tune=alpha=0.5 --tune beta=0.6" will set
tuningParms
to [ "alpha" : 0.5, "beta" : 0.6 ]. Alternatively you can set arraySep
as the element separator: double[string] tuningParms; arraySep = ","; // defaults to "", separation by whitespace getopt(args, "tune", &tuningParms);With the above code you can invoke the program with "--tune=alpha=0.5,beta=0.6", or "--tune alpha=0.5,beta=0.6". In general, the keys and values can be of any parsable types.
void function()
, void function(string option)
, void function(string option, string value)
, or their delegate equivalents. void main(string[] args) { uint verbosityLevel = 1; void myHandler(string option) { if (option == "quiet") { verbosityLevel = 0; } else { assert(option == "verbose"); verbosityLevel = 2; } } getopt(args, "verbose", &myHandler, "quiet", &myHandler); }
int main(string[] args) { uint verbosityLevel = 1; bool handlerFailed = false; void myHandler(string option, string value) { switch (value) { case "quiet": verbosityLevel = 0; break; case "verbose": verbosityLevel = 2; break; case "shouting": verbosityLevel = verbosityLevel.max; break; default : stderr.writeln("Unknown verbosity level ", value); handlerFailed = true; break; } } getopt(args, "verbosity", &myHandler); return handlerFailed ? 1 : 0; }
bool verbose; getopt(args, "verbose|loquacious|garrulous", &verbose);
getopt
the caseSensitive
directive like this: bool foo, bar; getopt(args, std.getopt.config.caseSensitive, "foo", &foo, "bar", &bar);In the example above, "--foo" and "--bar" are recognized, but "--Foo", "--Bar", "--FOo", "--bAr", etc. are rejected. The directive is active until the end of
getopt
, or until the converse directive caseInsensitive
is encountered: bool foo, bar; getopt(args, std.getopt.config.caseSensitive, "foo", &foo, std.getopt.config.caseInsensitive, "bar", &bar);The option "--Foo" is rejected due to
std.getopt.config.caseSensitive
, but not "--Bar", "--bAr" etc. because the directive std.getopt.config.caseInsensitive
turned sensitivity off before option "bar" was parsed. -t
). getopt
accepts such parameters seamlessly. When used with a double-dash (e.g. --t
), a single-letter option behaves the same as a multi-letter option. When used with a single dash, a single-letter option is accepted. If the option has a parameter, that must be "stuck" to the option without any intervening space or "=": uint timeout; getopt(args, "timeout|t", &timeout);To set
timeout
to 5
, use either of the following: --timeout=5
, --timeout 5
, --t=5
, --t 5
, or -t5
. Forms such as -t 5
and -timeout=5
will be not accepted. For more details about short options, refer also to the next section. "-a -b -c"
. By default, this option is turned off. You can turn it on with the std.getopt.config.bundling
directive: bool foo, bar; getopt(args, std.getopt.config.bundling, "foo|f", &foo, "bar|b", &bar);In case you want to only enable bundling for some of the parameters, bundling can be turned off with
std.getopt.config.noBundling
. bool foo, bar; getopt(args, std.getopt.config.required, "foo|f", &foo, "bar|b", &bar);Only the option directly following
std.getopt.config.required
is required. getopt
did not understand, it can pass the std.getopt.config.passThrough
directive to getopt
: bool foo, bar; getopt(args, std.getopt.config.passThrough, "foo", &foo, "bar", &bar);An unrecognized option such as "--baz" will be found untouched in
args
after getopt
returns. getopt
function returns a struct of type GetoptResult
. This return value contains information about all passed options as well a bool GetoptResult.helpWanted
flag indicating whether information about these options was requested. The getopt
function always adds an option for --help|-h
to set the flag if the option is seen on the command line. getopt
gathering. It is used to separate program options from other parameters (e.g., options to be passed to another program). Invoking the example above with "--foo -- --bar"
parses foo but leaves "--bar" in args
. The double-dash itself is removed from the argument array unless the std.getopt.config.keepEndOfOptions
directive is given.auto args = ["prog", "--foo", "-b"]; bool foo; bool bar; auto rslt = getopt(args, "foo|f", "Some information about foo.", &foo, "bar|b", "Some help message about bar.", &bar); if (rslt.helpWanted) { defaultGetoptPrinter("Some information about the program.", rslt.options); }
Configuration options for getopt
.
You can pass them to getopt
in any position, except in between an option string and its bound pointer.
Turn case sensitivity on
Turn case sensitivity off (default)
Turn bundling
on
Turn bundling off (default)
Pass unrecognized arguments through
Signal unrecognized arguments as errors (default)
Stop at first argument that does not look like an option
Do not erase the endOfOptions separator from args
Make the next option a required
option
The result of the getopt
function.
helpWanted
is set if the option --help
or -h
was passed to the option parser.
Flag indicating if help was requested
All possible options
Information about an option.
The short symbol for this option
The long symbol for this option
The description of this option
If a option is required
, not passing it will result in an error
The option character (default '-').
Defaults to '-' but it can be assigned to prior to calling getopt
.
The string that conventionally marks the end of all options (default '--').
Defaults to "--" but can be assigned to prior to calling getopt
. Assigning an empty string to endOfOptions
effectively disables it.
The assignment character used in options with parameters (default '=').
Defaults to '=' but can be assigned to prior to calling getopt
.
The string used to separate the elements of an array or associative array (default is "" which means the elements are separated by whitespace).
Defaults to "" but can be assigned to prior to calling getopt
.
This function prints the passed Option
s and text
in an aligned manner on stdout
.
The passed text
will be printed first, followed by a newline, then the short and long version of every option will be printed. The short and long version will be aligned to the longest option of every Option
passed. If the option is required, then "Required:" will be printed after the long version of the Option
. If a help message is present it will be printed next. The format is illustrated by this code:
foreach (it; opt) { writefln("%*s %*s%s%s", lengthOfLongestShortOption, it.optShort, lengthOfLongestLongOption, it.optLong, it.required ? " Required: " : " ", it.help); }
string text
| The text to printed at the beginning of the help output. |
Option[] opt
| The Option extracted from the getopt parameter. |
This function writes the passed text
and Option
into an output
range in the manner described in the documentation of function defaultGetoptPrinter
.
Output output
| The output range used to write the help information. |
string text
| The text to print at the beginning of the help output . |
Option[] opt
| The Option extracted from the getopt parameter. |
© 1999–2017 The D Language Foundation
Licensed under the Boost License 1.0.
https://dlang.org/phobos/std_getopt.html