The standard librarySlide 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.decodereads oneStr, 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
Boolflag standing alone istrue, and it takes the word after it only when that word istrueorfalse— which is howencodewrites 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
Defaulthas to be there, aBoolincluded. AnAtomflag takes only atoms the program mentions. - The words before the first flag, and everything after a lone
--, are the program's own, andhive.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())
}You can edit this program and run it here.Tab indents, Escape leaves the program, and Ctrl+Enter runs it.
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}"
}
}You can edit this program and run it here.Tab indents, Escape leaves the program, and Ctrl+Enter runs it.