|
can we have |
Replies: 2 comments 1 reply
|
Yes, A minimal implementation: # Cargo.toml — add under [features]/[dependencies]
clap_complete = { version = "4", optional = true }
[features]
cli = ["dep:clap", "dep:colored", "dep:env_logger", "dep:num-format", "dep:clap_complete"]// In the binary that builds the clap Command (src/bin/tokei.rs or similar)
use clap_complete::{generate, Shell};
fn print_completions(shell: Shell) {
let mut cmd = tokei::cli::build_cli(); // your clap::Command
let bin_name = "tokei";
generate(shell, &mut cmd, bin_name, &mut std::io::stdout());
}Add a hidden CLI flag like tokei --generate-completion bash > /etc/bash_completion.d/tokei
tokei --generate-completion fish > ~/.config/fish/completions/tokei.fish
tokei --generate-completion zsh > "${fpath[1]}/_tokei"Two practical notes:
Happy to send a PR if useful. |
|
Self-correction after re-reading the source. I went back to verify the symbol names I used and my code snippet is wrong on one detail — there's no The actual implementation needs a small refactor first: extract the // src/cli.rs
pub fn cli_command() -> clap::Command {
clap::Command::new("tokei")
.version(crate_version())
.author("Erin P. <xampprocky@gmail.com> + Contributors")
.styles(clap_cargo::style::CLAP_STYLING)
.about(concat!(crate_description!(), "
", "Support this project on GitHub Sponsors: https://github.com/sponsors/XAMPPRocky"))
.arg(/* columns */)
// ... all existing args
.arg(
Arg::new("generate-completion")
.long("generate-completion")
.value_parser(value_parser!(Shell))
.value_name("SHELL")
.hide(true),
)
}
impl Cli {
pub fn from_args() -> Self {
let mut cmd = cli_command();
let matches = cmd.clone().get_matches();
if let Ok(shell) = matches.get_one::<Shell>("generate-completion") {
let bin = std::env::args().next().unwrap_or_else(|| "tokei".into());
clap_complete::generate(*shell, &mut cmd, bin, &mut std::io::stdout());
std::process::exit(0);
}
// ...rest unchanged
}
}The |
Self-correction after re-reading the source. I went back to verify the symbol names I used and my code snippet is wrong on one detail — there's no
tokei::cli::build_cli().src/cli.rsbuilds the clapCommandinline insideCli::from_args()and discards it after parsing intoArgMatches, so it's not exposed publicly.The actual implementation needs a small refactor first: extract the
Commandbuilder into apub fn cli_command() -> clap::Commandinsrc/cli.rs, call it fromCli::from_args(), and call it again from the new completion flag. Concrete shape: