parseArgs

Parses options from the given list of arguments. Note that the first argument is assumed to be the program name and is ignored.

pure
T
parseArgs
(
T
)
(
const(string[]) arguments
,)
if (
is(T == struct)
)

Return Value

Type: T

Options structure filled out with values.

Throws

ArgParseError if arguments are invalid.

Examples

1 static struct Options
2 {
3     string testValue;
4 
5     @Option("test")
6     void test(string arg) pure
7     {
8         testValue = arg;
9     }
10 
11     @Option("help")
12     @Help("Prints help on command line arguments.")
13     OptionFlag help;
14 
15     @Option("version")
16     @Help("Prints version information.")
17     OptionFlag version_;
18 
19     @Argument("path", Multiplicity.oneOrMore)
20     @Help("Path to the build description.")
21     string[] path;
22 
23     @Option("dryrun", "n")
24     @Help("Don't make any functional changes. Just print what might" ~
25           " happen.")
26     OptionFlag dryRun;
27 
28     @Option("threads", "j")
29     @Help("The number of threads to use. Default is the number of" ~
30           " logical cores.")
31     size_t threads;
32 
33     @Option("color")
34     @Help("When to colorize the output.")
35     @MetaVar("{auto,always,never}")
36     string color = "auto";
37 }
38 
39 immutable options = parseArgs!Options([
40         "arg1",
41         "--version",
42         "--test",
43         "test test",
44         "--dryrun",
45         "--threads",
46         "42",
47         "--color=test",
48         "--",
49         "arg2",
50     ]);
51 
52 assert(options == Options(
53         "test test",
54         OptionFlag.no,
55         OptionFlag.yes,
56         ["arg1", "arg2"],
57         OptionFlag.yes,
58         42,
59         "test",
60         ));
static struct Options
{
    @Option("help")
    @Help("Prints help on command line usage.")
    OptionFlag help;

    @Option("version")
    @Help("Prints version information.")
    OptionFlag version_;

    @Argument("command", Multiplicity.optional)
    @Help("Subcommand")
    string command;

    @Argument("args", Multiplicity.zeroOrMore)
    @Help("Arguments for the command.")
    const(string)[] args;
}

immutable options = parseArgs!Options([
        "--version",
        "status",
        "--asdf",
        "blah blah"
    ], Config.ignoreUnknown);

assert(options == Options(
        OptionFlag.no,
        OptionFlag.yes,
        "status",
        ["--asdf", "blah blah"]
        ));

Meta