cmder

    Declarative CLI builder for MoonBit, inspired by gunshi

    cli
    argparse
    moonbit
    Download zip
    Author
    Version
    0.3.0
    License
    MIT
    Last updated
    19 days ago
    Downloads
    2K

    No dependencies

    #cmder

    hustcer/cmder is a declarative CLI builder for MoonBit. Built on moonbitlang/core/argparse, it organizes command-line applications around command definitions, options, and callbacks.

    This project is a fork of mizchi/admiral, modified and maintained on top of its implementation. Thanks to mizchi and the upstream contributors for the original design and implementation. The upstream project was inspired by gunshi.

    • String, boolean, and integer options, plus positional arguments.
    • Nested subcommands and command callbacks with access to ancestor option values.
    • Help text and root command version information generated by argparse.
    • JSON export of CLI definitions for tools and AI agents.
    • Completion script generation for Bash, Zsh, and Fish.

    #Installation

    Run this from the root of an existing MoonBit module:

    moon add hustcer/cmder

    Then add the import to the consuming package's moon.pkg:

    import { "hustcer/cmder", }

    Use the default alias @cmder in your code. For an executable package, also declare the following in moon.pkg:

    pkgtype(kind: "executable")

    #Quick Start

    Place the following code in your executable package's main.mbt:

    ///|
    fn main {
    let app = @cmder.cli(
    name="hello",
    version="1.0.0",
    description="A small greeting CLI",
    commands=[
    @cmder.command(
    name="greet",
    description="Greet someone",
    options=[
    @cmder.string("name", short='n', required=true),
    @cmder.bool("loud", short='l'),
    @cmder.int("count", short='c', default=Some(1)),
    ],
    examples=["hello greet -n Alice", "hello greet -n Bob -l -c 2"],
    run=Some(fn(ctx) {
    let name = ctx.get_string_required("name") catch {
    err => { println(err); return }
    }
    let count = ctx.get_int_required("count") catch {
    err => { println(err); return }
    }
    for _ in 0..<count {
    let message = "Hello, \{name}!"
    println(if ctx.get_bool("loud") { message.to_upper() } else { message })
    }
    }),
    ),
    ],
    )
    app.run() catch { err => println(err) }
    }

    After compiling the executable as hello:

    $ hello greet -n Alice Hello, Alice! $ hello greet -n Bob -l -c 2 HELLO, BOB! HELLO, BOB!

    Use hello --help to list commands, hello greet --help to view command arguments, and hello --version to display the version.

    This example prints errors to standard output. Applications can choose their own error reporting and exit codes; printing an error and returning does not imply a nonzero exit status.

    #Options and Positional Arguments

    The following options can be used in a command definition:

    let options = [
    @cmder.string("config", short='f', description="Config file", required=true),
    @cmder.string("host", default=Some("localhost")),
    @cmder.int("port", short='p', default=Some(3000)),
    @cmder.bool("verbose", short='v', description="Verbose output"),
    ]

    DefinitionUsageDefault behavior
    string--host localhostNone when omitted; supports a default value
    int--port 3000Converted to Int32 when read; supports a default value
    bool--verbose or -vfalse when omitted
    positionalcopy source.txt target.txtRead in declaration order

    short is optional. string and int support required=true. When a default value is configured, callers can omit the option even if required=true is also set.

    Integer options are still accepted as strings during argument parsing. get_int returns None for missing values, invalid formats, or values outside the Int32 range. To reject invalid input, use get_int_required and handle the error. Applications must enforce their own constraints, such as positive values or allowed ranges.

    Negative integer values work in both separated (--delta -1, -d -1) and attached (--delta=-1) forms.

    Declare positional arguments in positionals, placing required arguments before optional ones. Each positional argument except the last accepts at most one value; the last accepts all remaining values:

    let show = @cmder.command(
    name="show",
    positionals=[
    @cmder.positional("files", description="Input files", required=true),
    ],
    run=Some(fn(ctx) {
    for file in ctx.get_strings("files") {
    println(file)
    }
    }),
    )

    show a.txt b.txt places both filenames in files.

    #Subcommands and Option Scope

    cli(commands=...) declares top-level commands, while command(subcommands=...) declares the next level:

    let app = @cmder.cli(
    name="myapp",
    options=[@cmder.bool("verbose", short='v')],
    commands=[
    @cmder.command(name="db", subcommands=[
    @cmder.command(
    name="migrate",
    options=[@cmder.bool("dry-run")],
    run=Some(fn(ctx) {
    if ctx.get_bool("verbose") {
    println("Starting migration")
    }
    println(if ctx.get_bool("dry-run") { "Preview" } else { "Apply" })
    }),
    ),
    ]),
    ],
    )

    Invoke this as myapp -v db migrate --dry-run: options belong at the command level where they are declared. Callbacks can read values from ancestor levels. Descendant values with the same name take precedence, including descendant defaults.

    When a deeper subcommand is selected, only its callback runs; ancestor callbacks do not run in sequence. run raises an error if no command is specified, or if the selected command has neither a callback nor a selected subcommand. The root cli does not accept a run callback parameter.

    #Reading Arguments and Handling Errors

    Callbacks have the signature (Context) -> Unit. Errors from methods called inside a callback must be handled locally.

    Context methodReturn typeBehavior
    get_bool(name)BoolReturns false when absent
    get_string(name)String?Returns the first value, or None when absent
    get_string_required(name)String raiseRaises an error when absent
    get_int(name)Int32?Returns None when absent or invalid
    get_int_checked(name)Int32? raise CliErrorReturns None only when absent; malformed input and overflow raise distinct errors
    get_int_required(name)Int32 raiseRaises an error when absent or invalid
    get_strings(name)Array[String]Returns all values, or an empty array when absent
    get_subcommand()(String, Context)?Returns the selected next-level subcommand and its context

    Use get_int_checked when a default should apply only to missing input. It accepts signed decimal Int32 values, including leading zeroes, and raises CliError::InvalidInteger(name, value) or IntegerOutOfRange(name, value) for invalid input. The existing get_int retains its lenient behavior and legacy digit-length limit. Product-specific ranges remain the application's responsibility.

    Required getters and command execution errors now use CliError, whose message() and to_string() return display-ready text without internal source locations. ParseError(message) preserves argparse's original diagnostic and contextual help; its text is not a machine-readable error category. Callback signatures remain unchanged.

    #Parsing Without Execution

    app.parse(argv=...) requires explicit arguments without the executable name. It does not read process arguments or environment variables, print, exit, or invoke callbacks:

    let app = @cmder.cli(name="app", commands=[
    @cmder.command(name="go", options=[@cmder.int("count", default=Some(1))]),
    ])
    match app.parse(argv=["go", "--count", "3"]) {
    Parsed(call) => {
    // call.command_path is ["go"]. The host chooses how to execute it.
    let count = call.context.get_int_checked("count") catch {
    err => { println(err.message()); return }
    }
    println(count.unwrap_or(1))
    }
    Help(text) | Version(text) => println(text)
    Failed(error) => println(error.message())
    }

    Parsed also supports root arguments (command_path is empty) and commands without callbacks. The selected command's context includes ancestor values, with descendant values and defaults taking precedence; context.subcommand is None. Integer conversion remains lazy, matching run; use checked getters when consuming numbers.

    call.source_of(name) returns Argv, Env, Default, or None for an absent value. call.was_provided(name) is true only for an effective argv value, including an empty string or a value equal to the default. A descendant default shadows an ancestor argv value in both the context and source information. Source information is a parse snapshot and does not change if the caller edits the returned context. Current argument definitions do not configure environment bindings, so they produce Argv and Default; Env preserves the underlying source model without implicit environment access.

    run() remains the convenience API: it optionally reads process arguments, executes callbacks, and prints and exits successfully for help/version. Use parse when the host must retain control over output, execution, and exit status. Existing public record fields and run/get_int signatures remain unchanged.

    For help text alone, use app.render_help() or app.render_help(command_path=["db", "migrate"]). This performs no argument parsing or callback execution, includes explicit command examples, and raises CliError::UnknownCommand(path) for an unknown path.

    #Explicit Arguments and Testing

    app.run() uses process arguments. Pass argv=Some(...) to test command behavior directly, without including the executable name in the array:

    ///|
    test "dispatch greet" {
    let received = Ref("")
    let app = @cmder.cli(name="hello", commands=[
    @cmder.command(
    name="greet",
    options=[@cmder.string("name", required=true)],
    run=Some(fn(ctx) {
    received.val = ctx.get_string("name").unwrap_or("")
    }),
    ),
    ])
    app.run(argv=Some(["greet", "--name", "Alice"]))
    assert_eq(received.val, "Alice")
    }

    #Exporting CLI Definitions

    After constructing app, call:

    let schema_text = app.render_schema() // String
    let schema_json = app.render_schema_json() // Json

    The export describes the command hierarchy, option types, required status, default values, positional arguments, and examples. It is suitable for documentation generation and tooling. Here, schema refers to this library's CLI description format, not standard JSON Schema. Option defaults are represented as strings, including integer defaults.

    positionals remains an object keyed by argument name. Each entry includes a zero-based index, min_args (0 or 1), and max_args (1, or null for the final unbounded argument). Consumers should sort by index, rather than relying on JSON object key order.

    The library does not register --schema automatically. The repository's example program checks whether the last argument is --schema before calling run, then outputs the definition.

    #Shell Completion

    After constructing app, these methods return complete completion scripts:

    let bash_script = app.render_bash_completion()
    let zsh_script = app.render_zsh_completion()
    let fish_script = app.render_fish_completion()

    Applications must provide their own script export entry point, or write these strings to files during the build process. The library does not add a completion subcommand automatically. Construct the complete app before handling export requests to avoid referencing app before it is defined inside a callback used to initialize it.

    For a program named myapp, save the generated scripts separately, then load them in the corresponding shell:

    Bash scripts use built-in completion variables and do not require bash-completion. Completion follows the declared command path and option scope; after --, command and option suggestions stop. Built-in help flags, root version flags, and help command topics are included. Application-defined long and short spellings shadow the corresponding builtins independently, matching argparse. Custom value and positional filename suggestions are not generated by this library.

    # Bash source ./myapp.bash

    # Zsh: initialize the completion system first autoload -Uz compinit compinit source ./_myapp

    # Fish source ./myapp.fish

    #API and Source Code

    Entry pointPurpose
    cli(name=..., version=..., description=..., options=..., commands=...)Build an application
    command(name=..., description=..., options=..., positionals=..., examples=..., subcommands=..., run=...)Define a command
    string, int, bool, positionalDefine arguments
    CliApp::run(argv=...)Parse arguments and execute the callback
    CliApp::parse(argv=...)Return Parsed, Help, Version, or Failed without I/O or execution
    CliApp::render_help(command_path=...)Render root or nested help, including explicit examples
    Invocation::source_of / was_providedQuery effective argument provenance
    CliApp::render_schema / render_schema_jsonExport CLI definitions
    CliApp::render_bash_completion / render_zsh_completion / render_fish_completionGenerate completion scripts
    build_command(command)Convert to an underlying argparse.Command for direct use with argparse

    See the public API for complete signatures and src/examples/cli for a runnable example.

    #Local Development

    Run from the repository root:

    moon check moon test moon run src/examples/cli --target native -- greet -n Alice moon run src/examples/cli --target native -- db migrate up --dry-run moon run src/examples/cli --target native -- --schema

    To validate individual targets, use moon test --target native, moon test --target js, and moon test --target wasm-gc. Running the JS target requires a suitable JavaScript runtime.

    Run nu scripts/check-completions.nu for shell integration regressions (Nushell 0.116+, Bash, Fish, and Zsh required). These execute generated scripts in clean shells; Zsh completion widget calls are captured outside an interactive ZLE session. CI runs this suite on the native target.

    Run nu scripts/check-cli.nu to verify process argv, run output/exit behavior, and parse returning control to its host on JS, native, and wasm-gc.

    #Acknowledgments and License

    Thanks to the author and contributors of mizchi/admiral. This package is a fork of that repository, with further modifications built on its implementation. Thanks also to gunshi for the design inspiration, and to MoonBit's core/argparse for argument parsing.

    License: MIT, as declared in moon.mod.

    CliError

    pub(all) suberror CliError {
    ParseError(String)
    MissingCommand
    UnknownCommand(Array[String])
    MissingSubcommand(String, Array[String])
    MissingHandler(String)
    MissingOption(String)
    InvalidInteger(String, String)
    IntegerOutOfRange(String, String)
    } derive(
    Debug
    )

    Errors produced by cmder. Parser diagnostics remain display-ready text; cmder does not infer error categories by parsing argparse's messages.
    impl Show for CliError

    CliError::message

    fn CliError::message(self : CliError) -> String

    Returns a display-ready message without source locations or a Failure prefix.

    test {
    let error = @cmder.CliError::InvalidInteger("count", "abc")
    inspect(error.message(), content="invalid integer for 'count': 'abc'")
    }

    CliError::output

    fn CliError::output(self : CliError, logger : &Logger) -> Unit

    CliError::to_repr

    CliError::to_string

    fn CliError::to_string(self : CliError) -> String

    CliApp

    pub(all) struct CliApp {
    name : String
    version : String
    description : String
    root_options : Array[OptionDef]
    commands : Array[CommandDef]
    }

    CliApp::parse

    fn CliApp::parse(self : CliApp, argv~ : ArrayView[String]) -> ParseOutcome

    Parses explicit argv, excluding the executable name, without printing, exiting, reading process state, or invoking callbacks. Integer conversion remains lazy; use get_int_checked to distinguish invalid values from absence.

    test {
    let app = @cmder.cli(name="app", version="1.2.3")
    guard app.parse(argv=["--version"]) is Version(version) else {
    fail("expected version")
    }
    inspect(version, content="1.2.3")
    }

    CliApp::render_bash_completion

    fn CliApp::render_bash_completion(self : CliApp) -> String

    Generates a Bash completion script for this application.

    test {
    assert_true(
    @cmder.cli(name="demo").render_bash_completion().contains("complete -F"),
    )
    }

    CliApp::render_fish_completion

    fn CliApp::render_fish_completion(self : CliApp) -> String

    Generates a Fish completion script for this application.

    test {
    assert_true(
    @cmder.cli(name="demo")
    .render_fish_completion()
    .contains("Fish completions"),
    )
    }

    CliApp::render_help

    fn CliApp::render_help(self : CliApp, command_path? : ArrayView[String]) -> String raise CliError

    Renders root or nested command help without parsing argv or running callbacks. The path excludes the executable name. Unknown paths raise UnknownCommand; descriptions, options, positionals, and explicit examples come from the same command definition used by run and parse. Like argparse's render_help, this renders definitions without validating whether they are executable.

    test {
    let app = @cmder.cli(name="app", commands=[@cmder.command(name="go")])
    assert_true(app.render_help(command_path=["go"]).contains("Usage: app go"))
    }

    CliApp::render_schema

    fn CliApp::render_schema(self : CliApp) -> String

    Returns the application schema as a JSON string.

    test {
    assert_true(@cmder.cli(name="demo").render_schema().contains("demo"))
    }

    CliApp::render_schema_json

    fn CliApp::render_schema_json(self : CliApp) ->
    Json

    Returns a structured JSON description of the application.

    test {
    let schema = @cmder.cli(name="demo").render_schema_json()
    assert_true(schema.stringify().contains("demo"))
    }

    CliApp::render_zsh_completion

    fn CliApp::render_zsh_completion(self : CliApp) -> String

    Generates a Zsh completion script for this application.

    test {
    assert_true(
    @cmder.cli(name="demo").render_zsh_completion().contains("#compdef demo"),
    )
    }

    CliApp::run

    fn CliApp::run(self : CliApp, argv? : Array[String]?) -> Unit raise

    Parses arguments and executes the selected command's callback. Omit argv to read process arguments. Help and version print and exit with status 0, preserving the convenience API. Use parse for side-effect-free handling. Callback signatures and closest-value precedence are unchanged. Parse failures raise CliError::ParseError with the original diagnostic; missing command, subcommand, or callback errors have distinct CliError cases.

    test {
    let called = Ref(false)
    let app = @cmder.cli(name="demo", commands=[
    @cmder.command(name="go", run=Some(fn(_) { called.val = true })),
    ])
    app.run(argv=Some(["go"]))
    assert_true(called.val)
    }

    CommandDef

    pub(all) struct CommandDef {
    name : String
    description : String
    options : Array[OptionDef]
    positionals : Array[PositionalDef]
    examples : Array[String]
    subcommands : Array[CommandDef]
    run : (Context) -> Unit?
    }

    Context

    pub(all) struct Context {
    flags : Map[String, Bool]
    values : Map[String, Array[String]]
    subcommand : (String, Context)?
    }

    Context::get_bool

    fn Context::get_bool(self : Context, name : String) -> Bool

    Returns a flag's value, or false when it was not provided.

    test {
    let ctx : @cmder.Context = {
    flags: { "verbose": true },
    values: {},
    subcommand: None,
    }
    assert_true(ctx.get_bool("verbose"))
    }

    Context::get_int

    fn Context::get_int(self : Context, name : String) -> Int?

    Parses the first value as an Int32, returning None if missing or invalid.

    test {
    let ctx : @cmder.Context = {
    flags: {},
    values: { "count": ["3"] },
    subcommand: None,
    }
    assert_true(ctx.get_int("count") == Some(3))
    }

    Context::get_int_checked

    fn Context::get_int_checked(self : Context, name : String) -> Int? raise CliError

    Reads an optional signed decimal Int32. Missing values return None; empty, nondecimal, and sign-only values raise InvalidInteger; overflow raises IntegerOutOfRange. A leading minus is accepted, matching get_int's grammar. Leading zeroes do not cause overflow. No product-specific range is checked.

    test {
    let ctx : @cmder.Context = {
    flags: {},
    values: { "count": ["-2"] },
    subcommand: None,
    }
    assert_true(ctx.get_int_checked("count") == Some(-2))
    assert_true(ctx.get_int_checked("missing") is None)
    }

    Context::get_int_required

    fn Context::get_int_required(self : Context, name : String) -> Int raise

    Parses a required integer, raising MissingOption when absent and a checked integer error when malformed or outside Int32. No application range is imposed.

    test {
    let ctx : @cmder.Context = {
    flags: {},
    values: { "count": ["3"] },
    subcommand: None,
    }
    inspect(ctx.get_int_required("count"), content="3")
    }

    Context::get_string

    fn Context::get_string(self : Context, name : String) -> String?

    Returns the first value, or None if the name is absent.

    test {
    let ctx : @cmder.Context = {
    flags: {},
    values: { "name": ["Ada"] },
    subcommand: None,
    }
    assert_true(ctx.get_string("name") == Some("Ada"))
    }

    Context::get_string_required

    fn Context::get_string_required(self : Context, name : String) -> String raise

    Returns the first value, raising CliError::MissingOption if it is absent.

    test {
    let ctx : @cmder.Context = {
    flags: {},
    values: { "name": ["Ada"] },
    subcommand: None,
    }
    inspect(ctx.get_string_required("name"), content="Ada")
    }

    Context::get_strings

    fn Context::get_strings(self : Context, name : String) -> Array[String]

    Returns all values associated with a name, or an empty array.

    test {
    let ctx : @cmder.Context = {
    flags: {},
    values: { "files": ["a", "b"] },
    subcommand: None,
    }
    inspect(ctx.get_strings("files").length(), content="2")
    }

    Context::get_subcommand

    fn Context::get_subcommand(self : Context) -> (String, Context)?

    Returns the selected nested command and its context, if present.

    test {
    let ctx : @cmder.Context = { flags: {}, values: {}, subcommand: None, }
    assert_true(ctx.get_subcommand() is None)
    }

    Invocation

    pub struct Invocation {
    command_path : Array[String]
    context : Context
    // private fields
    }

    A parsed command without callback execution. The path excludes the application name; an empty path selects the root. Context contains the selected command's effective values, including ancestors, with the existing closest-value rules. Its subcommand is None. Sources describe this parse snapshot; editing Context afterwards does not change the recorded provenance.

    Invocation::source_of

    fn Invocation::source_of(self : Invocation, name : String) -> ValueSource?

    Returns the source of an effective value, or None when absent. A descendant default shadows an ancestor argv value, just as it does in the callback API.

    test {
    let app = @cmder.cli(name="app", options=[
    @cmder.int("count", default=Some(1)),
    ])
    guard app.parse(argv=[]) is Parsed(call) else { fail("expected arguments") }
    assert_true(call.source_of("count") == Some(@cmder.ValueSource::Default))
    }

    Invocation::was_provided

    fn Invocation::was_provided(self : Invocation, name : String) -> Bool

    True only when the effective value came from argv, including explicit empty strings. Defaults, environment values, and absent flags are not explicit.

    test {
    let app = @cmder.cli(name="app", options=[@cmder.string("name")])
    guard app.parse(argv=["--name="]) is Parsed(call) else {
    fail("expected arguments")
    }
    assert_true(call.was_provided("name"))
    }

    OptionDef

    pub(all) struct OptionDef {
    name : String
    type_ : OptionType
    short : Char
    description : String
    required : Bool
    default_value : String?
    } derive(
    Debug
    )

    OptionType

    pub(all) enum OptionType {
    StringOpt
    BoolOpt
    IntOpt
    } derive(Eq,
    Debug
    )

    impl Show for OptionType

    OptionType::equal

    fn OptionType::equal(OptionType, OptionType) -> Bool

    OptionType::not_equal

    fn OptionType::not_equal(x : OptionType, y : OptionType) -> Bool

    OptionType::output

    fn OptionType::output(self : OptionType, logger : &Logger) -> Unit

    OptionType::to_string

    fn OptionType::to_string(self : OptionType) -> String

    ParseOutcome

    pub(all) enum ParseOutcome {
    Parsed(Invocation)
    Help(String)
    Version(String)
    Failed(CliError)
    }

    The complete result of explicit argument parsing, without I/O or process exit. Parsed does not require a callback; the host decides how to execute it.

    PositionalDef

    pub(all) struct PositionalDef {
    name : String
    description : String
    required : Bool
    }

    ValueSource

    pub(all) enum ValueSource {
    Argv
    Env
    Default
    } derive(Eq,
    Debug
    )

    Origin of the effective argument value, matching argparse's source model. Current definitions use Argv and Default; no process environment is read.

    ValueSource::equal

    fn ValueSource::equal(ValueSource, ValueSource) -> Bool

    ValueSource::not_equal

    fn ValueSource::not_equal(x : ValueSource, y : ValueSource) -> Bool

    bool

    fn bool(name : String, short? : Char, description? : String) -> OptionDef

    Defines a Boolean flag, which defaults to false.

    test {
    let option = @cmder.bool("verbose", short='v')
    inspect(option.name, content="verbose")
    }

    build_command

    Converts a command definition into an argparse.Command. Explicit examples are included in its help description; callback execution is not attached.

    test {
    let command = @cmder.command(name="greet")
    let parser = @cmder.build_command(command)
    assert_true(parser.render_help().contains("greet"))
    }

    cli

    fn cli(name~ : String, version? : String, description? : String, options? : Array[OptionDef], commands? : Array[CommandDef]) -> CliApp

    Creates an application. Ancestor values are available to callbacks; values at a descendant level, including defaults, take precedence by name.

    test {
    let app = @cmder.cli(name="demo", commands=[@cmder.command(name="hello")])
    inspect(app.name, content="demo")
    }

    command

    fn command(name~ : String, description? : String, options? : Array[OptionDef], positionals? : Array[PositionalDef], examples? : Array[String], subcommands? : Array[CommandDef], run? : (Context) -> Unit?) -> CommandDef

    Defines a command with options, positionals, subcommands, and a callback.

    test {
    let greet = @cmder.command(name="greet", options=[@cmder.string("name")])
    inspect(greet.name, content="greet")
    }

    int

    fn int(name : String, short? : Char, description? : String, required? : Bool, default? : Int?) -> OptionDef

    Defines an integer-valued option.

    test {
    let option = @cmder.int("count", default=Some(3))
    inspect(option.required, content="false")
    }

    positional

    fn positional(name : String, description? : String, required? : Bool) -> PositionalDef

    Defines a positional argument. The final positional accepts multiple values; earlier positionals accept at most one. Declare required arguments first.

    test {
    let file = @cmder.positional("file", required=true)
    assert_true(file.required)
    }

    string

    fn string(name : String, short? : Char, description? : String, required? : Bool, default? : String?) -> OptionDef

    Defines a string-valued option.

    test {
    let option = @cmder.string("name", short='n', required=true)
    assert_true(option.required)
    }