π nanoargs
A lightweight, zero-dependency argument parser for Rust.
Part of the nano crate family β zero-dependency building blocks for Rust.
Everything you'd expect from a CLI parser β flags, options, subcommands, help generation, env fallback, typed parsing β with zero dependencies.
Why nanoargs?
Choosing a CLI parser in Rust usually feels like a compromise:
clapis the gold standard, but it's a heavy lift. It pulls in 10+ transitive dependencies, deep customization and vast api reference sheets.pico-args/lexoptare zero-dep, but they leave the hard work to you. You'll end up hand-coding your own --help strings, ENV fallbacks, and subcommand logic.nanoargsis the middle ground. You get the professional features you actually use like subcommands, help generation, and env fallbacks, with zero dependencies.
| Feature | nanoargs |
clap |
bpaf |
pico-args |
lexopt |
|---|---|---|---|---|---|
| Dependencies (transitive) | 0 | ~12* | 5** | 0 | 0 |
| Auto help text | β | β | β | β | β |
Version flag (--version) |
β | β | β | β | β |
| Env var fallback | β | β | β | β | β |
| Multi-value options | β | β | β | β | β |
| Subcommands | β | β | β | ββ | ββ |
Combined short flags (-abc) |
β | β | β | βΒ§ | β |
| Default values | β | β | β | β | β |
| Required args | β | β | β | β | β |
| Hidden args | β | β | β | β | β |
| Colored help | βΒ§ | β | βΒ§ | β | β |
| Derive macros | β | β | β | β | β |
| Value validation | β | β | β | β | β |
| Argument groups & conflicts | β | β | β | β | β |
| Shell completions | β | β | βΒ§ | β | β |
| Other advanced features | β | β | β | β | β |
* clap with default features. With derive, ~17 total.
** bpaf combinatoric API has 0 deps. With derive, 5 total (bpaf_derive + syn tree).
β No built-in support. Achievable manually by matching on positional tokens.
Β§ Via opt-in cargo features.
Which one should I use?
clap/bpaf: Your CLI is complex and needs deep customization and advanced support.pico-args/lexopt: Youβre building something tiny where most features aren't a priority.nanoargs: You want a clean, intuitive API that supports 90% of use cases without taking on any dependencies.
Quick Start
use ;
The extract! macro gives you typed, validated fields in one shot. See Extracting Results for the full syntax, or builder_api.rs for the manual accessor API.
Defining Arguments
Flags
Boolean switches toggled by presence.
let parser = new
.flag
.flag
.build;
Options
Key-value arguments with fluent modifiers. Construct an Opt with Opt::new(), chain .placeholder(), .desc(), .short(), .required(), .default(), .env(), .multi(), or .hidden() as needed, then pass it to .option().
let parser = new
.option
.option
.option
.option
.build;
Positionals
Unnamed arguments collected in order. Chain .required() to make a positional mandatory, .default(value) to provide a fallback when omitted, and .multi() to collect all remaining arguments into the last positional.
let parser = new
.positional
.positional
.positional
.build;
A few rules:
- A positional cannot be both
.required()and.default()β that's a build-time error. - A positional cannot be both
.required()and.multi(). - A
.multi()positional must be the last one registered.
Help text reflects these modifiers automatically:
Positional arguments:
<input> Input file
[output] Output file [default: out.txt]
[extra]... Additional arguments
Environment Variable Fallback (example)
Options can fall back to environment variables when not provided on the command line. Chain .env() on the Opt builder. The resolution order is: CLI value β env var β default β error (if required).
let parser = new
.option
.option
.option
.build;
# CLI value takes priority
# Falls back to env var when CLI option is omitted
MYAPP_OUTPUT=from_env.txt
# Falls back to default when both CLI and env var are absent
Help text automatically shows the associated env var:
Options:
-l, --log-level <LEVEL> Log level [env: MYAPP_LOG_LEVEL]
-o, --output <FILE> Output file (required) [env: MYAPP_OUTPUT]
-f, --format <FMT> Output format [default: text] [env: MYAPP_FORMAT]
Hidden Arguments
Flags and options can be marked as hidden β they parse normally but are excluded from --help output. Useful for internal, debug, or deprecated arguments.
let parser = new
.flag
.option
.flag
.build;
# Hidden arguments work on the command line
# But --help only shows --verbose
The .hidden() modifier is available on both Flag and Opt, and can be called in any order relative to other modifiers.
Combined Short Flags
Combine multiple short flags into a single token. The parser walks characters left-to-right against the registered schema.
let parser = new
.flag
.flag
.flag
.option
.build;
# Combined flags
# Attached option value
# Flags + option in one token
# Equals-delimited option value
When the parser encounters an option character during the walk, it claims all remaining characters as the value. If none remain, it consumes the next argument token.
Subcommands (example)
Git-style subcommands, each with their own flags, options, and positionals. Global flags are parsed before the subcommand token.
let build_parser = new
.name
.description
.flag
.build;
let test_parser = new
.name
.description
.flag
.build;
let parser = new
.name
.description
.flag
.subcommand
.subcommand
.build;
Note: When subcommands are registered, the first bare (non-flag/option) token is always treated as the subcommand name. Parent-level positional arguments are not supported alongside subcommands β this matches git-style CLI conventions.
# Supported β global flags before the subcommand: # NOT supported β positionals before the subcommand:
Version Flag
Built-in --version / -V support. Set a version string on the builder and the parser handles the rest.
let parser = new
.name
.version
.flag
.build
.unwrap;
The -V short flag is reserved when a version is configured β the builder will reject any user-registered flag or option that uses 'V' as its short form. When no version is set, --version and -V are treated as unknown arguments, and 'V' is available for user flags.
When both --help and --version appear, whichever comes first wins. After --, both are treated as positionals.
Value Validation (example)
Attach validators to options and positionals so that invalid values are rejected during parsing with clear error messages. Use the built-in range(), one_of(), non_empty(), min_length(), max_length(), and path_exists() convenience validators, or supply a custom closure.
use ;
let parser = new
.option
.option
.option
.positional
.build;
Validators run on all value sources β CLI arguments, environment variable fallbacks, and defaults β so misconfigured defaults are caught early. When a validator has a hint string (auto-generated by range and one_of), it appears in help text:
Options:
-p, --port <NUM> Port number [default: 3000] [range: 1..65535]
-l, --level <LEVEL> Log level [values: debug|info|warn|error]
For a custom hint, use Validator::with_hint():
with_hint
Argument Groups and Conflicts (example)
Declare relationships between arguments: groups require at least one member ("pick at least one"), and conflicts enforce mutual exclusivity ("pick at most one").
use ;
let parser = new
.flag
.option
.flag
.flag
.flag
.group
.conflict
.build
.unwrap;
Groups and conflicts are validated after all parsing and fallback resolution. An option with a default or env var counts as "provided" for both group satisfaction and conflict detection. Help text shows the relationships automatically:
Argument Groups:
input source --stdin, --file (at least one required)
Conflicts:
output format --json, --csv, --yaml (mutually exclusive)
Shell Completions (example)
Generate tab-completion scripts for Bash, Zsh, Fish, and PowerShell directly from your parser schema. The scripts include all non-hidden flags, options, and subcommands with descriptions.
use ;
let parser = new
.name
.flag
.option
.build
.unwrap;
let shell: Shell = "zsh".parse.unwrap;
print!;
Install completions for each shell:
# Bash
# or source it directly:
# Zsh β place in your fpath
# Fish
# PowerShell β add to your $PROFILE
Parsing and Results
Extracting Results (example)
The extract! macro is the recommended way to pull typed values out of a ParseResult. It replaces scattered get_flag / get_option_required / get_option_or_default calls with a single declaration:
let opts = extract!.unwrap;
println!;
Field names are automatically mapped to CLI option names by converting underscores to hyphens (listen_port β "listen-port"). Override with as "name" when needed:
let opts = extract!.unwrap;
Positional arguments can be extracted with as @pos β no more manual indexing into get_positionals():
let opts = extract!.unwrap;
Positional indices are assigned sequentially among @pos fields (non-@pos fields don't consume indices). The full set of positional variants:
| Syntax | Behavior |
|---|---|
name: T as @pos |
Required β error if absent |
name: Option<T> as @pos |
Optional β None if absent |
name: T as @pos = expr |
Default β falls back to expr if absent (macro-level only, not visible in --help) |
name: Vec<T> as @pos |
Remaining β collects all from current index onward |
Declare them in order: required β optional/default β Vec (remaining). Vec<T> as @pos must be last since it consumes all remaining positionals.
The macro returns Result<Struct, OptionError>, so use .unwrap() or ? as appropriate. The ParseResult is borrowed, so you can still call accessors afterward.
Accessors
parse_env() reads from std::env::args() and returns a Result<ParseResult, ParseError>:
let result = parser.parse_env?;
// Flags return bool
let verbose = result.get_flag;
// Options return Option<&str>
let output = result.get_option;
// Multi-value options return &[String]
let tags = result.get_option_values;
// Positionals in order
let positionals = result.get_positionals;
// Subcommand access
if let Some = result.subcommand
Accessors like get_flag and get_option use string keys, so a typo like get_flag("verbos") would silently return false. To catch these during development, nanoargs includes debug_assert! checks that panic if you access a name that was never registered. These checks run automatically in debug builds (cargo test, cargo run) and are stripped in release builds with zero overhead.
For the full manual accessor API (all get_option_* variants, get_option_values_*, etc.), see builder_api.rs.
You can also pass your own args with parser.parse(args) β see Error Handling for the full match pattern.
Typed Parsing
Parse option values into any type implementing FromStr. Convenience helpers collapse the common three-way match into a single call. All typed helpers return Result<T, OptionError>, so parse errors are always surfaced β never silently swallowed:
// With a default fallback β returns Ok(parsed) or Ok(default) if absent.
// Returns Err on parse failure (e.g. --jobs abc).
let jobs: u32 = result.get_option_or_default?;
// With a lazy default β closure only runs if the option is absent.
// Returns Err on parse failure without calling the closure.
let jobs: u32 = result.get_option_or?;
// Required β Err if absent or unparseable
let jobs: u32 = result.get_option_required?;
For fine-grained control over parse errors, the original accessor is still available:
match result.
Error Handling (example)
match parser.parse
Help and Output
Help Text (example)
Auto-generated from your schema. Triggered by --help or -h.
)
)
Colored Help (opt-in)
Enable the color feature to get ANSI-colored help text and error messages via nanocolor:
[]
= { = "0.1", = ["color"] }
When enabled, section headers are bold yellow, flag/option names are green, placeholders are cyan, and metadata like [default: ...] is dim. Error messages get a bold red error: prefix. Color is automatically suppressed when NO_COLOR is set or output is not a TTY (handled by nanocolor). Without the feature, the crate remains zero-dependency and output is unchanged.
Double-Dash Separator
Everything after -- is treated as a positional, even if it looks like a flag or option.
# positionals: ["--not-a-flag", "-abc"]
Schema-Free Parsing for Quick Scripts
parse_loose() skips the schema entirely β useful for throwaway scripts where defining flags and options feels like overkill.
It uses a heuristic to guess whether --key is a flag or an option: if the next token doesn't start with -, it's consumed as the value.
When it works well: simple scripts with clear flag/option boundaries (--verbose --output file.txt).
When it doesn't: --output -v silently treats --output as a flag (not an option), because -v starts with -. If your CLI has options that could receive flag-like values, use ArgBuilder instead.
API Reference
See the full API docs on docs.rs.
Examples
| Example | Description | Run |
|---|---|---|
| extract | extract! macro β the recommended API |
cargo run --example extract -- -o=result.txt -j 8 input.txt |
| builder_api | Manual builder API for power users | cargo run --example builder_api -- -o result.txt -j 8 -v input.txt |
| subcommands | Git-style subcommands with extract! |
cargo run --example subcommands -- build --release |
| env_fallback | Environment variable fallback | cargo run --example env_fallback -- --output out.txt |
| error_handling | ParseError variant handling |
cargo run --example error_handling |
| help_text | Auto-generated help text | cargo run --example help_text -- --help |
| value_validation | Declarative value validation | cargo run --example value_validation -- --port 8080 --level info /tmp/out |
| groups_and_conflicts | Argument groups and mutual exclusivity | cargo run --example groups_and_conflicts -- --file data.csv --json |
| completions | Shell completion script generation | cargo run --example completions -- zsh |
Contributing
Contributions are welcome. To get started:
- Fork the repository
- Create a feature branch (
git checkout -b my-feature) - Make your changes
- Run the tests:
cargo test - Submit a pull request
Please keep changes minimal and focused. This crate's goal is to stay small and dependency-free.
License
This project is licensed under the MIT License.