Reduces boilerplate for adding a shell completion command to Clap
| clap
version | clap-complete-command
version |
| -------------- | ------------------------------- |
| v3 | v0.1, v0.2, v0.3 |
| v4 | v0.4 |
```rust use clap::{CommandFactory, Parser, Subcommand};
struct Cli { #[command(subcommand)] command: Commands, }
enum Commands { /// Generate shell completions Completions { /// The shell to generate the completions for #[arg(valueenum)] shell: clapcomplete_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());
}
}
} ```
```rust use clap::{Arg, Command};
fn buildcli() -> Command {
Command::new(env!("CARGOPKGNAME"))
.subcommandrequired(true)
.subcommand(
Command::new("completions")
.about("Generate shell completions")
.arg(
Arg::new("shell")
.valuename("SHELL")
.help("The shell to generate the completions for")
.required(true)
.valueparser(
clap::builder::EnumValueParser::
fn main() { let matches = buildcli().getmatches();
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`")
}
}
} ```
The supported shells can be seen in clap_complete_command::Shell
.