A command line
A program’s command line is a type. #Cli, from weft/cli, reads its
fields at compile time and writes the parsing, the help, the completion
scripts and the error messages; main receives the arguments already
parsed and typed.
wv add weft/cliThe program
Section titled “The program”count counts the lines and bytes of files:
import weaver.io.{print, IoError}import weaver.{Fs}import weft.cli.{Cli}
/// Counts the lines and bytes of files.#Cli(name: "count", version: "1.0")type Args = { /// Counts the lines only lines: Bool `cli(short: 'l')` /// Reads at most N files max: Int? `cli(short: 'm', value: "N")` /// The width of the columns width: Int `cli(short: 'w', default: "8")` /// The files to read files: String[] `cli(positional, value: "FILE")`}
fn main(args: Args) ! IoError { if args.files.isEmpty() { print("count: no file given, see count --help") return } val n = (args.max ?? args.files.len()).min(args.files.len()) for file in args.files[0..n] { val text = Fs.readText(file)! val lines = text.split("\n").len() - 1 val shown = if args.lines { "${lines}" } else { "${lines} ${text.byteLen()}" } print("${shown.padStart(args.width)} ${file}") }}Each field is an argument, and its kind follows from its type:
| Field | Argument |
|---|---|
Bool |
a flag, -l, --lines |
String, Int, or a type that adopts Parse |
an option that takes a value, --width=4, --width 4, -w4; required unless it has a default |
an optional, Int? |
an option that may be absent, None then |
String[] |
a repeatable option, or with positional the arguments that are not options |
The long name is the field’s name in kebab case, maxLineLength giving
--max-line-length; the help of an argument is its /// comment, and
that of the program the type’s. The cli(…) tag adds a short name, the
name of the value in the help, a default, or positional.
Running it
Section titled “Running it”wv build -o count main.wft./count -l -w 3 a.txt b.txt 2 a.txt 1 b.txtShort flags group, and a value can follow its option glued: -lm1 is
-l -m 1. -- ends the options.
Help and errors
Section titled “Help and errors”--help is written from the type:
Usage: count [OPTION]... [FILE]...Counts the lines and bytes of files.
-l, --lines Counts the lines only -m, --max=N Reads at most N files -w, --width=WIDTH The width of the columns (default: 8) --help Print this help --version Print the version --completion=SHELL Print the bash, zsh or fish completionA wrong command line never reaches main: the message goes to standard
error, and the program exits with code 2.
$ ./count --colour a.txtcount: unknown option "--colour"Try "count --help".$ ./count -w x a.txtcount: option "-w" expects an integer, got "x"Try "count --help".--version prints count 1.0. --completion=bash, zsh or fish
prints the script that completes the command line in that shell, its
options and its commands:
source <(./count --completion=bash)Subcommands
Section titled “Subcommands”A tool with several commands, like git, describes them by an enum: each
variant is a command, named in kebab case, which carries the #Cli type of
its own options, or nothing. A field tagged cli(subcommand) receives it;
the options written before the command go to the record.
import weaver.io.printimport weft.cli.{Cli}
/// Keeps a list of things to do.#Cli(name: "todo")type Todo = { /// Says what is being done verbose: Bool `cli(short: 'v')` command: Command `cli(subcommand)`}
#Clitype AddArgs = { /// The priority, 1 to 3 priority: Int `cli(short: 'p', default: "2")` /// What to do text: String[] `cli(positional, value: "TEXT")`}
#Clienum Command = /// Adds a task | Add(AddArgs) /// Lists the tasks | List /// Marks every task done | ClearAll
fn main(args: Todo) { match args.command { Add(a) => print("add \"${a.text.join(" ")}\", priority ${a.priority}") List => print("list") ClearAll => print("clear all") }}Without a command, the program does not start: a command is required.
$ ./todo add -p 1 buy breadadd "buy bread", priority 1$ ./todo clear-allclear all$ ./todotodo: expected a command: add, list, clear-allTry "todo --help".todo --help lists the commands with their help, and todo add --help
describes one of them.
Going further
Section titled “Going further”- Two flags that contradict each other are settled by order:
binary: Bool `cli(short: 'b', overrides: ["text"])`makes a-bclear a-twritten before it. #Cli(usageStatus: 1)changes the exit code of a usage error, to imitate an existing tool.maincan also takeargs: String[], the raw arguments, and parse them itself withArgs.parse(args), which returns the arguments or aCliError.- Settings that also come from files and the environment are a
configuration:
weft/configreads its own options,--setand--config, and gives the rest back to the program.