cli
Parse command-line arguments: flags, options with values, positional arguments, and a help text generated from the same declarations.
Declare what the program accepts on a Parser, then call parse(&os.args()). It returns Args, or one of two errors: cli.Help when the user asked for -h or --help, holding the help text, and cli.UsageError when the command line is wrong, holding a message and the usage line.
The usual forms work: -v -v or -vv, -o file or -ofile, --output file or --output=file, and -- to end the options. Options and arguments can be mixed in any order.
A typical program
Section titled “A typical program”import cliimport os
let mut p = cli.parser("grab", "Download a file.")p.flag("verbose", "v", "say more")p.option("output", "o", "where to write", "out.txt")p.positional("url", "what to download")let args = p.parse(&os.args()) catch { cli.Help(h) => { print(h.text) os.exit(0) return } cli.UsageError(u) => { eprint(f"error: {u.message}") eprint(u.usage) os.exit(2) return }}if args.flag("verbose") { print(f"downloading {args.positional("url")}")}print(args.option("output"))Read the parsed values
Section titled “Read the parsed values”parse skips the first item, the program’s own name, as os.args() gives it.
import cli
let mut p = cli.parser("grab", "Download files.")p.flag("verbose", "v", "say more")p.option("output", "o", "where to write", "out.txt")p.positional("url", "what to download")p.optional("name", "file name to save as")p.rest("extra", "passed on to the server")let args = try p.parse(&["grab", "-vv", "--output=x.bin", "https://example.com", "e1", "e2"])print(args.count("verbose"))print(args.option("output"))print(args.positional("url"))print(args.get("name").unwrap_or("-"))print(args.rest().join(","))2x.binhttps://example.come1e2e1 fills the optional name; only what is left over goes to rest.
The generated help
Section titled “The generated help”import cli
let mut p = cli.parser("grab", "Download files.")p.flag("verbose", "v", "say more")p.option("output", "o", "where to write", "out.txt")p.option("retries", "", "how often to retry", "3")p.positional("url", "what to download")p.rest("extra", "passed on to the server")print(p.help())usage: grab [options] <url> [extra...]
Download files.
options: -v, --verbose say more -o, --output <value> where to write (default: out.txt) --retries <value> how often to retry (default: 3) -h, --help show this help
arguments: url what to download extra... passed on to the serverReference
Section titled “Reference”import cliFunctions
Section titled “Functions”parser
Section titled “parser”pub fn parser(name: &Str, about: &Str) -> Parserpub struct Help { pub text: Str}The help text, when the program was asked for -h or --help.
UsageError
Section titled “UsageError”pub struct UsageError { pub message: Str pub usage: Str}What was wrong with the command line, and the usage line to show with it.
Parser
Section titled “Parser”pub struct Parser {}Declares a program’s flags, options and arguments, then parses os.args() against them.
It also has 6 private field(s), so outside this module it is made only by this module’s functions, which check what goes in.
Parser.flag
Section titled “Parser.flag”pub fn flag(&mut self, long: &Str, short: &Str, help: &Str)A switch like -v / --verbose; short may be “” for none.
--help always shows the generated help, and so does -h unless the program declares a flag or option with the short name h (as ls -h does).
Parser.option
Section titled “Parser.option”pub fn option(&mut self, long: &Str, short: &Str, help: &Str, default: &Str)An option with a value like -o out.txt, --output=out.txt; default is used when it is not given.
An option always has a value: the one given, or default. args.given(&name) tells whether it was on the command line at all. An option given twice keeps the last value in option; args.all(&name) gives every value in order, for repeated options like -I a -I b.
The value after -o or --output is taken as it is, even when it starts with -.
Parser.positional
Section titled “Parser.positional”pub fn positional(&mut self, name: &Str, help: &Str)A required argument, taken in the order they are declared.
Parser.optional
Section titled “Parser.optional”pub fn optional(&mut self, name: &Str, help: &Str)An argument that may be left out; it must come after the required ones.
Positional arguments fill in the order they are declared, so an optional argument must come after the required ones. Read it with Args.get.
Parser.rest
Section titled “Parser.rest”pub fn rest(&mut self, name: &Str, help: &Str)Collects any arguments after the declared ones.
Parser.usage
Section titled “Parser.usage”pub fn usage(&self) -> StrParser.help
Section titled “Parser.help”pub fn help(&self) -> StrParser.parse
Section titled “Parser.parse”pub fn parse(&self, argv: &Vec<Str>) -> Args ! CliErrorargv[0] is the program itself and is skipped, as os.args() gives it.
An argument that starts with - is read as an option, except - alone and negative numbers such as -5 or -0.5 (unless the program declares a short option named like that digit). Anything else that starts with - goes after --.
pub struct Args {}It also has 5 private field(s), so outside this module it is made only by this module’s functions, which check what goes in.
Args.flag
Section titled “Args.flag”pub fn flag(&self, name: &Str) -> boolWhether a flag was given; asking for a name that was never declared is a bug and panics.
Asking for a name that was never declared panics: that is a mistake in the program, not in the command line. The same holds for count, option and positional.
Args.count
Section titled “Args.count”pub fn count(&self, name: &Str) -> i64How many times a flag was given, for things like -vvv.
Args.given
Section titled “Args.given”pub fn given(&self, name: &Str) -> boolWhether an option was given on the command line, as opposed to left at its default.
Args.all
Section titled “Args.all”pub fn all(&self, name: &Str) -> Vec<Str>Every value an option was given, in order (-I a -I b); empty when it was not given.
Args.option
Section titled “Args.option”pub fn option(&self, name: &Str) -> StrAn option’s value (the last one, if given more than once), or its default.
Args.get
Section titled “Args.get”pub fn get(&self, name: &Str) -> Option<Str>A positional argument’s value; None only for an optional one that was left out.
Args.positional
Section titled “Args.positional”pub fn positional(&self, name: &Str) -> StrA required positional argument’s value.
Only for arguments declared with positional. An optional one panics here when it was left out; use get.
Args.rest
Section titled “Args.rest”pub fn rest(&self) -> &Vec<Str>Constants and error sets
Section titled “Constants and error sets”CliError
Section titled “CliError”pub error CliError = Help | UsageError