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         "--help",
42         "--version",
43         "--test",
44         "test test",
45         "--dryrun",
46         "--threads",
47         "42",
48         "--color=test",
49         "--",
50         "arg2",
51     ]);
52 
53 assert(options == Options(
54         "test test",
55         OptionFlag.yes,
56         OptionFlag.yes,
57         ["arg1", "arg2"],
58         OptionFlag.yes,
59         42,
60         "test",
61         ));
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