Declarative API (Struct-Based)
Status: Available since v0.5.0. The declarative API is optional — if you prefer the builder API, nothing changes for you.
ArgMojo provides a struct-based declarative API inspired by Swift’s
swift-argument-parser. Instead
of building Command + Argument chains imperatively, you define a struct that
conforms to the Parsable trait, and ArgMojo uses compile-time reflection to
generate the parser automatically.
from argmojo import Parsable, Option, Flag, Positional, Count
Wrapper Types
Four wrapper types encode argument metadata as compile-time parameters:
| Wrapper | CLI syntax | Example |
|---|---|---|
Positional[T] | Bare value, matched by order | var input: Positional[String, help="Input file", required=True] |
Option[T] | --key value or -k value | var output: Option[String, long="output", short="o"] |
Flag | --switch (no value) | var verbose: Flag[short="v", help="Verbose mode"] |
Count | -vvv (repeated) | var debug: Count[short="d", help="Debug level", max=3] |
Each wrapper accepts the same parameters as the corresponding builder methods
(e.g. choices, default, append, range_min/range_max, group,
prompt, password, etc.) as compile-time keyword parameters. See
src/argmojo/argument_wrappers.mojo for the full parameter list.
As for the value type T, Option[T] and Positional[T] accept String,
Int, Float64 and List[String], and Option[T] additionally accepts
Dict[String, String] when map_option=True. Anything else is rejected at
compile time with a message listing what is allowed. There is no Option[Bool]
— use Flag for that.
To read a value back, use .value. Flag and Count also define __bool__
and __int__, so they can be converted directly:
if args.verbose: # Flag → Bool
print("level:", Int(args.debug)) # Count → Int
print(args.ratio.value) # everything else via .value
One restriction worth flagging: range validation is integer-only. has_range
parses the value with atol and cannot express a fractional bound, so
has_range=True together with Float64 is refused at compile time instead of
failing at run time with a confusing “expected an integer”. Check fractional
bounds yourself after parsing.
The Parsable Trait
A struct conforming to Parsable only needs to provide description():
struct MyArgs(Parsable):
var pattern: Positional[String, help="Search pattern", required=True]
var verbose: Flag[short="v", help="Verbose output"]
@staticmethod
def description() -> String:
return "My awesome tool."
No __init__ is needed — the trait auto-initialises all fields via reflection.
Optional overrides:
| Method | Default | Purpose |
|---|---|---|
description() | (required) | Help text description |
version() | "0.1.0" | --version string |
name() | "command" | Program name in help |
subcommands() | no-op | Register child commands (see below) |
run() | no-op | Execute command logic after parsing |
Pure Declarative — One-Line Parse
For simple tools, one line is all you need:
def main() raises:
var arguments = Search.parse() # build + parse sys.argv() + typed result
print(arguments.pattern.value)
print(arguments.verbose.value)
For testing without a real binary, use parse_arguments() with an explicit
argument list:
var arguments = Search.parse_arguments(List[String]("search", "--verbose", "query"))
See examples/declarative/search.mojo
for a complete example.
Hybrid — Declarative + Builder Customisation
When you need builder-level features (mutually exclusive groups, implications,
colours, tips) on top of a declarative struct, use the to_command() → modify →
parse_from_command() bridge:
def main() raises:
var command = Deploy.to_command() # struct → owned Command
command.mutually_exclusive(["force", "dry_run"])
command.implies("force", "validated")
command.add_tip("Use --dry-run to preview changes first")
command.header_color["CYAN"]()
var deploy = Deploy.parse_from_command(command^) # Command → typed struct
print(deploy.target.value)
See examples/declarative/deploy.mojo
for a complete example.
Full Parse — Declarative + Extra Builder Fields
When some arguments are too complex for the struct, add them via builder methods
and retrieve both the typed struct and the raw ParseResult:
def main() raises:
var command = Convert.to_command()
command.add_argument(
Argument("format", help="Output format")
.long["format"]().choice["json"]().choice["yaml"]().default["json"]()
)
var (args, raw) = Convert.parse_full_from_command(command^)
print(args.input.value) # typed — from struct
print(raw.get_string("format")) # untyped — from builder
See examples/declarative/convert.mojo
for a complete example.
Subcommands in Declarative API
Every level in the command tree is a Parsable struct. Register children via
the subcommands() hook:
struct Clone(Parsable):
var url: Positional[String, help="Repository URL", required=True]
var depth: Option[Int, long="depth", help="Clone depth", default="0"]
@staticmethod
def description() -> String: return "Clone a repository."
@staticmethod
def name() -> String: return "clone"
def run(self) raises:
print("Cloning:", self.url.value)
struct MyGit(Parsable):
var verbose: Flag[short="v", help="Verbose output", persistent=True]
@staticmethod
def name() -> String: return "mgit"
@staticmethod
def description() -> String: return "A mini git tool."
@staticmethod
def subcommands() raises -> List[Command]:
var subs = List[Command]()
subs.append(Clone.to_command())
return subs^
def main() raises:
var (git_args, result) = MyGit.parse_full()
if git_args.verbose:
print("Verbose mode on")
if result.subcommand == "clone":
var sub = result.get_subcommand_result()
Clone.from_parse_result(sub).run()
See examples/declarative/jomo.mojo for a
more complete example that mixes declarative and builder subcommands, including
nested subcommands.
Auto-Naming Convention
When you don’t provide an explicit long name, the field name is used with
underscores converted to hyphens:
| Field name | Auto-generated -- name |
|---|---|
max_count | --max-count |
verbose | --verbose |
output_file | --output-file |
Fields wrapped in Positional[...] don’t get auto-generated long names.
API Summary
| Method | Returns | Purpose |
|---|---|---|
T.parse() | T | Build + parse sys.argv() + typed result |
T.parse_arguments(arguments) | T | Parse explicit arg list (testing) |
T.to_command() | Command | Reflect struct → owned Command for customisation |
T.parse_from_command(command^) | T | Parse a customised Command → typed struct |
T.parse_full() | Tuple[T, ParseResult] | Typed struct + raw result from sys.argv() |
T.parse_full_from_command(command^) | Tuple[T, ParseResult] | Typed struct + raw result from customised Command |
T.from_parse_result(result) | T | Write-back from existing ParseResult (subcommand dispatch) |
The four parsing methods follow a 2×2 naming convention:
sys.argv() | from Command | |
|---|---|---|
returns Self | parse() | parse_from_command(command^) |
returns Tuple | parse_full() | parse_full_from_command(command^) |
fullmeans dual return — you get both the typed struct and the rawParseResult.from_commandmeans parsing from a pre-configuredCommand(created viato_command()+ builder customisation).