#shell-completion #clap #reduce-boilerplate #command #cli-command #command-line

clap_complete_command

Reduces boilerplate for adding a shell completion command to Clap

12 unstable releases (4 breaking)

0.5.1 Mar 10, 2023
0.5.0 Mar 10, 2023
0.4.0 Oct 4, 2022
0.3.4 May 29, 2022
0.1.0 Apr 5, 2022

#62 in Command-line interface

Download history 5250/week @ 2023-11-21 7053/week @ 2023-11-28 6598/week @ 2023-12-05 6735/week @ 2023-12-12 5976/week @ 2023-12-19 6236/week @ 2023-12-26 7414/week @ 2024-01-02 8674/week @ 2024-01-09 8616/week @ 2024-01-16 8027/week @ 2024-01-23 9272/week @ 2024-01-30 9226/week @ 2024-02-06 8693/week @ 2024-02-13 13740/week @ 2024-02-20 19330/week @ 2024-02-27 23462/week @ 2024-03-05

66,523 downloads per month
Used in 16 crates

MIT license

17KB
224 lines

clap-complete-command

crates.io

Reduces boilerplate for adding a shell completion command to Clap

Compatible clap versions

clap version clap_complete_command version
v3 v0.1, v0.2, v0.3
v4 v0.4, v0.5

Examples

Derive

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

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

#[derive(Subcommand)]
enum Commands {
    /// Generate shell completions
    Completions {
        /// The shell to generate the completions for
        #[arg(value_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 {
    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)
                        .value_parser(
                            clap::builder::EnumValueParser::<clap_complete_command::Shell>::new(),
                        ),
                ),
        )
}

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

    match matches.subcommand() {
        Some(("completions", sub_matches)) => {
            // e.g. `$ cli completions bash`
            if let Some(shell) = sub_matches.get_one::<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

~1–1.5MB
~27K SLoC