#clap #cli #completion

clap_complete_command

Reduces boilerplate for adding a shell completion command to Clap

9 releases

Uses new Rust 2021

0.3.4 May 29, 2022
0.3.3 Apr 26, 2022
0.2.2 Apr 7, 2022
0.1.0 Apr 5, 2022

#144 in Command-line interface

Download history 77/week @ 2022-04-21 51/week @ 2022-04-28 61/week @ 2022-05-05 132/week @ 2022-05-12 39/week @ 2022-05-19 50/week @ 2022-05-26 209/week @ 2022-06-02 253/week @ 2022-06-09 55/week @ 2022-06-16 50/week @ 2022-06-23 81/week @ 2022-06-30 71/week @ 2022-07-07 70/week @ 2022-07-14 69/week @ 2022-07-21 59/week @ 2022-07-28 41/week @ 2022-08-04

269 downloads per month

MIT license

15KB
189 lines

clap-complete-command

crates.io

Reduces boilerplate for adding a shell completion command to Clap

Examples

Derive

use clap::{IntoApp, Parser, Subcommand};

#[derive(Parser)]
struct Cli {
    #[clap(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// Generate shell completions
    Completions {
        /// The shell to generate the completions for
        #[clap(arg_enum)]
        shell: clap_complete_command::Shell,
    },
}

fn main() {
    let cli = Cli::parse();

    match cli.command {
        // e.g. `$ cli completions bash`
        Commands::Completions { shell } => {
            shell.generate(&mut Cli::command(), &mut std::io::stdout());
        }
    }
}

Builder

use clap::{Arg, Command};

fn build_cli() -> Command<'static> {
    Command::new(env!("CARGO_PKG_NAME"))
        .subcommand_required(true)
        .subcommand(
            Command::new("completions")
                .about("Generate shell completions")
                .arg(
                    Arg::new("shell")
                        .value_name("SHELL")
                        .help("The shell to generate the completions for")
                        .required(true)
                        .possible_values(clap_complete_command::Shell::possible_values()),
                ),
        )
}

fn main() {
    let matches = build_cli().get_matches();

    match matches.subcommand() {
        Some(("completions", sub_matches)) => {
            // e.g. `$ cli completions bash`
            if let Ok(shell) = sub_matches.value_of_t::<clap_complete_command::Shell>("shell") {
                let mut command = build_cli();
                shell.generate(&mut command, &mut std::io::stdout());
            }
        }
        _ => {
            unreachable!("Exhausted list of subcommands and `subcommand_required` prevents `None`")
        }
    }
}

Supported shells

The supported shells can be seen in clap_complete_command::Shell.

Dependencies

~2MB
~33K SLoC