Skip to content
Weaverv0.5.0

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.

Terminal window
wv add weft/cli

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.

Terminal window
wv build -o count main.wft
./count -l -w 3 a.txt b.txt
2 a.txt
1 b.txt

Short flags group, and a value can follow its option glued: -lm1 is -l -m 1. -- ends the options.

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

A wrong command line never reaches main: the message goes to standard error, and the program exits with code 2.

$ ./count --colour a.txt
count: unknown option "--colour"
Try "count --help".
$ ./count -w x a.txt
count: 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:

Terminal window
source <(./count --completion=bash)

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.print
import 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)`
}
#Cli
type AddArgs = {
/// The priority, 1 to 3
priority: Int `cli(short: 'p', default: "2")`
/// What to do
text: String[] `cli(positional, value: "TEXT")`
}
#Cli
enum 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 bread
add "buy bread", priority 1
$ ./todo clear-all
clear all
$ ./todo
todo: expected a command: add, list, clear-all
Try "todo --help".

todo --help lists the commands with their help, and todo add --help describes one of them.

  • Two flags that contradict each other are settled by order: binary: Bool `cli(short: 'b', overrides: ["text"])` makes a -b clear a -t written before it.
  • #Cli(usageStatus: 1) changes the exit code of a usage error, to imitate an existing tool.
  • main can also take args: String[], the raw arguments, and parse them itself with Args.parse(args), which returns the arguments or a CliError.
  • Settings that also come from files and the environment are a configuration: weft/config reads its own options, --set and --config, and gives the rest back to the program.