Skip to content
Kavachकवच

Command-line Programs: Arguments

● Intermediate4 min

Describe the options as a record, and cli.parse reads them, checks their types, and writes the help text for you.

use std.cli

type Args {
    input: String
    limit: Int = 10
    verbose: Bool = false
}

fn main() {
    const args = cli.parse<Args>() catch e => {
        print(e)
        cli.exit(2)
        return
    }
    print("reading {args.input}, at most {args.limit} rows, verbose: {args.verbose}")
}
src/main.kav: Kavach code
terminal
kavach run src/main.kav --input sales.csv --limit 5 --verbose
reading sales.csv, at most 5 rows, verbose: true
kavach run src/main.kav --input sales.csv
reading sales.csv, at most 10 rows, verbose: false
kavach run src/main.kav --limit 5
missing --input
usage: main [options]
  --input <String>         (required)
  --limit <Int>            (default 10)
  --verbose
kavach run src/main.kav --help
usage: main [options]
  --input <String>         (required)
  --limit <Int>            (default 10)
  --verbose
  • A field limit is the option --limit; an _ in a name is written -.
  • A field with a default may be left out. One without a default, like input, is required.
  • A Bool is a flag with no value: --verbose.
  • --help, or a mistake, gives an error whose text is the usage.