logo
pub fn generate<G, S>(gen: G, cmd: &mut Command, bin_name: S, buf: &mut dyn Write)where
    G: Generator,
    S: Into<String>,
Expand description

Generate a completions file for a specified shell at runtime.

Until cargo install can install extra files like a completion script, this may be used e.g. in a command that outputs the contents of the completion script, to be redirected into a file by the user.

Examples

Assuming a separate cli.rs like the example above, we can let users generate a completion script using a command:

// src/main.rs

mod cli;
use std::io;
use clap_complete::{generate, shells::Bash};

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

    if matches.is_present("generate-bash-completions") {
        generate(Bash, &mut cli::build_cli(), "myapp", &mut io::stdout());
    }

    // normal logic continues...
}

Usage:

$ myapp generate-bash-completions > /usr/share/bash-completion/completions/myapp.bash