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

Subcommands

Subcommands (app <subcommand> [args]) let you group related functionality under a single binary — similar to git commit, docker run, or cargo build. In ArgMojo, a subcommand is simply another Command instance registered on the parent.

Defining Subcommands

Register subcommands with add_subcommand(). Each subcommand has its own set of arguments, help text, and validation rules.

var app = Command("app", "My CLI tool", version="1.0.0")
app.add_argument(Argument("verbose", help="Verbose output").long["verbose"]().short["v"]().flag())

var search = Command("search", "Search for patterns")
search.add_argument(Argument("pattern", help="Search pattern").positional().required())
search.add_argument(Argument("max-depth", help="Max depth").long["max-depth"]().short["d"]().value_name["N"]())

var init = Command("init", "Initialise a new project")
init.add_argument(Argument("name", help="Project name").positional().required())

app.add_subcommand(search^)
app.add_subcommand(init^)

var result = app.parse()
app search "fn main" --max-depth 3
app init my-project

Root-level flags before the subcommand token are parsed as part of the root command:

app --verbose search "fn main"
# verbose = True (root flag), subcommand = "search"

Help output — when subcommands are registered, the root help automatically includes a Commands section and the usage line shows <COMMAND>:

My CLI tool

usage: app <COMMAND> [OPTIONS]

options:
  -v, --verbose    Verbose output
  -h, --help       Show this help message
  -V, --version    Show version

commands:
  search    Search for patterns
  init      Initialise a new project

Child help shows the full command path in the usage line:

app search --help
Search for patterns

usage: app search <pattern> [OPTIONS]

arguments:
  pattern    Search pattern

options:
  -d, --max-depth N    Max depth
  -h, --help           Show this help message
  -V, --version        Show version

The -- stop marker prevents subcommand dispatch. After --, all tokens become positional arguments for the root command:

app -- search
# "search" is a root positional, NOT a subcommand dispatch

Parsing Subcommand Results

After parsing, check result.subcommand to see which subcommand was selected, and use result.get_subcommand_result() to access the child’s parsed values.

var result = app.parse()

if result.subcommand == "search":
    var sub = result.get_subcommand_result()
    var pattern = sub.get_string("pattern")
    var depth = sub.get_int("max-depth") if sub.has("max-depth") else 10
    print("Searching for:", pattern)

elif result.subcommand == "init":
    var sub = result.get_subcommand_result()
    var name = sub.get_string("name")
    print("Initialising project:", name)
Method / FieldReturnsDescription
result.subcommandStringName of selected subcommand (empty if none).
result.has_subcommand_result()BoolTrue if a subcommand was dispatched.
result.get_subcommand_result()ParseResultThe child command’s parsed result.

All standard ParseResult methods (get_flag(), get_string(), get_int(), get_list(), get_map(), get_count(), has()) work on the subcommand result.

Auto-Dispatch with set_run_function / execute

The problem: manual subcommand routing

When a CLI has subcommands (like git clone, git push, git remote add), the ParseResult tells you which subcommand was selected — but you must route to the right handler yourself:

var result = app.parse()

if result.subcommand == "clone":
    handle_clone(result.get_subcommand_result())
elif result.subcommand == "push":
    handle_push(result.get_subcommand_result())
elif result.subcommand == "remote":
    var sub = result.get_subcommand_result()
    if sub.subcommand == "add":
        handle_remote_add(sub.get_subcommand_result())
    elif sub.subcommand == "remove":
        handle_remote_remove(sub.get_subcommand_result())

This is tedious. Every time you add a subcommand, you update the router. With nested subcommands the if/elif tree gets deeper. A typo in "clone" vs "cloen" silently breaks routing.

The solution: auto-dispatch

With auto-dispatch, you register a handler on the command itself. ArgMojo then parses the arguments and routes to the correct handler in one call:

