Quickstart Tutorial
Imagine we're building a utility for joining MP3 files.
We want the user to supply the file names as a list of command line arguments.
We also want to support an --out/-o
option so the user can specify an output filename and a --quiet/-q
flag for tuning the program's verbosity.
First we need to create an ArgParser
instance:
import std::args; var parser = args::ArgParser(); parser:helptext("Usage: mp3cat..."); parser:version("1.0");
Supplying a helptext string for the parser activates an automatic --help/-h
flag; similarly, supplying a version string activates an automatic --version/-v
flag.
Now we can register our flags and options:
parser:flag("quiet q"); parser:option("out o", "output.mp3");
Here we're setting a default value of "output.mp3"
for the --out/-o
option — this will be used if the user doesn't specify a custom value on the command line.
That's it, we're done specifying our interface. Now we can parse the program's command line arguments:
if let result = parser:parse(); $is_err(result) { $exit("error: ${result}"); }
This will exit with a suitable error message for the user if anything goes wrong.
Now we can check if the --quiet
flag was found:
if parser:found("quiet") { do_stuff_quietly(); }
And determine our output filepath:
var filepath = parser:value("out");
Positional arguments are appended to the parser's .args
vector:
for filename in parser.args { do_stuff(); }