1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
|
getopt: command line option parsing
getopt provides an interface for parsing command line arguments and
automatically generates a brief help message explaining the command usage. See
[[parse]] or [[tryparse]] for the main entry point.
The caller provides [[help]] arguments to specify which command line flags and
parameters are supported, and to provide some brief help text which describes
their use. Provide [[flag_help]] to add a flag which does not take a parameter,
and [[parameter_help]] to add a flag with a required parameter. The first
[[cmd_help]] is used as a short, one-line summary of the command's purpose, and
any later [[cmd_help]] arguments are used to provide the name of any arguments
which follow the options list.
By convention, the caller should sort the list of options, first providing all
flags, then all parameters, alpha-sorted within each group by the flag rune.
// Usage for sed
const cmd = getopt::parse(os::args,
"stream editor",
('E', "use extended regular expressions"),
('i', "edit files in place"),
('s', "treat files as separate, rather than one continuous stream"),
('z', "separate lines by NUL characters"),
('e', "script", "execute commands from script"),
('f', "file", "execute commands from a file"),
"files...",
);
defer getopt::finish(&cmd);
for (let opt .. cmd.opts) {
switch (opt.0) {
case 'E' =>
extended = true;
case 'i' =>
in_place = true;
case 's' =>
continuous = false;
case 'z' =>
sep = '\0';
case 'e' =>
script = opt.1;
case 'f' =>
file = opt.1;
case => abort(); // unreachable
};
};
for (let arg .. cmd.args) {
// ...
};
If any non-option arguments are provided on the command line, the options list
is terminated by the first non-option argument, or by a "--" argument if one is
present. The arguments list is NOT reordered to accomodate for options which
appear after other arguments. Overriding the behavior of "--" is not supported;
providing '-' as a flag or parameter rune will have no effect.
If "-h" is not among the options defined by the caller, the "-h" option will
cause a summary of the command usage to be printed to [[os::stderr]] (see also
[[printhelp]]), and [[os::exit]] will be called with [[os::status::SUCCESS]].
The help text is brief and should serve only as a reminder. It is recommended
that your command line program be accompanied by a man page to provide detailed
usage information. 'h' may be provided as a flag or parameter rune to override
the default behavior.
|