clone.set_run_function(handle_clone)
push.set_run_function(handle_push)
remote_add.set_run_function(handle_remote_add)
app.execute()   # parse sys.argv() → walk the subcommand tree → call the right handler

No if/elif boilerplate. This is the pattern Cobra (Go’s most popular CLI framework) pioneered: every command carries its own handler, and Execute() walks the tree automatically.


Step 1 — Define handler functions

Each handler is a free function with signature def (ParseResult) raises. It receives the parsed arguments for the command it is attached to. It is a procedure — it does work but returns nothing.

from argmojo import Command, Argument, ParseResult

def handle_search(result: ParseResult) raises:
    print("Searching for: " + result.get_string("pattern"))

def handle_init(result: ParseResult) raises:
    print("Initialising project: " + result.get_string("name"))

Why free functions? Mojo does not yet support storing closures (functions that capture variables from their enclosing scope) as struct fields. Handlers must be module-level def functions. If you need to pass state to a handler, encode it in the parsed arguments or use module-level constants.

Step 2 — Register handlers with set_run_function()

def main() raises:
    var app = Command("app", "My CLI tool", version="1.0.0")

    var search = Command("search", "Search for patterns")
    search.add_argument(Argument("pattern", help="Search pattern").positional().required())
    search.set_run_function(handle_search)     # ← "when 'search' is selected, call handle_search"
    app.add_subcommand(search^)

    var init = Command("init", "Initialise a new project")
    init.add_argument(Argument("name", help="Project name").positional().required())
    init.set_run_function(handle_init)         # ← "when 'init' is selected, call handle_init"
    app.add_subcommand(init^)

    app.execute()  # Parse sys.argv() → find matching subcommand → call its handler

Running myapp search hello calls handle_search with pattern="hello". Running myapp init myproject calls handle_init with name="myproject".


Method reference

MethodDescription
cmd.set_run_function(handler)Registers a def (ParseResult) raises handler on cmd.
cmd.execute()Parses sys.argv(), walks the subcommand chain, and calls the matching handler.
cmd._execute_with_arguments(args)Testing helper. Like execute() but takes an explicit List[String] and raises on parse errors (instead of exiting).

set_run_function(handler) — Stores the handler function pointer on the command. You can call it again to replace a previous handler. Think of it as labelling a mailbox: “when mail arrives here, this person handles it.”

execute() — The main entry point for production code. It does three things in one call:

  1. Reads the command line from sys.argv().
  2. Parses it (calling self.parse() internally).
  3. Walks the subcommand chain and invokes the matching handler.

If no handler is registered on the resolved command, an Error is raised.

_execute_with_arguments(args) — A testing helper (prefixed with _ to indicate internal use). Like execute(), but accepts an explicit List[String] instead of reading sys.argv(). Unlike execute(), parse errors raise instead of calling exit(2), making it suitable for tests that need to catch and inspect errors. Production code should always call execute().


How dispatch walks the tree

Given app remote add origin, the internal dispatch chain is:

app._dispatch({subcommand: "remote", ...})
  → find child "remote"
  → remote._dispatch({subcommand: "add", ...})
    → find child "add"
    → add._dispatch({subcommand: "", name: "origin"})
      → no subcommand → call add's handler → handle_remote_add({name: "origin"})

At each level:

  • Has subcommand? Find the matching child command and recurse.
  • No subcommand? This is the leaf — call its registered handler.
  • Grouping command (has subcommands, no handler)? Show help instead of raising — matching Cobra’s behaviour.
  • No handler, no subcommands? Raise Error("No run function registered for command '…'").

Nested subcommands

The dispatch recursion handles arbitrary nesting depth:

def handle_remote_add(result: ParseResult) raises:
    print("Adding remote: " + result.get_string("name"))

