Overview
Command-line arguments into a record: declare the record, and get its parser and its help.
(import (std argparse))
(def/cmdline-choices (: Level (Union Fast Safe Paranoid)))
(def/cmdline
(: Options (Record #:program "copy" #:summary "Copies files into a directory."
(: verbose int #:count #:short #\v #:help "Say more.")
(: dry-run bool #:short #\n #:help "Change nothing.")
(: output string #:short #\o #:default "." #:value "DIR")
(: level Level #:default Safe)
(: exclude (List string) #:short #\x #:value "GLOB")
(: files (List string) #:positional #:at-least 1 #:value "FILE"))))
(defun (main args)
(def (Ok opts) (cmdline-parse-Options args)
:leave ((Err e) (panic! (arg-error-message e) #:exit-code (arg-error-exit-code e))))
...)
The type of a field gives its shape on the command line.
bool | a flag. --dry-run sets it, --no-dry-run clears it. Absent is #f |
int with #:count | a counter: each -v adds one |
T | an option with a value. Required, unless it has #:default |
(Option T) | an option that can be absent |
(List T), (Vec T) | an option that can be repeated. Each one adds a value |
(Tuple A B ...) | an option that takes that many words: --size 800 600. At most 4 |
A Tuple can be inside an Option, a List or a
Vec. With #:positional, a field is an argument, not an
option. Positional fields take the arguments in the order they are
declared. A positional List or Vec takes the rest, so it
is the last positional field. The type is read by its name, so an alias
of Option or List is a plain value.
The command line follows GNU getopt_long:
-vnis-v -n. A short option with a value takes the rest of its word or the next word:-oout,-o out.--output outand--output=out. The=form is for an option of one word.- A long name is never abbreviated. Otherwise a new option could change what an old command line means.
- Options and arguments can be mixed, unless the record has
#:options-first: then the first argument ends the options. --ends the options. A lone-is an argument.- A value can start with
-: in--jobs -1,-1is the value. -hand--helpare added, unless a field has the name.--versionis added when the record has#:version.
Given twice. For a flag, the last one counts, so a command line
can override an alias. An option with one value given twice is an error,
unless it has #:last-wins. A list takes each one. A counter counts
each one.
Subcommands. A field marked #:subcommand has a union type
declared with def/cmdline-commands. Each case holds a
def/cmdline record. The options before the command’s name are the
outer record’s, and the words after it are the command’s. Each level has
its own help; the outer help lists the commands with their summaries.
(def/cmdline (: BuildOptions (Record #:summary "Builds the project." (: release bool #:short #\r))))
(def/cmdline (: TestOptions (Record #:summary "Runs the tests." (: filter (List string) #:positional))))
(def/cmdline-commands (: Command (Union (: Build BuildOptions) (: Test TestOptions))))
(def/cmdline (: Bjo (Record #:program "bjo" (: debug bool #:short #\d) (: command Command #:subcommand))))
;; bjo -d test parse → (Bjo (debug #t) (command (Test (TestOptions (filter ("parse"))))))
Ending the program. There is no function that exits. Match the
Err: arg-error-message gives the text, and
arg-error-exit-code gives 0 for help and the version, and 2 for a
wrong command line. panic! writes to standard error. To write the
help to standard output, match HelpWanted first:
(match (cmdline-parse-Options args)
((Ok opts) (run opts))
((Err (HelpWanted text)) (println text) 0)
((Err e) (panic! (arg-error-message e) #:exit-code (arg-error-exit-code e))))
The help is not wrapped: it is the same in a terminal, in a pipe and in a test.
See also: def/cmdline, parse-args, ArgError, ArgValue
Reference
arg-error-exit-codearg-error-messagearg-value-placeholdercmdline-command-entrycmdline-commandscmdline-countcmdline-dispatchcmdline-flagcmdline-given?cmdline-help-textcmdline-infocmdline-info-makecmdline-listcmdline-optioncmdline-parsecmdline-placeholdercmdline-programcmdline-scancmdline-speccmdline-subcommandcmdline-usagecmdline-valuecmdline-veccmdline-wordcmdline-words2cmdline-words3cmdline-words4parse-arg-valueparse-args
Types
ArgError
union ↑ Types
Why a parse did not give a record.
HelpWanted-hor--help. Holds the help of the level it was given at.VersionWanted--version. Holds the program's name and version.BadArgs- A wrong command line. Holds the problem, the program's name, and the usage line of the level it was found at.
See also: arg-error-message, arg-error-exit-code, ArgProblem
ArgProblem
union ↑ Types
What is wrong with a command line.
UnknownOption- An option no field has, and the nearest known name, when one is near.
MissingValue- An option whose words are missing at the end of the line.
BadValue- The option, the value, and what the option takes.
Missing- A required option, argument or command is absent.
Repeated- An option with one value is given twice, without
#:last-wins. Conflict- Two fields of one exclusive group.
NoneOf- The fields of a
#:require-onegroup, of which none is given. TooMany- The arguments that are left over.
UnknownCommand- A command no case has, and the nearest name, when one is near.
See also: ArgError
ArgValue
trait ↑ Types
A type that can be the value of an option.
%a- The type.
(impl (ArgValue Size)
(defun (parse-arg-value word)
(match (parse-size word)
((Some s) (Ok s))
(None (Err "a size such as 512, 10k or 3M")))))
Instances: string, Path, whose
placeholder is PATH, int, long, double,
char, and bool, which takes true/false,
yes/no and 1/0. An integer is an optional
sign and digits, with no spaces. Numbers are read the same on each
machine: 0.5, never 0,5.
See also: def/cmdline-choices
Cmdline
trait ↑ Types
A record that def/cmdline declares.
%a- The record.
See also: def/cmdline, parse-args
CmdlineCommands
trait ↑ Types
A union of subcommands that def/cmdline-commands declares.
%a- The union.
See also: def/cmdline-commands
CmdInfo
record ↑ Types
The table def/cmdline makes for a record.
program#:program, or "".summary#:summary, or "".version#:version, or "".after#:after, or "".options-first- Whether the record has
#:options-first. require-one- The groups of
#:require-one. specs- One entry per field, in the order they are declared.
commands- The name and summary of each subcommand.
See also: OptSpec
OptSpec
record ↑ Types
One field of a CmdInfo.
long- The long name, without --, or "" for an argument.
short- The short name, or "".
kind- 0 a flag, 1 a counter, 2 an option with a value, 3 an argument, 4 a subcommand.
words- How many words a value is.
multi- Whether it takes each one given.
required- Whether it must be given.
last-wins- Whether, given twice, the last counts.
at-least- How many values a list needs.
exclusive- The exclusive group, or "".
help- The help line.
placeholder- The placeholder, or the argument's name.
default-text- The default as the help shows it, or "".
group- The heading in the help, or "".
hidden- Whether the help leaves it out.
See also: CmdInfo
Scanned
record ↑ Types
The words given for each field. Generated code reads it; not an API for people.
info- The table.
program- The program's name.
occs- Per field, the words of each time it was given, the latest first.
command- The subcommand's name and the words after it.
See also: cmdline-scan
Functions
parse-args
function ↑ Functions
(: parse-args (-> (Vec string) (Result ArgError %a)))
(parse-args args)
Parses the command line as a record declared with def/cmdline.
%a- The record. The type the result is used as selects it.
args- The arguments, as main gets them.
- returns
- The record, or why the words do not make one.
(def (: r (Result ArgError Options)) (parse-args args))
cmdline-parse-Name, which def/cmdline declares, is the same
function at one type, and needs no annotation.
See also: cmdline-parse, ArgError
arg-error-message
function ↑ Functions
(: arg-error-message (-> ArgError string))
(arg-error-message e)
The text to show for an ArgError.
e- The error.
- returns
- The help or the version, as they are. For a wrong command line, three
lines: what is wrong, the usage line, and
Try 'prog --help' for more.
See also: arg-error-exit-code
arg-error-exit-code
function ↑ Functions
(: arg-error-exit-code (-> ArgError int))
(arg-error-exit-code e)
The exit code for an ArgError.
e- The error.
- returns
- 0 for help and the version. 2, the usual code for a wrong command line, for the rest.
See also: arg-error-message
parse-arg-value
function ↑ Functions
(: parse-arg-value (-> string (Result string %a)))
Reads one word as a value.
word- The word.
- returns
- The value, or what the type takes, to complete the sentence
"--name takes ...":
"an int".
See also: ArgValue
arg-value-placeholder
function ↑ Functions
(: arg-value-placeholder (-> (Option %a) string))
The placeholder of the type in the help.
type- None, at the type. Only its type is used.
- returns
- The placeholder, or "" for the type's name in capitals, which is the default.
See also: ArgValue
cmdline-parse
function ↑ Functions
(: cmdline-parse (-> (List string) string (Result ArgError %a)))
Parses words as the record.
words- The words.
program- The name for the usage line, or "" for the record's own.
- returns
- The record, or why not.
See also: parse-args
cmdline-info
function ↑ Functions
(: cmdline-info (-> (Option %a) CmdInfo))
The table of the record’s options.
type- None, at the record. Only its type is used.
- returns
- The table.
See also: CmdInfo, cmdline-help-text
cmdline-dispatch
function ↑ Functions
(: cmdline-dispatch (-> string (List string) string (Option (Result ArgError %a))))
Parses the words after a command’s name.
name- The command's name.
words- The words after it.
program- The name for the usage line: the program and the command.
- returns
- None when no case has the name, else the parse.
See also: CmdlineCommands
cmdline-commands
function ↑ Functions
(: cmdline-commands (-> (Option %a) (List (Tuple string string))))
Each command’s name and summary.
type- None, at the union. Only its type is used.
- returns
- The commands, in the order of the cases.
See also: CmdlineCommands
cmdline-help-text
function ↑ Functions
(: cmdline-help-text (-> CmdInfo string string))
(cmdline-help-text info program)
The help of a record.
info- The record's table.
program- The program's name, for the usage line.
- returns
- The help, without a newline at the end.
See also: cmdline-usage
cmdline-usage
function ↑ Functions
(: cmdline-usage (-> CmdInfo string string))
(cmdline-usage info program)
The usage line of a record: Usage: prog [OPTIONS] FILE…
info- The record's table.
program- The program's name.
- returns
- The line.
See also: cmdline-help-text
cmdline-scan
function ↑ Functions
(: cmdline-scan (-> CmdInfo string (List string) (Result ArgError Scanned)))
(cmdline-scan info program words)
Reads words against a table, and checks them. Generated code calls it; not an API for people.
info- The table.
program- The program's name.
words- The words.
- returns
- The words given for each field, or the first problem.
See also: Scanned
cmdline-spec
function ↑ Functions
(: cmdline-spec (-> string string int int bool bool bool int string string string string string bool OptSpec))
(cmdline-spec long short kind words multi required last-wins at-least
exclusive help placeholder default-text group hidden)
Makes an OptSpec. Generated code calls it; not an API for people.
long- See OptSpec.
short- See OptSpec.
kind- See OptSpec.
words- See OptSpec.
multi- See OptSpec.
required- See OptSpec.
last-wins- See OptSpec.
at-least- See OptSpec.
exclusive- See OptSpec.
help- See OptSpec.
placeholder- See OptSpec.
default-text- See OptSpec.
group- See OptSpec.
hidden- See OptSpec.
- returns
- The spec.
See also: OptSpec
cmdline-info-make
function ↑ Functions
(: cmdline-info-make (-> string string string string bool (List string) (List OptSpec) (List (Tuple string string)) CmdInfo))
(cmdline-info-make program summary version after options-first require-one specs commands)
Makes a CmdInfo. Generated code calls it; not an API for people.
program- See CmdInfo.
summary- See CmdInfo.
version- See CmdInfo.
after- See CmdInfo.
options-first- See CmdInfo.
require-one- See CmdInfo.
specs- See CmdInfo.
commands- See CmdInfo.
- returns
- The table.
See also: CmdInfo
cmdline-program
function ↑ Functions
(: cmdline-program (-> string))
(cmdline-program)
The name the program was started by, without its directory or extension.
- returns
- The name of the entry assembly, else of the process, else "program".
See also: def/cmdline
cmdline-placeholder
function ↑ Functions
(: cmdline-placeholder (-> string (List string) (List string) string))
(cmdline-placeholder explicit given fallback)
An option’s placeholder. Generated code calls it; not an API for people.
explicit#:value, or "".given- Per word, what
arg-value-placeholdergives. fallback- Per word, the type's name in capitals.
- returns
- The placeholder.
See also: arg-value-placeholder
cmdline-flag
function ↑ Functions
(: cmdline-flag (-> Scanned int bool bool))
(cmdline-flag sc i fallback)
A flag’s value. Generated code calls it; not an API for people.
sc- The scan.
i- The field.
fallback- The value when absent.
- returns
- The value of the last one given, else fallback.
See also: Scanned
cmdline-count
function ↑ Functions
(: cmdline-count (-> Scanned int int))
(cmdline-count sc i)
A counter’s value. Generated code calls it; not an API for people.
sc- The scan.
i- The field.
- returns
- How many times it was given.
See also: Scanned
cmdline-given?
function ↑ Functions
(: cmdline-given? (-> Scanned int bool))
(cmdline-given? sc i)
Whether a field was given. Generated code calls it; not an API for people.
sc- The scan.
i- The field.
- returns
- #t when it was given.
See also: Scanned
cmdline-value
function ↑ Functions
(: cmdline-value (-> Scanned int (-> (List string) (Result string %a)) (Result ArgError %a)))
(cmdline-value sc i conv)
An option’s value. Generated code calls it; not an API for people.
sc- The scan.
i- The field.
conv- Converts the words.
- returns
- The last value given, converted.
See also: Scanned
cmdline-option
function ↑ Functions
(: cmdline-option (-> Scanned int (-> (List string) (Result string %a)) (Result ArgError (Option %a))))
(cmdline-option sc i conv)
An Option field’s value. Generated code calls it; not an API for people.
sc- The scan.
i- The field.
conv- Converts the words.
- returns
- None when absent, else the value, converted.
See also: Scanned
cmdline-list
function ↑ Functions
(: cmdline-list (-> Scanned int (-> (List string) (Result string %a)) (Result ArgError (List %a))))
(cmdline-list sc i conv)
A List field’s values. Generated code calls it; not an API for people.
sc- The scan.
i- The field.
conv- Converts the words.
- returns
- Each value, in the order given, converted.
See also: Scanned
cmdline-vec
function ↑ Functions
(: cmdline-vec (-> Scanned int (-> (List string) (Result string %a)) (Result ArgError (Vec %a))))
(cmdline-vec sc i conv)
A Vec field’s values. Generated code calls it; not an API for people.
sc- The scan.
i- The field.
conv- Converts the words.
- returns
- Each value, in the order given, converted.
See also: Scanned
cmdline-subcommand
function ↑ Functions
(: cmdline-subcommand (-> Scanned (-> string (List string) string (Option (Result ArgError %a))) (Result ArgError %a)))
(cmdline-subcommand sc dispatch)
A subcommand’s value. Generated code calls it; not an API for people.
sc- The scan.
dispatch- Parses the words after the command's name.
- returns
- The command's record in its case, or why not.
See also: CmdlineCommands
cmdline-word
function ↑ Functions
(: cmdline-word (-> (List string) (Result string %a)))
(cmdline-word ws)
Converts one word. Generated code calls it; not an API for people.
ws- The words of one value.
- returns
- The value.
See also: ArgValue
cmdline-words2
function ↑ Functions
(: cmdline-words2 (-> (List string) (Result string (Tuple %a %b))))
(cmdline-words2 ws)
Converts two words to a Tuple. Generated code calls it; not an API for people.
ws- The words of one value.
- returns
- The value.
See also: ArgValue
cmdline-words3
function ↑ Functions
(: cmdline-words3 (-> (List string) (Result string (Tuple %a %b %c))))
(cmdline-words3 ws)
Converts three words to a Tuple. Generated code calls it; not an API for people.
ws- The words of one value.
- returns
- The value.
See also: ArgValue
cmdline-words4
function ↑ Functions
(: cmdline-words4 (-> (List string) (Result string (Tuple %a %b %c %d))))
(cmdline-words4 ws)
Converts four words to a Tuple. Generated code calls it; not an API for people.
ws- The words of one value.
- returns
- The value.
See also: ArgValue
cmdline-command-entry
function ↑ Functions
(: cmdline-command-entry (-> string CmdInfo (Tuple string string)))
(cmdline-command-entry name info)
A command’s line in the outer help. Generated code calls it; not an API for people.
name- The command's name.
info- The table of the command's record.
- returns
- The name and the summary.
See also: cmdline-commands
Macros
def/cmdline
macro ↑ Macros
(def/cmdline declaration)
Declares a record of command-line options, with its parser and its help.
declaration-
(: Name (Record marker ... field ...)). A field is(: name type marker ...).Record markers:
#:program "name"the name in the usage line. By default, the name the program was started by #:summary "text"the first line of the help, and the command's line in a list of commands #:version "1.2.3"adds --version#:after "text"a paragraph after the options #:options-firstthe first argument ends the options #:require-one "name"exactly one field of the exclusive group is given Field markers:
#:short #\xalso -x#:long "name"the long name. By default the field's name #:default exprthe value when absent. Shown in the help #:help "text"the field's line in the help #:value "NAME"the placeholder in the help. On a #:subcommandfield, the name in the usage line: COMMAND by default#:countan intthat counts#:positionalan argument, not an option #:at-least na list takes at least n values #:last-winsgiven twice, the last counts; otherwise twice is an error #:exclusive "name"at most one field of the group is given #:group "Heading"the field is listed under that heading in the help #:subcommanda union from def/cmdline-commands, which takes the rest of the words#:hiddenparsed, but not in the help
(def/cmdline
(: Source (Record #:program "src" #:require-one "input"
(: file (Option string) #:exclusive "input" #:help "Read a file.")
(: stdin bool #:exclusive "input" #:help "Read standard input.")
(: size (Option (Tuple int int)) #:value "W H")
(: name string #:last-wins #:default "x"))))
The form declares:
- the record, with the markers taken off its fields;
- an instance of
(Cmdline Name), whichparse-argsuses; cmdline-parse-Name, of type(-> (Vec string) (Result ArgError Name));cmdline-help-Name, of type(-> string).
These are compile errors: two options with one long or short name; a
positional list that is not the last positional field; #:count on
a field that is not an int; #:last-wins on a flag, a counter
or a list; #:default on an Option, a List or a
Vec; an exclusive group of one field; #:require-one with no
such group; a #:subcommand field beside positional fields; and a
type with no ArgValue instance.
The placeholder of an option is #:value, else what the type’s
arg-value-placeholder gives, else the type’s name in capitals:
INT. For an argument, it is the field’s name in capitals.
See also: parse-args, def/cmdline-choices, def/cmdline-commands, ArgValue
def/cmdline-choices
macro ↑ Macros
(def/cmdline-choices declaration)
Declares a union of plain cases, and its ArgValue instance.
declaration(: Name (Union Case ...)). The cases carry nothing.
(def/cmdline-choices (: Level (Union Fast Safe VeryCareful)))
;; --level fast, --level very-careful
A value is the case’s name in lower case, with words joined by -:
VeryCareful is very-careful. A wrong value is the error
--level takes one of fast, safe, very-careful, not 'quick'. The
help shows the choices as the placeholder: fast|safe|very-careful.
See also: def/cmdline, ArgValue
def/cmdline-commands
macro ↑ Macros
(def/cmdline-commands declaration)
Declares the union of a record’s subcommands.
declaration(: Name (Union (: Case Record) ...)). Each record is declared withdef/cmdline.
(def/cmdline-commands (: Command (Union (: Build BuildOptions) (: Test TestOptions))))
(def/cmdline (: Bjo (Record (: debug bool) (: command Command #:subcommand))))
The name of a command is the case’s name in kebab case: Build is
build. The form declares the union and an instance of
CmdlineCommands.
See also: def/cmdline