cmder

    Declarative CLI builder for MoonBit, inspired by gunshi

    cli
    argparse
    moonbit
    Download zip
    Author
    Version
    0.2.0
    License
    MIT
    Last updated
    7 days ago
    Downloads
    1K

    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_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

    #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. 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::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.

    #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.

    CliApp

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

    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_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.

    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_required

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

    Parses a required integer, raising an error if missing or invalid.

    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 an error 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)
    }

    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

    PositionalDef

    pub(all) struct PositionalDef {
    name : String
    description : String
    required : 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.

    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)
    }