def main() raises:
    var app = Command("app", "My CLI")

    var remote = Command("remote", "Manage remotes")
    # Note: 'remote' itself has no set_run_function — it is just a grouping command.
    # Only its children have handlers.

    var remote_add = Command("add", "Add a remote")
    remote_add.add_argument(Argument("name", help="Remote name").positional().required())
    remote_add.set_run_function(handle_remote_add)
    remote.add_subcommand(remote_add^)

    app.add_subcommand(remote^)

    app.execute()  # "app remote add origin" → handle_remote_add()

The remote command does not need a handler — it exists only to group add, remove, and other child commands. If a user types just app remote with no child subcommand, the help for remote is shown automatically (matching Cobra’s behaviour for grouping commands).


Testing with _execute_with_arguments()

In tests, pass explicit argument lists instead of relying on sys.argv():

# Test that "app search hello" calls the search handler correctly
var args: List[String] = ["app", "search", "hello"]
app._execute_with_arguments(args)  # Calls handle_search with pattern="hello"

When to use auto-dispatch vs manual parsing

ScenarioRecommended approach
CLI with 2+ subcommandsAuto-dispatch (set_run_function + execute)
Simple CLI, no subcommandsEither works; parse() is fine too
Need ParseResult for custom logicManual parse() + your own routing
Integration testing_execute_with_arguments(args)

Persistent (Global) Flags

A persistent flag is declared on the parent command but is automatically available in every subcommand. The user can place it either before or after the subcommand token — both work identically.

This is inspired by Go cobra’s PersistentFlags() and is useful for cross-cutting concerns like verbosity, output format, or colour control.


Defining persistent flags

var app = Command("app", "My app")

# These are available everywhere
app.add_argument(
    Argument("verbose", help="Verbose output")
    .long["verbose"]().short["v"]().flag().persistent()
)
app.add_argument(
    Argument("output", help="Output format")
    .long["output"]().short["o"]()
    .choice["json"]().choice["text"]().choice["yaml"]()
    .default["text"]()
    .persistent()
)

var search = Command("search", "Search for patterns")
search.add_argument(Argument("pattern", help="Pattern").positional().required())
app.add_subcommand(search^)

Both positions work

app --verbose search "fn main"     # flag BEFORE subcommand
app search --verbose "fn main"     # flag AFTER subcommand  (same result)
app -v search -o json "fn main"    # short forms work too

Bidirectional sync — persistent flag values are synchronised between root and child results, regardless of where the user places them:

var result = app.parse()
var sub = result.get_subcommand_result()

# Both see the same value, no matter where the flag was placed
print(result.get_flag("verbose"))   # True
print(sub.get_flag("verbose"))      # True

Help output — persistent flags appear under a separate Global Options heading in both root and child help:

# Root help (app --help)
options:
  -h, --help       Show this help message
  -V, --version    Show version

global options:
  -v, --verbose               Verbose output
  -o, --output {json,text,yaml}    Output format

# Child help (app search --help)
options:
  -h, --help    Show this help message
  -V, --version Show version

global options:
  -v, --verbose               Verbose output
  -o, --output {json,text,yaml}    Output format

Conflict detection — if a persistent flag on the parent has the same long or short name as a local flag on a child, add_subcommand() raises an error at registration time:

var app = Command("app", "My app")
app.add_argument(Argument("verbose", help="Verbose").long["verbose"]().short["v"]().flag().persistent())

var sub = Command("sub", "A child")
sub.add_argument(Argument("verbose", help="Also verbose").long["verbose"]().flag())  # conflict!

app.add_subcommand(sub^)  # raises: Persistent flag '--verbose' on 'app'
                           #         conflicts with '--verbose' on subcommand 'sub'

Non-persistent root flags with the same name as child flags do not conflict — they are independent and scoped to their own command.


All argument types can be made persistent — flags, count flags, value options, choices, etc.:

app.add_argument(
    Argument("log-level", help="Log level")
    .long["log-level"]().choice["debug"]().choice["info"]().choice["warn"]().choice["error"]()
    .default["info"]().persistent()
)

The help Subcommand

