generated zsh completion fails when `source <()`'d
drahnr opened this issue · 2 comments
Please complete the following tasks
- I have searched the discussions
- I have searched the open and rejected issues
Rust Version
rustc 1.58.1 (db9d1b20b 2022-01-20)
Clap Version
3.1.2
Minimal reproducible code
use clap::{AppSettings, Arg, Command, PossibleValue, Subcommand, ValueHint};
use clap_complete::{generate, Generator, Shell};
use std::{io, collections::{HashSet, HashMap}};
fn build_cli() -> Command<'static> {
Command::new(env!("CARGO_PKG_NAME"))
.subcommand_required(true)
.subcommand(
Command::new("foo")
.arg(
Arg::new("foo")
.long("foo")
.help("foos for real")
.possible_value(PossibleValue::new("7"))
.possible_value(PossibleValue::new("seven"))
),
)
.subcommand(
Command::new("comp")
.arg(
Arg::new("shell")
.long("shell")
.help("shell to generate for")
.possible_values(Shell::possible_values()),
),
)
}
fn print_completions<G: Generator>(gen: G, cmd: &mut Command) {
generate(gen, cmd, cmd.get_name().to_string(), &mut io::stdout());
}
fn main() {
let app = build_cli();
let matches = app.get_matches();
match matches.subcommand() {
Some(("comp", args)) => {
if let Ok(shell) = args.value_of_t::<Shell>("shell") {
let mut cmd = build_cli();
eprintln!("Generating completion file for {}...", shell);
print_completions(dbg!(shell), &mut cmd);
return;
}
eprintln!("nope");
}
Some(("foo", _args)) => {
println!("foo");
return;
}
_ => {}
}
build_cli().print_long_help().unwrap();
}
Steps to reproduce the bug with the above code
source <(cargo run -- comp --shell zsh)
Actual Behaviour
errors out and the completion does not work with the binary afterwards
error:
# source <(cargo run -- comp --shell zsh)
Finished dev [unoptimized + debuginfo] target(s) in 0.01s
Running `target/debug/clap-completion-zoink comp --shell zsh`
Generating completion file for zsh...
[src/main.rs:42] shell = Zsh
_arguments:comparguments:325: can only be called from completion function
Expected Behaviour
should source the completion and from thereon complete the execution
Additional Context
An almost minimal, reproducible example can be checked out at https://github.com/drahnr/clap-completion-zoink
Encountered in the wild on https://github.com/soywod/himalaya and reported as volta-cli/volta#496
Debug Output
No response
did you find a way to avoid the issue?
The generated file is meant to be written to a file, assuming the above project is foo
, _foo
would be the correct file name which has to reside in $fpath
.
There also seems to be an artifact when writing to a file via foo comp --shell zsh > _foo
:
<snip>
_cargo-spellcheck "$@"
which doesn't seem to be an ordinary linebreak when openeing an editor 🤷
Quick fix:
Delete the comment #compinit foo
marker at the top and the last line _foo
and it then should load fine, unless you hit #3022