Crates.io | clap-nested |
lib.rs | clap-nested |
version | 0.4.0 |
source | src |
created_at | 2019-09-13 19:37:52.483069 |
updated_at | 2020-05-29 10:39:32.312502 |
description | Convenient `clap` for CLI apps with multi-level subcommands. |
homepage | https://github.com/skymavis/clap-nested |
repository | https://github.com/skymavis/clap-nested |
max_upload_size | |
id | 164638 |
size | 30,986 |
Convenient clap
for CLI apps with multi-level subcommands.
Add clap-nested
to your Cargo.toml
:
[dependencies]
clap-nested = "0.4.0"
First of all, clap
is awesome!
It provides a fast, simple-to-use, and full-featured library for parsing CLI arguments as well as subcommands.
However, while supporting parsing nicely, clap
is very unopinionated
when it comes to how we should structure and execute logic given provided
arguments and subcommands.
That's why we often find ourselves matching clap
's parsing result with
tens of subcommands, let alone a lot of arguments, in our CLI application which
includes multi-level subcommands. The bad experience also escalates quickly,
imagine suddenly we have a lot of subcommand logic grouped under a very long
file.
So, we add a little sauce of opinion into clap
to help with that
awkward process.
Main use cases of clap-nested
, together with explanation, rationale,
and related code examples are below:
You can always find more in the documentation.
With clap-nested
, we can write in a more organized way:
// foo.rs
pub fn get_cmd<'a>() -> Command<'a, str> {
Command::new(file_stem!())
.description("Shows foo")
.options(|app| {
app.arg(
Arg::with_name("debug")
.short("d")
.help("Prints debug information verbosely"),
)
})
.runner(|args, matches| {
let debug = clap::value_t!(matches, "debug", bool).unwrap_or_default();
println!("Running foo, env = {}, debug = {}", args, debug);
Ok(())
})
}
// bar.rs
pub fn get_cmd<'a>() -> Command<'a, str> {
Command::new(file_stem!())
.description("Shows bar")
.runner(|args, _matches| {
println!("Running bar, env = {}", args);
Ok(())
})
}
// main.rs
fn main() {
Commander::new()
.options(|app| {
app.arg(
Arg::with_name("environment")
.short("e")
.long("env")
.global(true)
.takes_value(true)
.value_name("STRING")
.help("Sets an environment value, defaults to \"dev\""),
)
})
.args(|_args, matches| matches.value_of("environment").unwrap_or("dev"))
.add_cmd(foo::get_cmd())
.add_cmd(bar::get_cmd())
.no_cmd(|_args, _matches| {
println!("No subcommand matched");
Ok(())
})
.run();
}
Kindly see examples/clap_nested/
and examples/clap.rs
for comparison.