When you call add_subcommand() for the first time, ArgMojo automatically registers a help subcommand. This mirrors the behaviour of git help, cargo help, and kubectl help.

app help search    # equivalent to: app search --help
app help init      # equivalent to: app init --help
app help           # shows root help (same as: app --help)

The auto-registered help subcommand is excluded from the Commands section in help output to avoid clutter.


Disabling the help subcommand

If you don’t want the auto-registered help subcommand (e.g., you want to use help as a real subcommand name), call disable_help_subcommand():

app.disable_help_subcommand()

This can be called before or after add_subcommand(). If called after, the auto-added help entry is removed.

Subcommand Aliases

You can register short aliases for subcommands with command_aliases(). When the user types an alias, ArgMojo dispatches to the canonical subcommand and stores the canonical name (not the alias) in result.subcommand.

var clone = Command("clone", "Clone a repository")
var aliases: List[String] = ["cl"]
clone.command_aliases(aliases^)
app.add_subcommand(clone^)
app cl https://example.com/repo.git   # dispatches to "clone"
app clone https://example.com/repo.git # still works
var result = app.parse()
print(result.subcommand)  # always "clone", even if user typed "cl"

Aliases appear in help output alongside the primary name:

commands:
  clone, cl    Clone a repository
  commit, ci   Record changes to the repository

Aliases are also included in shell-completion scripts and typo suggestions.

Unknown Subcommand Error

When the root command has subcommands registered and allow_positional_with_subcommands() has not been called, an unrecognised token triggers an error listing available commands:

app foobar
# error: app: Unknown command 'foobar'. Available commands: search, init

The error message excludes the auto-registered help subcommand and hidden subcommands from the list.

If the command has opted in via allow_positional_with_subcommands(), unknown tokens are treated as positionals rather than triggering this error.

Hidden Subcommands

A hidden subcommand is fully functional but excluded from user-facing surfaces:

  • --help output (the Commands: section and usage line)
  • Shell completion scripts (bash, zsh, fish)
  • “Available commands” error messages
  • Typo suggestions

The subcommand remains dispatchable by its exact name or alias. This is useful for internal, experimental, or deprecated commands.

var app = Command("myapp", "My application")

var debug = Command("debug", "Internal diagnostics")
debug.hidden()                          # mark as hidden
app.add_subcommand(debug^)

var search = Command("search", "Search for items")
app.add_subcommand(search^)

# 'debug' won't appear in --help or completions, but:
#   myapp debug ...   still works

Hidden subcommand aliases also remain functional:

var debug = Command("debug", "Internal diagnostics")
debug.hidden()
var aliases: List[String] = ["dbg"]
debug.command_aliases(aliases^)
app.add_subcommand(debug^)
# myapp dbg   still dispatches to debug

Mixing Positional Args with Subcommands

By default, ArgMojo prevents mixing positional arguments and subcommands on the same command. This follows the convention of major CLI frameworks (cobra, clap, Click) — mixing the two creates ambiguity about whether an unknown token is a misspelt subcommand or a positional value.

var app = Command("app", "My app")
app.add_subcommand(Command("search", "Search"))
app.add_argument(Argument("query", help="Query").positional())  # raises!

The same guard triggers if you add a subcommand to a command that already has positional arguments:

var app = Command("app", "My app")
app.add_argument(Argument("file", help="File").positional())
app.add_subcommand(Command("init", "Init"))  # raises!

If you genuinely need both (e.g., -- stopping dispatch so the subcommand name becomes a positional), call allow_positional_with_subcommands() before adding either:

var app = Command("app", "My app")
app.allow_positional_with_subcommands()
app.add_subcommand(Command("search", "Search"))
app.add_argument(Argument("fallback", help="Fallback").positional())

# "foo" doesn't match any subcommand → treated as positional
var args: List[String] = ["app", "foo"]
var result = app.parse_arguments(args)
print(result.get_string("fallback"))  # "foo"

Please seriously think twice before doing this — it’s usually better to design your CLI with a clear separation between subcommands and positionals. Allowing both on the same command can lead to confusing user experiences and error messages.


Error path prefix — errors inside child parsing include the full command path for clarity:

app search --unknown-flag
# error: app search: Unknown option '--unknown-flag'

This makes it immediately clear which subcommand triggered the error, especially in deeply nested command trees.

Compile-Time Best Practice: Split Large Command Trees

When your CLI has many subcommands (roughly 10+, e.g., the mgit example), you should build each subcommand in its own function instead of constructing everything in a single monolithic main(). This can reduce compile time by an order of magnitude.

Why monolithic functions compile slowly

Mojo’s compiler includes a lifetime checker (the CheckLifetimes pass) that verifies ownership and borrowing safety — ensuring no value is used after a move, no mutable reference aliases another, and every value is destroyed exactly once. To do this it performs liveness analysis: at every program point in a function, it computes which variables are still “live” (may be read or moved later).

[!Note] See Mojo Miji - Chapter Lifetimes and origins on the ownership model and lifetime checking of Mojo.

The cost of this analysis depends on two factors that multiply together:

  1. Number of live variables (N) — every Command, Argument, and temporary created by a builder chain (e.g., Argument("x").long["y"]().flag() produces intermediate owned values) is a variable the checker must track.

  2. Number of program points (M) — roughly proportional to the number of statements in the function.

At each of the M program points, the checker must update the liveness status of up to N variables, making the total work O(N × M). In a monolithic function, both N and M grow together (more subcommands → more variables and more statements), so the cost scales roughly as O(N²).

Concretely, a monolithic main() with 27 subcommands and 107 builder calls creates ~400+ live variables across ~600 statements. The checker must process 400 × 600 ≈ 240,000 variable-point pairs. Split into 13 functions of ~30 variables and ~45 statements each, the total drops to 13 × (30 × 45) ≈ 17,550 — a ~14× reduction in work.

The pattern

Instead of:

# Slow — everything in one scope
def main() raises:
    var app = Command("app", "My app")

    var search = Command("search", "Search")
    search.add_argument(Argument("pattern", help="Pattern").positional())
    search.add_argument(Argument("max-depth", help="Depth").long["max-depth"]())
    app.add_subcommand(search^)

    var init = Command("init", "Init")
    init.add_argument(Argument("name", help="Name").positional())
    app.add_subcommand(init^)

    # ... 10 more subcommands ...

    app.execute()

Write:

# Fast — each subcommand in its own function
def generate_search_subcommand() raises -> Command:
    var cmd = Command("search", "Search")
    cmd.add_argument(Argument("pattern", help="Pattern").positional())
    cmd.add_argument(Argument("max-depth", help="Depth").long["max-depth"]())
    return cmd^

def generate_init_subcommand() raises -> Command:
    var cmd = Command("init", "Init")
    cmd.add_argument(Argument("name", help="Name").positional())
    return cmd^

# ... one function per subcommand ...

def main() raises:
    var app = Command("app", "My app")
    app.add_subcommand(generate_search_subcommand())
    app.add_subcommand(generate_init_subcommand())
    app.execute()

Each generator function has its own small scope — the lifetime checker analyses it independently in O(k²) time where k is tiny. The total work across all functions is far less than one giant O(N²) pass.

Real-world measurement

The mgit.mojo example (27 subcommands, 107 builder calls) demonstrated this in one measured run (MacBook Pro M4 Pro, Mojo nightly 2025.7):

LayoutCompile time
Monolithic main()~320 s
Split into 13 generate_*_subcommand() functions~13 s

Roughly a 25× speedup from a purely structural refactor — no logic changes. Exact numbers vary by machine, compiler version, and build settings.

Rule of thumb

If your main() constructs more than ~5 subcommands, factor each one into a generate_<name>_subcommand() function that returns Command. This keeps every function body small and gives the Mojo lifetime checker an easy job.