args
The args module provides command-line argument parsing with support for
positional arguments, options, flags, and subcommands.
Interface
/// Argument kind
type Kind = [`Positional, `Option, `Flag];
/// Argument descriptor
type Arg = {
name: string,
kind: Kind,
short: [string, null],
help: [string, null],
default: [string, null],
required: [bool, null]
};
/// Command descriptor (recursive for subcommands)
type Command = {
name: string,
version: [string, null],
about: [string, null],
args: Array<Arg>,
subcommands: Array<Command>
};
/// Parse result: the matched command path, and every level's args by
/// name (an option's string, a flag's "true" or "false", null when absent)
type ParseResult = {
command: Array<string>,
values: Map<string, [string, null]>
};
/// create a positional argument descriptor
val positional: fn(#name: string, ?#help: [string, null], ?#required: [bool, null]) -> Arg;
/// create an option argument descriptor (--name value)
val option: fn(#name: string, ?#short: [string, null], ?#help: [string, null], ?#default: [string, null], ?#required: [bool, null]) -> Arg;
/// create a flag argument descriptor (--name, boolean)
val flag: fn(#name: string, ?#short: [string, null], ?#help: [string, null]) -> Arg;
/// create a command descriptor
val command: fn(#name: string, ?#version: [string, null], ?#about: [string, null], ?#subcommands: Array<Command>, args: Array<Arg>) -> Command;
/// parse the program's arguments (sys::args) against the spec. A
/// flag's value is "true" or "false". --help and --version answer
/// `ArgHelp with the text to print, a usage error `ArgError.
val parse: fn(cmd: Command) -> [ParseResult, Error<[`ArgError(string), `ArgHelp(string)]>];
parse reads the program’s own arguments, the ones sys::args returns.
In values an option’s value is its string, and a flag’s is "true" or
"false"; every command level on the path to the matched subcommand puts
its args there, so a subcommand may not reuse an enclosing command’s arg
name (parse refuses the spec with `ArgError). --help and --version answer `ArgHelp with the text
to print, and a usage error answers `ArgError with clap’s message,
so a script prints either and exits, 0 for help and non-zero for an
error, as the example does.
Example
let cli: args::ParseResult = select args::parse(
args::command(
#name: "example",
#version: "0.1.0",
#about: "An example CLI tool",
#subcommands: [
args::command(
#name: "serve",
[args::option(#name: "port", #short: "p", #default: "8080")]
)
],
[
args::positional(#name: "file", #help: "Input file"),
args::option(#name: "count", #short: "n", #default: "1", #help: "Repeat count"),
args::flag(#name: "verbose", #short: "v", #help: "Verbose output")
]
)
) {
args::ParseResult as r => r,
Error<'e> as e => select e.0 {
`ArgHelp(text) => {
println(text);
sys::exit(text ~ 0)
},
`ArgError(text) => {
println(text);
sys::exit(text ~ 2)
}
}
};
println("Command: [cli.command]");
println("Values: [cli.values]");