Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

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
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 command-line arguments against the spec.
val parse: fn(cmd: Command) -> [ParseResult, Error<`ArgError(string)>];

Example

use args;

let cli = 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")
        ]
    )
)$;

println("Command: [cli.command]");
println("Values: [cli.values]");