getopt function, which adheres tothe POSIX syntax for command line options. GNU extensions aresupported in the form of long options introduced by a double dash("--"). Support for bundling of command line options, as was the casewith the more traditional single-letter approach, is provided but notenabled by default.CreditsThis module and its documentation are inspired by Perl'sGetopt::Long module. The syntax of D'sgetopt is simpler than its Perl counterpart because getopt infers the expected parameter types from the static types of the passed-in pointers.
Sourcestd/getopt.d
GetOptException:object.Exception;getopt(T...)(ref string[]args, Topts);Synopsis
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 bymain) 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 togetopt should not start with a dash. In all cases, the command-line options that were parsed and used bygetopt are removed fromargs. Whatever in the arguments did not look like an option is left inargs 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 invokegetopt. 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), aConvException exception is thrown. Ifstd.getopt.config.passThrough was not passed togetopt and an unrecognized command-line argument is found, or if a required argument is missing aGetOptException is thrown. Depending on the type of the pointer being bound,getopt recognizes the following kinds of options:bool verbose =false, debugging =true;getopt(args,"verbose", &verbose,"debug", &debugging);To setverbose totrue, invoke the program with either--verbose or--verbose=true. To setdebugging tofalse, invoke the program with--debugging=false.
uint timeout;getopt(args,"timeout", &timeout);To settimeout to5, 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 setparanoid 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.nogetopt(args,"color", &color);To setcolor toColor.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 setoutputFile 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 setoutputFiles to[ "myfile.txt", "yourfile.txt" ]. Alternatively you can setarraySep to allow multiple elements in one parameter.
string[] outputFiles;arraySep =",";// defaults to "", meaning one element per parametergetopt(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 settuningParms to [ "alpha" : 0.5, "beta" : 0.6 ]. Alternatively you can setarraySep as the element separator:
double[string] tuningParms;arraySep =",";// defaults to "", meaning one element per parametergetopt(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 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;}
Options with multiple namesSometimes option synonyms are desirable, e.g. "--verbose","--loquacious", and "--garrulous" should have the same effect. Suchalternate option names can be included in the option specification,using "|" as a separator:
bool verbose;getopt(args,"verbose|loquacious|garrulous", &verbose);
CaseBy default options are case-insensitive. You can change that behaviorby passinggetopt thecaseSensitive 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 theconverse directivecaseInsensitive 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 tostd.getopt.config.caseSensitive, but not "--Bar", "--bAr"etc. because the directivestd.getopt.config.caseInsensitive turned sensitivity off beforeoption "bar" was parsed.
Short versus long optionsTraditionally, programs accepted single-letter options preceded byonly one dash (e.g.-t).getopt accepts such parametersseamlessly. When used with a double-dash (e.g.--t), asingle-letter option behaves the same as a multi-letter option. Whenused with a single dash, a single-letter option is accepted.
BundlingSingle-letter options can be bundled together, i.e. "-abc" is the same as"-a -b -c". By default, this option is turned off. You can turn it onwith thestd.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 withstd.
getopt.config.noBundling.RequiredAn option can be marked as required. If that option is not present in thearguments an exception will be thrown.
bool foo, bar;getopt(args, std.getopt.config.required,"foo|f", &foo,"bar|b", &bar);Only the option directly followingstd.
getopt.config.required isrequired.Passing unrecognized options throughIf an application needs to do its own processing of whichever argumentsgetopt did not understand, it can pass thestd.getopt.config.passThrough directive togetopt:
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 aftergetopt returns.Help Information GenerationIf an option string is followed by another string, this string serves as adescription for this option. Thegetopt function returns a struct of typeGetoptResult. This return value contains information about all passed optionsas well abool GetoptResult.helpWanted flag indicating whether informationabout these options was requested. Thegetopt function always adds an option for--help|-h to set the flag if the option is seen on the command line.
Options TerminatorA lone double-dash terminatesgetopt gathering. It is used toseparate program options from other parameters (e.g., options to be passedto another program). Invoking the example above with"--foo -- --bar"parses foo but leaves "--bar" inargs. The double-dash itself isremoved from the argument array unless thestd.getopt.config.keepEndOfOptionsdirective is given.
autoargs = ["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);}
config: int;caseSensitivecaseInsensitivebundlingnoBundlingpassThroughnoPassThroughstopOnFirstNonOptionkeepEndOfOptionsrequiredGetoptResult;helpWanted;options;Option;optShort;optLong;help;required;optionChar;endOfOptions;endOfOptions effectively disables it.assignChar;arraySep;arraySep is set to something else, then each parameter is first split by the separator, and the individual pieces are treated as arguments to the same option.defaultGetoptPrinter(stringtext, Option[]opt);foreach (it;opt){ writefln("%*s %*s%s%s", lengthOfLongestShortOption, it.optShort, lengthOfLongestLongOption, it.optLong, it.required ?" Required: " :" ", it.help);}
stringtext | The text to printed at the beginning of the help output. |
Option[]opt | TheOption extracted from thegetopt parameter. |
defaultGetoptFormatter(Output)(Outputoutput, stringtext, Option[]opt, stringstyle = "%*s %*s%*s%s\n");Outputoutput | The output range used to write the help information. |
stringtext | The text to print at the beginning of the help output. |
Option[]opt | TheOption extracted from thegetopt parameter. |
stringstyle | The manner in which to display the output of eachOption. |