Skip to content

A command-line tool

The cli module declares a program’s flags, options and arguments, parses the command line against them, and writes the help text. --help and mistakes come back as errors, so the program decides how to show them.

import cli
fn options() -> cli.Parser {
let mut p = cli.parser(&"greet", &"Greets people.")
p.flag(&"loud", &"l", &"shout the greeting")
p.option(&"times", &"n", &"how often", &"1")
p.positional(&"name", &"who to greet")
return p
}
fn run(argv: &Vec<Str>) {
let p = options()
let args = p.parse(argv) catch {
cli.Help(h) => {
print(h.text)
return
}
cli.UsageError(e) => {
print("error: " + e.message)
print(e.usage)
return
}
}
let mut text = "hello, " + args.positional(&"name")
if args.flag(&"loud") {
text = text.to_upper()
}
for _ in 0..args.option(&"times").to_i64().unwrap_or(1) {
print(text)
}
}
run(&["greet", "-l", "--times", "2", "Ada"])
run(&["greet"])
HELLO, ADA
HELLO, ADA
error: missing <name>
usage: greet [options] <name>

In a real program, pass &os.args() (with import os) instead of a fixed list, and os.exit(2) after a usage error.