Wolfgang Thallergcc16 merge934c3885 months agoHistory
2052 lines · 60.7 KB · D
RawDownload
// Written in the D programming language. /**Processing of command line options. The getopt module implements a `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. Copyright: Copyright Andrei Alexandrescu 2008 - 2015.License:   $(HTTP www.boost.org/LICENSE_1_0.txt, Boost License 1.0).Authors:   $(HTTP erdani.org, Andrei Alexandrescu)Credits:   This module and its documentation are inspired by Perl's           $(HTTPS perldoc.perl.org/Getopt/Long.html, Getopt::Long) module. The syntax of           D's `getopt` is simpler than its Perl counterpart because $(D           getopt) infers the expected parameter types from the static types of           the passed-in pointers.Source:    $(PHOBOSSRC std/getopt.d)*//*         Copyright Andrei Alexandrescu 2008 - 2015.Distributed under the Boost Software License, Version 1.0.   (See accompanying file LICENSE_1_0.txt or copy at         http://www.boost.org/LICENSE_1_0.txt)*/module std.getopt; import std.exception : basicExceptionCtors;import std.traits; /**Thrown on one of the following conditions:$(UL  $(LI An unrecognized command-line argument is passed, and       `std.getopt.config.passThrough` was not present.)  $(LI A command-line option was not found, and       `std.getopt.config.required` was present.)  $(LI A callback option is missing a value.))*/class GetOptException : Exception{    mixin basicExceptionCtors;} static assert(is(typeof(new GetOptException("message"))));static assert(is(typeof(new GetOptException("message", Exception.init)))); /**   Parse and remove command line options from a string array.    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 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, or if a required argument is missing a `GetOptException` is thrown.  Depending on the type of the pointer being bound, `getopt` recognizes the following kinds of options:  $(OL    $(LI $(I Boolean options). A lone argument sets the option to `true`.    Additionally $(B true) or $(B 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`.    )     $(LI $(I Numeric options.) If an option is bound to a numeric type, a    number is expected as the next option, or right within the option separated    with an "=" sign: ---------  uint timeout;  getopt(args, "timeout", &timeout);---------     To set `timeout` to `5`, invoke the program with either    `--timeout=5` or $(D --timeout 5).    )     $(LI $(I Incremental options.) If an option name has a "+" suffix and is    bound to a numeric type, then the option's value tracks the number of times    the option occurred on the command line: ---------  uint paranoid;  getopt(args, "paranoid+", &paranoid);---------     Invoking the program with "--paranoid --paranoid --paranoid" will set $(D    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.    )     $(LI $(I Enum options.) If an option is bound to an enum, an enum symbol as    a string is expected as the next option, or right within the option    separated with an "=" sign: ---------  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 $(D --color yes).    )     $(LI $(I String options.) If an option is bound to a string, a string is    expected as the next option, or right within the option separated with an    "=" sign: ---------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'.    )     $(LI $(I Array options.) If an option is bound to an array, a new element    is appended to the array each time the option occurs: ---------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    $(D [ "myfile.txt", "yourfile.txt" ]).     Alternatively you can set $(LREF arraySep) 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".)     $(LI $(I Hash options.) If an option is bound to an associative array, a    string of the form "name=value" is expected as the next option, or right    within the option separated with an "=" sign: ---------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 $(LREF arraySep) 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.    )     $(LI $(I Callback options.) An option can be bound to a function or    delegate with the signature $(D void function()), $(D void function(string    option)), $(D void function(string option, string value)), or their    delegate equivalents.     $(UL        $(LI If the callback doesn't take any arguments, the callback is        invoked whenever the option is seen.        )         $(LI If the callback takes one string argument, the option string        (without the leading dash(es)) is passed to the callback.  After that,        the option string is considered handled and removed from the options        array. ---------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);}---------         )         $(LI If the callback takes two string arguments, the option string is        handled as an option with one argument, and parsed accordingly. The        option and its value are passed to the callback. After that, whatever        was passed to the callback is considered handled and removed from the        list. ---------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_names:Sometimes 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);--------- Case:By default options are case-insensitive. You can change that behaviorby passing `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 theconverse 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 $(Dstd.getopt.config.caseSensitive), but not "--Bar", "--bAr"etc. because the directive $(Dstd.getopt.config.caseInsensitive) turned sensitivity off beforeoption "bar" was parsed. Short_versus_long_options:Traditionally, 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. To set `timeout` to `5`, use either of the following: `--timeout=5`,`--timeout 5`, `--t=5`, `--t 5`, `-t5`, or `-t 5`. Forms such as`-timeout=5` will be not accepted. For more details about short options, refer also to the next section. Bundling:Single-letter options can be bundled together, i.e. "-abc" is the same as$(D "-a -b -c"). By default, this option is turned off. You can turn it onwith 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`. Required:An 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 following `std.getopt.config.required` isrequired. Passing_unrecognized_options_through:If an application needs to do its own processing of whichever arguments`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. Help_Information_Generation:If an option string is followed by another string, this string serves as adescription for this option. The `getopt` function returns a struct of type`GetoptResult`. This return value contains information about all passed optionsas well a $(D bool GetoptResult.helpWanted) flag indicating whether informationabout 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. Options_Terminator:A lone double-dash terminates `getopt` gathering. It is used toseparate program options from other parameters (e.g., options to be passedto another program). Invoking the example above with $(D "--foo -- --bar")parses foo but leaves "--bar" in `args`. The double-dash itself isremoved from the argument array unless the `std.getopt.config.keepEndOfOptions`directive is given.*/GetoptResult getopt(T...)(ref string[] args, T opts){    import std.exception : enforce;    enforce(args.length,            "Invalid arguments string passed: program name missing");    configuration cfg;    GetoptResult rslt;     GetOptException excep;    void[][string] visitedLongOpts, visitedShortOpts;    getoptImpl(args, cfg, rslt, excep, visitedLongOpts, visitedShortOpts, opts);     if (!rslt.helpWanted && excep !is null)    {        throw excep;    }     return rslt;} ///@safe unittest{    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.*/enum config {    /// Turn case sensitivity on    caseSensitive,    /// Turn case sensitivity off (default)    caseInsensitive,    /// Turn bundling on    bundling,    /// Turn bundling off (default)    noBundling,    /// Pass unrecognized arguments through    passThrough,    /// Signal unrecognized arguments as errors (default)    noPassThrough,    /// Stop at first argument that does not look like an option    stopOnFirstNonOption,    /// Do not erase the endOfOptions separator from args    keepEndOfOptions,    /// Make the next option a required option    required} /** The result of the `getopt` function. `helpWanted` is set if the option `--help` or `-h` was passed to the option parser.*/struct GetoptResult {    bool helpWanted; /// Flag indicating if help was requested    Option[] options; /// All possible options} /** Information about an option.*/struct Option {    string optShort; /// The short symbol for this option    string optLong; /// The long symbol for this option    string help; /// The description of this option    bool required; /// If a option is required, not passing it will result in an error}

Lines 1–500 of 2052.

Keyboard shortcuts

General

Show keyboard shortcuts
?
Focus the current search
/

Issues and pull requests

Open filters
f

Issues, pull requests and Inbox

Select next item
j↓
Select previous item
k↑
Open selected item
Enter
Dismiss filters or clear selection
Esc

Repository code

Go to file
t