Skip to content

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.

import cli
import 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"))

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(","))
2
x.bin
https://example.com
e1
e2

e1 fills the optional name; only what is left over goes to rest.

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 server
import cli
pub fn parser(name: &Str, about: &Str) -> Parser
pub struct Help {
pub text: Str
}

The help text, when the program was asked for -h or --help.

pub struct UsageError {
pub message: Str
pub usage: Str
}

What was wrong with the command line, and the usage line to show with it.

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.

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).

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 -.

pub fn positional(&mut self, name: &Str, help: &Str)

A required argument, taken in the order they are declared.

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.

pub fn rest(&mut self, name: &Str, help: &Str)

Collects any arguments after the declared ones.

pub fn usage(&self) -> Str
pub fn help(&self) -> Str
pub fn parse(&self, argv: &Vec<Str>) -> Args ! CliError

argv[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.

pub fn flag(&self, name: &Str) -> bool

Whether 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.

pub fn count(&self, name: &Str) -> i64

How many times a flag was given, for things like -vvv.

pub fn given(&self, name: &Str) -> bool

Whether an option was given on the command line, as opposed to left at its default.

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.

pub fn option(&self, name: &Str) -> Str

An option’s value (the last one, if given more than once), or its default.

pub fn get(&self, name: &Str) -> Option<Str>

A positional argument’s value; None only for an optional one that was left out.

pub fn positional(&self, name: &Str) -> Str

A required positional argument’s value.

Only for arguments declared with positional. An optional one panics here when it was left out; use get.

pub fn rest(&self) -> &Vec<Str>
pub error CliError = Help | UsageError