flag
The flag module reads command-line flags into a struct. Each field is a flag, named after the field (min_len is --min-len), and its type says what the flag takes. The values the struct holds before parsing are the defaults, and --help is written for you.
import flag
enum Format:
Text
Json
struct Opts:
port: int
verbose: bool
tag: [str]
format: Format
config: Option[str]
fn main():
o = Opts(port=8080, verbose=false, tag=[], format=Format.Text, config=None)
c = flag.cli("serve", "Serve files over HTTP.")
c.flag("port", "p", "port to listen on")
c.flag("verbose", "v", "log every request")
c.exit_on_help = false
args = ["-p", "9000", "public", "-v", "--tag", "a", "--tag=b", "--format", "json"]
match flag.parse_from(c, args, &o):
Ok(dirs):
print(o.port, o.verbose, o.tag, o.format, o.config, dirs)
Err(e):
print(e)
print(flag.parse_from(c, ["--prot", "1"], &o))9000 true ["a", "b"] Format.Json None ["public"]
Err("unknown flag --prot (did you mean --port?); serve --help lists the flags")In a program, flag.parse(c, &o) reads os.args() (without the program's name) and returns the positional arguments. Make main return a Result so a mistake on the command line is printed as error: ... with exit status 1:
import flag
struct Opts:
top: int
min_len: int
fn main() Result[int, str]:
o = Opts(top=10, min_len=1)
c = flag.cli("wc", "count the words in files")
c.flag("top", "n", "how many words to print")
c.args("[FILE...]")
files = flag.parse(c, &o)?
print(o.top, files)
return Ok(0)Functions
fn cli(name: str, about: str) Cli the program's name and a one-line description
fn flag(c: mut Cli, field: str, short: str, help: str)
a one-letter short form ("" for none) and help
fn env(c: mut Cli, field: str, var: str) an environment variable the field falls back to
fn require(c: mut Cli, field: str) the flag must be given (or set by its variable)
fn args(c: mut Cli, text: str) the usage line's positional part ("[FILE...]")
fn stop_at_args(c: mut Cli) flags end at the first positional (commands)
fn parse[T](c: Cli, out: mut T) Result[[str], str] os.args() into out; the positionals
fn parse_from[T](c: Cli, args: [str], out: mut T) Result[[str], str]
the same for args you pass
fn usage[T](c: Cli, out: T) str the --help text, out's values as defaultsc.flag(...) changes c (its first parameter is mut), so c must be a variable.
What a flag takes
| Field type | On the command line |
|---|---|
int, float | --port 80, --port=80, -p 80, -p80, -p=80 |
str | the same; the value may start with - (--offset -5) |
bool | --verbose (true), --verbose=false, --no-verbose; -v, and short ones together: -vq |
| an enum without payloads | a variant's name in any case: --format json |
[T] of one of those | repeated: --tag a --tag b |
Option[T] of one of those | None unless the flag is given |
-- ends the flags (everything after it is positional), and - alone is a positional (by convention, standard input). Positionals may come before, between or after flags, unless c.stop_at_args() was called. A flag given twice keeps the last value, except for a list, which keeps them all. Booleans also accept 1/0, yes/no and on/off.
Errors name the flag and say what was expected:
import flag
struct Opts:
port: int
rate: float
fn main():
o = Opts(port=1, rate=1.0)
c = flag.cli("app", "")
print(flag.parse_from(c, ["--port", "abc"], &o))
print(flag.parse_from(c, ["--rate"], &o))
print(flag.parse_from(c, ["-x"], &o))Err("--port: expected an integer, got `abc`")
Err("--rate needs a value (a number)")
Err("unknown flag -x; app --help lists the flags")Environment variables and required flags
c.env(field, var) reads var when the flag isn't on the command line (a list's variable holds a,b,c); c.require(field) makes parsing fail unless the flag or its variable gives a value:
import flag
import os
struct Opts:
port: int
token: str
fn main():
os.setenv("APP_PORT", "7000")
o = Opts(port=8080, token="")
c = flag.cli("app", "")
c.env("port", "APP_PORT")
c.require("token")
print(flag.parse_from(c, [], &o))
print(flag.parse_from(c, ["--token", "t0k"], &o), o.port)Err("--token is required")
Ok([]) 7000Help
-h or --help prints the usage and exits with status 0. With c.exit_on_help = false it is an Err holding the usage instead (for tests). flag.usage(c, o) returns the same text:
import flag
struct Opts:
port: int
name: str
verbose: bool
tag: [str]
fn main():
c = flag.cli("serve", "Serve files over HTTP.")
c.flag("port", "p", "port to listen on")
c.flag("verbose", "v", "log every request")
c.env("name", "SERVE_NAME")
c.args("[DIR]")
print(flag.usage(c, Opts(port=8080, name="site", verbose=false, tag=[])))serve: Serve files over HTTP.
usage: serve [flags] [DIR]
flags:
-p, --port int port to listen on (default 8080)
--name str (default "site") [$SERVE_NAME]
-v, --verbose log every request
--tag str... (repeatable)
-h, --help show this help
Commands
For a tool with commands (tool -v build --release), parse the common flags with stop_at_args(), then the command's own flags from what's left:
import flag
struct Common:
verbose: bool
struct Build:
release: bool
jobs: int
fn main():
top = flag.cli("tool", "")
top.flag("verbose", "v", "")
top.stop_at_args()
g = Common(verbose=false)
rest = flag.parse_from(top, ["-v", "build", "--release", "--jobs", "4"], &g).unwrap_or([])
if len(rest) > 0 and rest[0] == "build":
b = Build(release=false, jobs=1)
print(flag.parse_from(flag.cli("tool build", ""), rest[1..], &b), g.verbose, b)Ok([]) true Build{release: true, jobs: 4}How it works, and speed
The compiler writes a small table of each struct's fields (name, type, an enum's variants) into the program as a constant, and a setter that stores an int, float, bool, string or enum variant into field number k. flag looks each flag up in the table (in C, without copying the argument), converts its value, and calls the setter: no reflection, and no text in between. On an error, and for --help, the struct is put back as it was.
bench/std builds the parser and parses a 16-argument command line into 8 fields, against Go's flag and Rust's clap (derive) and lexopt (a match written by hand, no help text):
| Tern | Go flag | Rust clap | Rust lexopt | |
|---|---|---|---|---|
| one parse | 177 ns | 831 ns | 7,442 ns | 424 ns |
| a small CLI's binary | 149 KB | 1.7 MB | 584 KB | 319 KB |
| starting it (spawn to exit) | 1.27 ms | 1.77 ms | 1.29 ms | 1.26 ms |
| its peak memory | 1.53 MB | 3.98 MB | 1.73 MB | 1.48 MB |
Start-up is mostly the process, not the parsing: a Tern hello world takes 1.20 ms against Rust's 1.25 ms.