Command Line Argument Parser for Rust
Dual-licensed under Apache 2.0 or MIT.
Create your command-line parser, with all of the bells and whistles, declaratively or procedurally.
use clap::Parser;
#[derive(Parser)]
#[clap(about, version, author)] // Pull these from `Cargo.toml`
struct Cli {
/// Sets a custom config file. Could have been an Option<T> with no default too
#[clap(short, long, default_value = "default.toml", value_name = "PATH")]
config: std::path::PathBuf,
/// Some input. Because this isn't an Option<T> it's required to be used
input: String,
/// A level of verbosity, and can be used multiple times
#[clap(short, long, parse(from_occurrences))]
verbose: i32,
}
fn main() {
let args = Cli::parse();
println!("Value for config: {}", args.config.display());
println!("Using input file: {}", args.input);
// Vary the output based on how many times the user used the "verbose" flag
// (i.e. 'myprog -v -v -v' or 'myprog -vvv' vs 'myprog -v'
match args.verbose {
0 => println!("No verbose info"),
1 => println!("Some verbose info"),
2 => println!("Tons of verbose info"),
_ => println!("Don't be ridiculous"),
}
// more program logic goes here...
}
$ demo --help
clap [..]
A simple to use, efficient, and full-featured Command Line Argument Parser
USAGE:
demo[EXE] [OPTIONS] <INPUT>
ARGS:
<INPUT> Some input. Because this isn't an Option<T> it's required to be used
OPTIONS:
-c, --config <PATH> Sets a custom config file. Could have been an Option<T> with no default
too [default: default.toml]
-h, --help Print help information
-v, --verbose A level of verbosity, and can be used multiple times
-V, --version Print version information
(version number and .exe
extension on windows replaced by placeholders)
While these aspirations can be at odds with fast build times and low binary size, we will still strive to keep these reasonable for the flexibility you get. Check out the argparse-benchmarks for CLI parsers optimized for other use cases.
trycmd
: Snapshot testing
assert_cmd
and assert_fs
no_std
environments in a backwards compatible manner.Did you mean '--myoption'?
feature for when users make typos.#[derive(Parser)]
). Without this you must use one of the other methods of creating a clap
CLI listed above.CARGO_*
environment variables.Warning: These may contain breaking changes between minor releases.
App::replace
AppSettings::Multicall
ArgMatches::grouped_values_of