Crates.io | nameless-clap |
lib.rs | nameless-clap |
version | 3.0.0-beta.2.2 |
source | src |
created_at | 2021-03-02 19:58:33.104011 |
updated_at | 2022-11-27 18:11:18.685497 |
description | A simple to use, efficient, and full-featured Command Line Argument Parser |
homepage | https://clap.rs/ |
repository | https://github.com/sunfishcode/clap |
max_upload_size | |
id | 362850 |
size | 841,006 |
This is nameless-clap, a temporary fork of clap
for the nameless
project.
These are the patches we currently have:
Upstream clap_derive
parses command-line arguments twice. The first patch
makes it parse arguments just once:
The PR is here: https://github.com/clap-rs/clap/pull/2206
The second patch adds an auto
mode which uses some Rust type magic to
automatically select between FromStr
, TryFrom<&OsStr>
, and other parsing
traits based on which traits a type implements. This means that users don't
need to manually configure things in many cases; more things Just Work:
The PR is here: https://github.com/clap-rs/clap/pull/2298
The third patch adds a new parsing trait, TryFromOsArg
, which is for
parsing functions which may have side effects such as acquiring resources,
as nameless
's types do. This avoids the having side effects in FromStr
and similar traits. Thanks to auto
(the first patch above), this new trait
is automatically used when applicable, and thanks to parsing the arguments
only once (the second patch above), the side effects are only produced once.
This patch is not yet submitted upstream, as it depends on the previous two.
The upstream README.md content follows...
Command Line Argument Parser for Rust
It is a simple-to-use, efficient, and full-featured library for parsing command line arguments and subcommands when writing command line, console or terminal applications.
We are currently hard at work trying to release 3.0
. We have a 3.0.0-beta.2
prerelease out but we do not give any guarantees that its API is stable. We do not have a changelog yet which will be written down after we are sure about the API stability. We recommend users to not update to the prerelease version yet and to wait for the official 3.0
.
If you're looking for the readme & examples for
clap v2.33
- find it on github, crates.io, docs.rs.
clap
is used to parse and validate the string of command line arguments provided by a user at runtime. You provide the list of valid possibilities, and clap
handles the rest. This means you focus on your applications functionality, and less on the parsing and validating of arguments.
clap
provides many things 'for free' (with no configuration) including the traditional version and help switches (or flags) along with associated messages. If you are using subcommands, clap
will also auto-generate a help
subcommand and separate associated help messages.
Once clap
parses the user provided string of arguments, it returns the matches along with any applicable values. If the user made an error or typo, clap
informs them with a friendly message and exits gracefully (or returns a Result
type and allows you to perform any clean up prior to exit). Because of this, you can make reasonable assumptions in your code about the validity of the arguments prior to your applications main execution.
How does clap
compare to structopt?
For a full FAQ, see this
Below are a few of the features which clap
supports, full descriptions and usage can be found in the documentation and examples directory
clap_generate
-f
and --flag
respectively)-fBgoZ
is the same as -f -B -g -o -Z
)-vvv
or -v -v -v
)myprog <file>...
such as myprog file1.txt file2.txt
being two values for the same "file" argument)-o value
, -ovalue
, -o=value
and --option value
or --option=value
respectively)-o <val1> -o <val2>
or -o <val1> <val2>
)-o=val1,val2,val3
, can also change the delimiter)-o <FILE> <INTERFACE>
etc. for when you require specific multiple valuesgit add <file>
where add
is a sub-command of git
)
--mode
option which may only have one of two values fast
or slow
such as --mode fast
or --mode slow
)clap
is fully compatible with Rust's env!()
macro for automatically setting the version of your application to the version in your Cargo.toml. See 09_auto_version example for how to do this (Thanks to jhelwig for pointing this out)clap
to get typed values (i.e. i32
, u8
, etc.) from positional or option arguments so long as the type you request implements std::str::FromStr
See the 12_typed_values example. You can also use clap
s arg_enum!
macro to create an enum with variants that automatically implement std::str::FromStr
. See 13_enum_values example for details--myoption
argument, and the user mistakenly typed --moyption
(notice y
and o
transposed), they would receive a Did you mean '--myoption'?
error and exit gracefully. This also works for subcommands and flags. (Thanks to Byron for the implementation) (This feature can optionally be disabled, see 'Optional Dependencies / Features')alias ls='ls -l'
but then using ls -C
in your terminal which ends up passing ls -l -C
as the final arguments. Since -l
and -C
aren't compatible, this effectively runs ls -C
in clap
if you choose...clap
also supports hard conflicts that fail parsing). (Thanks to Vinatorul!)--
meaning, only positional arguments followThe following examples show a quick example of some of the very basic functionality of clap
. For more advanced usage, such as requirements, conflicts, groups, multiple values and occurrences see the documentation, examples directory of this repository.
NOTE: All of these examples are functionally the same, but show different styles in which to use clap
. These different styles are purely a matter of personal preference.
Add clap
to your Cargo.toml
[dependencies]
clap = { version = "3.0.0-beta.2", package = "nameless-clap" }
The first example shows the simplest way to use clap
, by defining a struct. If you're familiar with the structopt
crate you're in luck, it's the same! (In fact it's the exact same code running under the covers!)
Clap introduces the additional convenience of auto-detecting whether a type implements FromStr
, From<&OsStr>
, TryFrom<&OsStr>
and other standard parsing traits, so in many cases it's no longer necessary to use attributes such as parse(try_from_str)
, parse(from_os_str)
, parse(try_from_os_str)
, and similar.
// (Full example with detailed comments in examples/01d_quick_example.rs)
//
// This example demonstrates clap's full 'custom derive' style of creating arguments which is the
// simplest method of use, but sacrifices some flexibility.
use clap::{AppSettings, Clap};
/// This doc string acts as a help message when the user runs '--help'
/// as do all doc strings on fields
#[derive(Clap)]
#[clap(version = "1.0", author = "Kevin K. <kbknapp@gmail.com>")]
#[clap(setting = AppSettings::ColoredHelp)]
struct Opts {
/// Sets a custom config file. Could have been an Option<T> with no default too
#[clap(short, long, default_value = "default.conf")]
config: String,
/// 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,
#[clap(subcommand)]
subcmd: SubCommand,
}
#[derive(Clap)]
enum SubCommand {
#[clap(version = "1.3", author = "Someone E. <someone_else@other.com>")]
Test(Test),
}
/// A subcommand for controlling testing
#[derive(Clap)]
struct Test {
/// Print debug info
#[clap(short)]
debug: bool
}
fn main() {
let opts: Opts = Opts::parse();
// Gets a value for config if supplied by user, or defaults to "default.conf"
println!("Value for config: {}", opts.config);
println!("Using input file: {}", opts.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 opts.verbose {
0 => println!("No verbose info"),
1 => println!("Some verbose info"),
2 => println!("Tons of verbose info"),
_ => println!("Don't be crazy"),
}
// You can handle information about subcommands by requesting their matches by name
// (as below), requesting just the name used, or both at the same time
match opts.subcmd {
SubCommand::Test(t) => {
if t.debug {
println!("Printing debug info...");
} else {
println!("Printing normally...");
}
}
}
// more program logic goes here...
}
This second method shows a method using the 'Builder Pattern' which allows more advanced configuration options (not shown in this small example), or even dynamically generating arguments when desired. The downside is it's more verbose.
// (Full example with detailed comments in examples/01b_quick_example.rs)
//
// This example demonstrates clap's "builder pattern" method of creating arguments
// which the most flexible, but also most verbose.
use clap::{Arg, App};
fn main() {
let matches = App::new("My Super Program")
.version("1.0")
.author("Kevin K. <kbknapp@gmail.com>")
.about("Does awesome things")
.arg(Arg::new("config")
.short('c')
.long("config")
.value_name("FILE")
.about("Sets a custom config file")
.takes_value(true))
.arg(Arg::new("INPUT")
.about("Sets the input file to use")
.required(true)
.index(1))
.arg(Arg::new("v")
.short('v')
.multiple_occurrences(true)
.takes_value(true)
.about("Sets the level of verbosity"))
.subcommand(App::new("test")
.about("controls testing features")
.version("1.3")
.author("Someone E. <someone_else@other.com>")
.arg(Arg::new("debug")
.short('d')
.about("print debug information verbosely")))
.get_matches();
// You can check the value provided by positional arguments, or option arguments
if let Some(i) = matches.value_of("INPUT") {
println!("Value for input: {}", i);
}
if let Some(c) = matches.value_of("config") {
println!("Value for config: {}", c);
}
// You can see how many times a particular flag or argument occurred
// Note, only flags can have multiple occurrences
match matches.occurrences_of("v") {
0 => println!("Verbose mode is off"),
1 => println!("Verbose mode is kind of on"),
2 => println!("Verbose mode is on"),
_ => println!("Don't be crazy"),
}
// You can check for the existence of subcommands, and if found use their
// matches just as you would the top level app
if let Some(ref matches) = matches.subcommand_matches("test") {
// "$ myapp test" was run
if matches.is_present("debug") {
// "$ myapp test -d" was run
println!("Printing debug info...");
} else {
println!("Printing normally...");
}
}
// Continued program logic goes here...
}
The next example shows a far less verbose method, but sacrifices some of the advanced configuration options (not shown in this small example). This method also takes a very minor runtime penalty.
// (Full example with detailed comments in examples/01a_quick_example.rs)
//
// This example demonstrates clap's "usage strings" method of creating arguments
// which is less verbose
use clap::App;
fn main() {
let matches = App::new("myapp")
.version("1.0")
.author("Kevin K. <kbknapp@gmail.com>")
.about("Does awesome things")
.arg("-c, --config=[FILE] 'Sets a custom config file'")
.arg("<INPUT> 'Sets the input file to use'")
.arg("-v... 'Sets the level of verbosity'")
.subcommand(App::new("test")
.about("controls testing features")
.version("1.3")
.author("Someone E. <someone_else@other.com>")
.arg("-d, --debug 'Print debug information'"))
.get_matches();
// Same as previous example...
}
This third method shows how you can use a YAML file to build your CLI and keep your Rust source tidy or support multiple localized translations by having different YAML files for each localization.
First, create the cli.yaml
file to hold your CLI options, but it could be called anything we like:
name: myapp
version: "1.0"
author: Kevin K. <kbknapp@gmail.com>
about: Does awesome things
args:
- config:
short: c
long: config
value_name: FILE
about: Sets a custom config file
takes_value: true
- INPUT:
about: Sets the input file to use
required: true
index: 1
- verbose:
short: v
multiple: true
about: Sets the level of verbosity
subcommands:
- test:
about: controls testing features
version: "1.3"
author: Someone E. <someone_else@other.com>
args:
- debug:
short: d
about: print debug information
Since this feature requires additional dependencies that not everyone may want, it is not compiled in by default and we need to enable a feature flag in Cargo.toml:
Simply add the yaml
feature flag to your Cargo.toml
.
[dependencies]
clap = { version = "3.0.0-beta.2", package = "nameless-clap", features = ["yaml"] }
Finally we create our main.rs
file just like we would have with the previous two examples:
// (Full example with detailed comments in examples/17_yaml.rs)
//
// This example demonstrates clap's building from YAML style of creating arguments which is far
// more clean, but takes a very small performance hit compared to the other two methods.
use clap::{App, load_yaml};
fn main() {
// The YAML file is found relative to the current file, similar to how modules are found
let yaml = load_yaml!("cli.yaml");
let matches = App::from(yaml).get_matches();
// Same as previous examples...
}
Finally there is a macro version, which is like a hybrid approach offering the speed of the builder pattern (the first example), but without all the verbosity.
use clap::clap_app;
fn main() {
let matches = clap_app!(myapp =>
(version: "1.0")
(author: "Kevin K. <kbknapp@gmail.com>")
(about: "Does awesome things")
(@arg CONFIG: -c --config +takes_value "Sets a custom config file")
(@arg INPUT: +required "Sets the input file to use")
(@arg verbose: -v --verbose "Print test information verbosely")
(@subcommand test =>
(about: "controls testing features")
(version: "1.3")
(author: "Someone E. <someone_else@other.com>")
(@arg debug: -d ... "Sets the level of debugging information")
)
).get_matches();
// Same as previous examples...
}
If you were to compile any of the above programs and run them with the flag --help
or -h
(or help
subcommand, since we defined test
as a subcommand) the following would be output (except the first example where the help message sort of explains the Rust code).
$ myprog --help
My Super Program 1.0
Kevin K. <kbknapp@gmail.com>
Does awesome things
ARGS:
INPUT The input file to use
USAGE:
MyApp [FLAGS] [OPTIONS] <INPUT> [SUBCOMMAND]
FLAGS:
-h, --help Prints help information
-v Sets the level of verbosity
-V, --version Prints version information
OPTIONS:
-c, --config <FILE> Sets a custom config file
SUBCOMMANDS:
help Prints this message or the help of the given subcommand(s)
test Controls testing features
NOTE: You could also run myapp test --help
or myapp help test
to see the help message for the test
subcommand.
To try out the pre-built examples, use the following steps:
$ git clone https://github.com/clap-rs/clap && cd clap/
$ cargo build --example <EXAMPLE>
$ ./target/debug/examples/<EXAMPLE> --help
$ cargo run --example <EXAMPLE> -- [args to example]
To test out clap
's default auto-generated help/version follow these steps:
$ cargo new fake --bin && cd fake
$ cargo build --release
$ ./target/release/fake --help
or $ ./target/release/fake --version
For full usage, add clap
as a dependency in your Cargo.toml
to use from crates.io:
[dependencies]
clap = { version = "3.0.0-beta.2", package = "nameless-clap" }
Define a list of valid arguments for your program (see the documentation or examples directory of this repo)
Then run cargo build
or cargo update && cargo build
for your project.
#[derive(Clap)]
). Without this you must use one of the other methods of creating a clap
CLI listed above.CARGO_*
environment variables.Did you mean '--myoption'?
feature for when users make typos. (builds dependency strsim
)AppSettings::ColoredHelp
. (builds dependency termcolor
)textwrap
)To disable these, add this to your Cargo.toml
:
[dependencies.clap]
version = "3.0.0-beta.2"
default-features = false
features = ["std"]
You can also selectively enable only the features you'd like to include, by adding:
[dependencies.clap]
version = "3.0.0-beta.2"
default-features = false
# Cherry-pick the features you'd like to use
features = ["std", "suggestions", "color"]
term-size
)yaml-rust
)regex
)You can find complete documentation on the docs.rs for this project.
You can also find usage examples in the examples directory of this repo.
Details on how to contribute can be found in the CONTRIBUTING.md file.
Because clap
takes SemVer and compatibility seriously, this is the official policy regarding breaking changes and minimum required versions of Rust.
clap
will pin the minimum required version of Rust to the CI builds. Bumping the minimum version of Rust is considered a minor breaking change, meaning at a minimum the minor version of clap
will be bumped.
In order to keep from being surprised of breaking changes, it is highly recommended to use the ~major.minor.patch
style in your Cargo.toml
only if you wish to target a version of Rust that is older than current stable minus two releases:
[dependencies]
clap = { version = "~3.0.0-beta.2", package = "nameless-clap" }
This will cause only the patch version to be updated upon a cargo update
call, and therefore cannot break due to new features, or bumped minimum versions of Rust.
clap
will officially support current stable Rust, minus two releases, but may work with prior releases as well. For example, current stable Rust at the time of this writing is 1.38.0, meaning clap
is guaranteed to compile with 1.36.0 and beyond.
At the 1.39.0 stable release, clap
will be guaranteed to compile with 1.37.0 and beyond, etc.
The following is a list of the minimum required version of Rust to compile clap
by our MAJOR.MINOR
version number:
clap | MSRV |
---|---|
>=3.0 | 1.46.0 |
>=2.21 | 1.24.0 |
>=2.2 | 1.12.0 |
>=2.1 | 1.6.0 |
>=1.5 | 1.4.0 |
>=1.4 | 1.2.0 |
>=1.2 | 1.1.0 |
>=1.0 | 1.0.0 |
clap
takes a similar policy to Rust and will bump the major version number upon breaking changes with only the following exceptions:
clap
is distributed under the terms of both the MIT license and the Apache License (Version 2.0).
See the LICENSE-APACHE and LICENSE-MIT files in this repository for more information.
There are several excellent crates which can be used with clap
, I recommend checking them all out! If you've got a crate that would be a good fit to be used with clap
open an issue and let me know, I'd love to add it!
assert_cmd
- This crate allows you test your CLIs in a very intuitive and functional way!