# cmder

[English](README.md) | [简体中文](README.zh.md)

`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](https://github.com/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](https://github.com/kazupon/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:

```sh
moon add hustcer/cmder
```

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

```text
import {
  "hustcer/cmder",
}
```

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

```text
pkgtype(kind: "executable")
```

## Quick Start

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

```moonbit
///|
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`:

```text
$ 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:

```moonbit
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"),
]
```

| Definition   | Usage                        | Default behavior                                         |
| ------------ | ---------------------------- | -------------------------------------------------------- |
| `string`     | `--host localhost`           | `None` when omitted; supports a default value            |
| `int`        | `--port 3000`                | Converted to `Int32` when read; supports a default value |
| `bool`       | `--verbose` or `-v`          | `false` when omitted                                     |
| `positional` | `copy source.txt target.txt` | Read 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:

```moonbit
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:

```moonbit
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 method              | Return type             | Behavior                                                                            |
| --------------------------- | ----------------------- | ----------------------------------------------------------------------------------- |
| `get_bool(name)`            | `Bool`                  | Returns `false` when absent                                                         |
| `get_string(name)`          | `String?`               | Returns the first value, or `None` when absent                                      |
| `get_string_required(name)` | `String raise`          | Raises an error when absent                                                         |
| `get_int(name)`             | `Int32?`                | Returns `None` when absent or invalid                                               |
| `get_int_checked(name)`     | `Int32? raise CliError` | Returns `None` only when absent; malformed input and overflow raise distinct errors |
| `get_int_required(name)`    | `Int32 raise`           | Raises 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:

```moonbit
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:

```moonbit
///|
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:

```moonbit
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](src/examples/cli/main.mbt) 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:

```moonbit
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
# Bash
source ./myapp.bash
```

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

```fish
# Fish
source ./myapp.fish
```

## API and Source Code

| Entry point                                                                                                | Purpose                                                                  |
| ---------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------ |
| `cli(name=..., version=..., description=..., options=..., commands=...)`                                   | Build an application                                                     |
| `command(name=..., description=..., options=..., positionals=..., examples=..., subcommands=..., run=...)` | Define a command                                                         |
| `string`, `int`, `bool`, `positional`                                                                      | Define 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_provided`                                                                   | Query effective argument provenance                                      |
| `CliApp::render_schema` / `render_schema_json`                                                             | Export CLI definitions                                                   |
| `CliApp::render_bash_completion` / `render_zsh_completion` / `render_fish_completion`                      | Generate completion scripts                                              |
| `build_command(command)`                                                                                   | Convert to an underlying `argparse.Command` for direct use with argparse |

See the [public API](src/pkg.generated.mbti) for complete signatures and [src/examples/cli](src/examples/cli/main.mbt) for a runnable example.

## Local Development

Run from the repository root:

```sh
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](https://github.com/mizchi/admiral). This package is a fork of that repository, with further modifications built on its implementation. Thanks also to [gunshi](https://github.com/kazupon/gunshi) for the design inspiration, and to MoonBit's `core/argparse` for argument parsing.

License: MIT, as declared in [moon.mod](moon.mod).
