Skip to content
Kavachकवच

Command-line Programs: Commands

● Intermediate3 min

Parse into a union, and each case is a command with its own options, like git add and git log.

use std.cli

type Command = AddItem(name: String, count: Int = 1) | Show(limit: Int = 10)

fn main() {
    const command = cli.parse<Command>() catch e => {
        print(e)
        cli.exit(2)
        return
    }
    match command {
        Command.AddItem(name, count) => print("add {count} {name}"),
        Command.Show(limit) => print("show {limit} items"),
    }
}
src/main.kav: Kavach code
terminal
kavach run src/main.kav add-item --name milk --count 2
add 2 milk
kavach run src/main.kav show --limit 3
show 3 items
kavach run src/main.kav --help
usage: main <command> [options]
  add-item
    --name <String>        (required)
    --count <Int>          (default 1)
  show
    --limit <Int>          (default 10)
kavach run src/main.kav add-item --help
usage: main add-item [options]
  --name <String>          (required)
  --count <Int>            (default 1)

The case AddItem is the command add-item. --help before a command lists every command; after one, it shows that command's options.