clap-nested 0.3.0

Convenient `clap` for CLI apps with multi-level subcommands.
Documentation

clap-nested

Cargo Crate Docs License Build Status Coverage Status

Convenient clap for CLI apps with multi-level subcommands.

Installation

Add clap-nested to your Cargo.toml:

[dependencies]
clap-nested = "0.3.0"

Why?

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.

Use cases

Main use cases of clap-nested, together with explanation, justification, and related code examples are below:

You can always find more in the documentation.

Examples

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.