feat(complete): Allow user to override bin/completer

This commit is contained in:
Ed Page 2024-09-17 15:43:53 -05:00
parent 21c9892efe
commit b2c8e445aa

View file

@ -91,6 +91,8 @@ pub use shells::*;
pub struct CompleteEnv<'s, F> {
factory: F,
var: &'static str,
bin: Option<String>,
completer: Option<String>,
shells: Shells<'s>,
}
@ -137,6 +139,8 @@ impl<'s, F: FnOnce() -> clap::Command> CompleteEnv<'s, F> {
Self {
factory,
var: "COMPLETE",
bin: None,
completer: None,
shells: Shells::builtins(),
}
}
@ -147,6 +151,22 @@ impl<'s, F: FnOnce() -> clap::Command> CompleteEnv<'s, F> {
self
}
/// Override the name of the binary to complete
///
/// Default: `Command::get_bin_name`
pub fn bin(mut self, bin: impl Into<String>) -> Self {
self.bin = Some(bin.into());
self
}
/// Override the binary to call to get completions
///
/// Default: `Command::get_bin_name`
pub fn completer(mut self, completer: impl Into<String>) -> Self {
self.completer = Some(completer.into());
self
}
/// Override the shells supported for completions
pub fn shells(mut self, shells: Shells<'s>) -> Self {
self.shells = shells;
@ -230,10 +250,19 @@ impl<'s, F: FnOnce() -> clap::Command> CompleteEnv<'s, F> {
args.drain(0..escape_index);
if args.is_empty() {
let name = cmd.get_name();
let bin = cmd.get_bin_name().unwrap_or_else(|| cmd.get_name());
let bin = self
.bin
.as_deref()
.or_else(|| cmd.get_bin_name())
.unwrap_or_else(|| cmd.get_name());
let completer = self
.completer
.as_deref()
.or_else(|| cmd.get_bin_name())
.unwrap_or_else(|| cmd.get_name());
let mut buf = Vec::new();
shell.write_registration(self.var, name, bin, bin, &mut buf)?;
shell.write_registration(self.var, name, bin, completer, &mut buf)?;
std::io::stdout().write_all(&buf)?;
} else {
let mut buf = Vec::new();
@ -297,8 +326,8 @@ pub trait EnvCompleter {
///
/// - `var`: see [`CompleteEnv::var`]
/// - `name`: an identifier to use in the script
/// - `bin`: the binary being completed
/// - `completer`: the command to run to generate completions
/// - `bin`: see [`CompleteEnv::bin`]
/// - `completer`: see [`CompleteEnv::completer`]
///
/// **WARNING:** There are no stability guarantees between the call to
/// [`EnvCompleter::write_complete`] that this generates and actually calling [`EnvCompleter::write_complete`].