The standard library
Slide 61 of 85
61FlagThe standard library

Command-line flags

hive.term.codec() reads command-line flags into a type of your own through T.decode, and encode writes one back. A field is --name value or --name=value, named by the field itself or by -- Flag as <name>; without its dashes — and a second, shorter name is read after one dash: -- Flag as dry-run n; is --dry-run and -n alike, -n value and -n=value. A failure is a hive.term.FlagError, whose path is the flag as written.

  • T.decode reads one Str, split the way a shell splits a line, so a quoted value stays one word. hive.term.flags() is the program's own arguments as that line, each word quoted again where it holds a space, a quote or a backslash: args() hands them over with the shell's quotes already gone, so joining it would split a quoted value a second time.
  • A Bool flag standing alone is true, and it takes the word after it only when that word is true or false — which is how encode writes one, --dry-run true.
  • A vector is its flag repeated, and an absent vector is empty. Any other flag given twice is an error.
  • A field with no Default has to be there, a Bool included. An Atom flag takes only atoms the program mentions.
  • The words before the first flag, and everything after a lone --, are the program's own, and hive.term.positional(line) answers with them. Between them is nothing but flags and their values: a flag the type does not declare is an error that lists the ones it does, and so is a word that is no flag's value — it goes before the flags or after --.
Flags into a type
type Options {
	name: Str
	dryRun: Bool -- Flag as dry-run; Default as false;
	count: Int -- Default as 10;
}

proc main(): void {
	// The line hive.term.flags() hands over for these arguments, the value with a space quoted again.
	line := "--name 'Ada Lovelace' --dry-run --count=3"
	if Options.decode(line, hive.term.codec()) is Result.Ok(o) {
		echo "{o.name} {o.dryRun} {o.count}"
	}

	// A flag with no Default has to be there.
	if Options.decode("--dry-run", hive.term.codec()) is Result.Error(why) {
		echo "{why.path}: expected {why.expected}, found {why.found}"
	}

	echo encode(Options("Ada Lovelace", true, 3), hive.term.codec())
}
Short names, and the program's own words
type Options {
	model: Str -- Flag as model m; Default as "small";
	verbose: Bool -- Flag as verbose v; Default as false;
}

proc main(): void {
	// What follows a lone -- is the program's own, as are any words before the flags.
	line := "-m large -v -- what is this"
	if Options.decode(line, hive.term.codec()) is Result.Ok(o) {
		echo "{o.model} {o.verbose}"
	}
	echo hive.term.positional(line)

	if Options.decode("--modle large", hive.term.codec()) is Result.Error(why) {
		echo "{why.path}: expected {why.expected}, found {why.found}"
	}
}