| 1 |
//! [`COMPLETE=$SHELL <bin>`][CompleteEnv] completion integration |
| 2 |
//! |
| 3 |
//! See [`CompleteEnv`]: |
| 4 |
//! ```rust |
| 5 |
//! # use clap_complete::CompleteEnv; |
| 6 |
//! fn cli() -> clap::Command { |
| 7 |
//! // ... |
| 8 |
//! # clap::Command::new("empty") |
| 9 |
//! } |
| 10 |
//! |
| 11 |
//! fn main() { |
| 12 |
//! CompleteEnv::with_factory(cli) |
| 13 |
//! .complete(); |
| 14 |
//! |
| 15 |
//! // ... rest of application logic |
| 16 |
//! } |
| 17 |
//! ``` |
| 18 |
//! |
| 19 |
//! To customize completions, see |
| 20 |
//! - [`ValueHint`][crate::ValueHint] |
| 21 |
//! - [`ValueEnum`][clap::ValueEnum] |
| 22 |
//! - [`ArgValueCandidates`][crate::ArgValueCandidates] |
| 23 |
//! - [`ArgValueCompleter`][crate::ArgValueCompleter] |
| 24 |
//! |
| 25 |
//! To source your completions: |
| 26 |
//! |
| 27 |
//! <div class="warning"> |
| 28 |
//! |
| 29 |
//! **WARNING:** We recommend re-sourcing your completions on upgrade. |
| 30 |
//! These completions work by generating shell code that calls into `your_program` while completing. |
| 31 |
//! That interface is unstable and a mismatch between the shell code and `your_program` may result |
| 32 |
//! in either invalid completions or no completions being generated. |
| 33 |
//! For this reason, we recommend generating the shell code anew on shell startup so that it is |
| 34 |
//! "self-correcting" on shell launch, rather than writing the generated completions to a file. |
| 35 |
//! |
| 36 |
//! </div> |
| 37 |
//! |
| 38 |
//! **Bash** |
| 39 |
//! ```bash |
| 40 |
//! echo "source <(COMPLETE=bash your_program)" >> ~/.bashrc |
| 41 |
//! ``` |
| 42 |
//! |
| 43 |
//! **Elvish** |
| 44 |
//! ```elvish |
| 45 |
//! echo "eval (E:COMPLETE=elvish your_program | slurp)" >> ~/.elvish/rc.elv |
| 46 |
//! ``` |
| 47 |
//! |
| 48 |
//! **Fish** |
| 49 |
//! ```fish |
| 50 |
//! echo "COMPLETE=fish your_program | source" >> ~/.config/fish/config.fish |
| 51 |
//! ``` |
| 52 |
//! |
| 53 |
//! **Powershell** |
| 54 |
//! ```powershell |
| 55 |
//! echo '$env:COMPLETE = "powershell"; your_program | Out-String | Invoke-Expression; Remove-Item Env:\COMPLETE' >> $PROFILE |
| 56 |
//! ``` |
| 57 |
//! Note that to execute scripts in PowerShell on Windows, including [`$PROFILE`][$Profile], |
| 58 |
//! the [execution policy][ExecutionPolicies] needs to be set to `RemoteSigned` at minimum. |
| 59 |
//! |
| 60 |
//! [$Profile]: https://learn.microsoft.com/en-us/powershell/scripting/learn/shell/creating-profiles |
| 61 |
//! [ExecutionPolicies]: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies |
| 62 |
//! |
| 63 |
//! **Zsh** |
| 64 |
//! ```zsh |
| 65 |
//! echo "source <(COMPLETE=zsh your_program)" >> ~/.zshrc |
| 66 |
//! ``` |
| 67 |
//! |
| 68 |
//! To disable completions, you can set `COMPLETE=` or `COMPLETE=0` |
| 69 |
|
| 70 |
mod shells; |
| 71 |
|
| 72 |
use std::ffi::OsString; |
| 73 |
use std::io::Write as _; |
| 74 |
|
| 75 |
pub use shells::*; |
| 76 |
|
| 77 |
/// Environment-activated completions for your CLI |
| 78 |
/// |
| 79 |
/// Benefits over a CLI completion argument or subcommand |
| 80 |
/// - Performance: we don't need to generate [`clap::Command`] twice or parse arguments |
| 81 |
/// - Flexibility: there is no concern over it interfering with other CLI logic |
| 82 |
/// |
| 83 |
/// **Warning:** `stdout` should not be written to before [`CompleteEnv::complete`] has had a |
| 84 |
/// chance to run. |
| 85 |
/// |
| 86 |
/// # Examples |
| 87 |
/// |
| 88 |
/// ```rust |
| 89 |
/// # use clap_complete::CompleteEnv; |
| 90 |
/// fn cli() -> clap::Command { |
| 91 |
/// // ... |
| 92 |
/// # clap::Command::new("empty") |
| 93 |
/// } |
| 94 |
/// |
| 95 |
/// fn main() { |
| 96 |
/// CompleteEnv::with_factory(cli) |
| 97 |
/// .complete() |
| 98 |
/// |
| 99 |
/// // ... rest of application logic |
| 100 |
/// } |
| 101 |
/// ``` |
| 102 |
pub struct CompleteEnv<'s, F> { |
| 103 |
factory: F, |
| 104 |
var: &'static str, |
| 105 |
bin: Option<String>, |
| 106 |
completer: Option<String>, |
| 107 |
shells: Shells<'s>, |
| 108 |
} |
| 109 |
|
| 110 |
impl<'s, F: Fn() -> clap::Command> CompleteEnv<'s, F> { |
| 111 |
/// Complete a [`clap::Command`] |
| 112 |
/// |
| 113 |
/// # Example |
| 114 |
/// |
| 115 |
/// Builder: |
| 116 |
/// ```rust |
| 117 |
/// # use clap_complete::CompleteEnv; |
| 118 |
/// fn cli() -> clap::Command { |
| 119 |
/// // ... |
| 120 |
/// # clap::Command::new("empty") |
| 121 |
/// } |
| 122 |
/// |
| 123 |
/// fn main() { |
| 124 |
/// CompleteEnv::with_factory(cli) |
| 125 |
/// .complete() |
| 126 |
/// |
| 127 |
/// // ... rest of application logic |
| 128 |
/// } |
| 129 |
/// ``` |
| 130 |
/// |
| 131 |
/// Derive: |
| 132 |
/// ``` |
| 133 |
/// # use clap::Parser; |
| 134 |
/// # use clap_complete::CompleteEnv; |
| 135 |
/// use clap::CommandFactory as _; |
| 136 |
/// |
| 137 |
/// #[derive(Debug, Parser)] |
| 138 |
/// struct Cli { |
| 139 |
/// custom: Option<String>, |
| 140 |
/// } |
| 141 |
/// |
| 142 |
/// fn main() { |
| 143 |
/// CompleteEnv::with_factory(|| Cli::command()) |
| 144 |
/// .complete() |
| 145 |
/// |
| 146 |
/// // ... rest of application logic |
| 147 |
/// } |
| 148 |
/// ``` |
| 149 |
pub fn with_factory(factory: F) -> Self { |
| 150 |
Self { |
| 151 |
factory, |
| 152 |
var: "COMPLETE", |
| 153 |
bin: None, |
| 154 |
completer: None, |
| 155 |
shells: Shells::builtins(), |
| 156 |
} |
| 157 |
} |
| 158 |
|
| 159 |
/// Override the environment variable used for enabling completions |
| 160 |
pub fn var(mut self, var: &'static str) -> Self { |
| 161 |
self.var = var; |
| 162 |
self |
| 163 |
} |
| 164 |
|
| 165 |
/// Override the name of the binary to complete |
| 166 |
/// |
| 167 |
/// Default: `Command::get_bin_name` |
| 168 |
pub fn bin(mut self, bin: impl Into<String>) -> Self { |
| 169 |
self.bin = Some(bin.into()); |
| 170 |
self |
| 171 |
} |
| 172 |
|
| 173 |
/// Override the binary to call to get completions |
| 174 |
/// |
| 175 |
/// Default: `args_os()[0]` |
| 176 |
pub fn completer(mut self, completer: impl Into<String>) -> Self { |
| 177 |
self.completer = Some(completer.into()); |
| 178 |
self |
| 179 |
} |
| 180 |
|
| 181 |
/// Override the shells supported for completions |
| 182 |
pub fn shells(mut self, shells: Shells<'s>) -> Self { |
| 183 |
self.shells = shells; |
| 184 |
self |
| 185 |
} |
| 186 |
} |
| 187 |
|
| 188 |
impl<'s, F: Fn() -> clap::Command> CompleteEnv<'s, F> { |
| 189 |
/// Process the completion request and exit |
| 190 |
/// |
| 191 |
/// **Warning:** `stdout` should not be written to before this has had a |
| 192 |
/// chance to run. |
| 193 |
pub fn complete(self) { |
| 194 |
let args = std::env::args_os(); |
| 195 |
let current_dir = std::env::current_dir().ok(); |
| 196 |
if self |
| 197 |
.try_complete(args, current_dir.as_deref()) |
| 198 |
.unwrap_or_else(|e| e.exit()) |
| 199 |
{ |
| 200 |
std::process::exit(0) |
| 201 |
} |
| 202 |
} |
| 203 |
|
| 204 |
/// Process the completion request |
| 205 |
/// |
| 206 |
/// **Warning:** `stdout` should not be written to before or after this has run. |
| 207 |
/// |
| 208 |
/// Returns `true` if a command was completed and `false` if this is a regular run of your |
| 209 |
/// application |
| 210 |
pub fn try_complete( |
| 211 |
self, |
| 212 |
args: impl IntoIterator<Item = impl Into<OsString>>, |
| 213 |
current_dir: Option<&std::path::Path>, |
| 214 |
) -> clap::error::Result<bool> { |
| 215 |
self.try_complete_(args.into_iter().map(|a| a.into()).collect(), current_dir) |
| 216 |
} |
| 217 |
|
| 218 |
fn try_complete_( |
| 219 |
self, |
| 220 |
mut args: Vec<OsString>, |
| 221 |
current_dir: Option<&std::path::Path>, |
| 222 |
) -> clap::error::Result<bool> { |
| 223 |
let Some(name) = std::env::var_os(self.var) else { |
| 224 |
return Ok(false); |
| 225 |
}; |
| 226 |
if name.is_empty() || name == "0" { |
| 227 |
return Ok(false); |
| 228 |
} |
| 229 |
|
| 230 |
// Ensure any child processes called for custom completers don't activate their own |
| 231 |
// completion logic. |
| 232 |
std::env::remove_var(self.var); |
| 233 |
|
| 234 |
let shell = self.shell(std::path::Path::new(&name))?; |
| 235 |
|
| 236 |
let mut cmd = (self.factory)(); |
| 237 |
cmd.build(); |
| 238 |
|
| 239 |
let completer = args.remove(0); |
| 240 |
let escape_index = args |
| 241 |
.iter() |
| 242 |
.position(|a| *a == "--") |
| 243 |
.map(|i| i + 1) |
| 244 |
.unwrap_or(args.len()); |
| 245 |
args.drain(0..escape_index); |
| 246 |
if args.is_empty() { |
| 247 |
let mut buf = Vec::new(); |
| 248 |
self.write_registration(&cmd, current_dir, shell, completer, &mut buf)?; |
| 249 |
std::io::stdout().write_all(&buf)?; |
| 250 |
} else { |
| 251 |
let mut buf = Vec::new(); |
| 252 |
shell.write_complete(&mut cmd, args, current_dir, &mut buf)?; |
| 253 |
std::io::stdout().write_all(&buf)?; |
| 254 |
} |
| 255 |
|
| 256 |
Ok(true) |
| 257 |
} |
| 258 |
|
| 259 |
fn shell(&self, name: &std::path::Path) -> Result<&dyn EnvCompleter, std::io::Error> { |
| 260 |
// Strip off the parent dir in case `$SHELL` was used |
| 261 |
let name = name.file_stem().unwrap_or(name.as_os_str()); |
| 262 |
// lossy won't match but this will delegate to unknown |
| 263 |
// error |
| 264 |
let name = name.to_string_lossy(); |
| 265 |
|
| 266 |
let shell = self.shells.completer(&name).ok_or_else(|| { |
| 267 |
let shells = |
| 268 |
self.shells |
| 269 |
.names() |
| 270 |
.enumerate() |
| 271 |
.fold(String::new(), |mut seed, (i, name)| { |
| 272 |
use std::fmt::Write as _; |
| 273 |
let prefix = if i == 0 { "" } else { ", " }; |
| 274 |
let _ = write!(&mut seed, "{prefix}`{name}`"); |
| 275 |
seed |
| 276 |
}); |
| 277 |
std::io::Error::new( |
| 278 |
std::io::ErrorKind::Other, |
| 279 |
format!("unknown shell `{name}`, expected one of {shells}"), |
| 280 |
) |
| 281 |
})?; |
| 282 |
Ok(shell) |
| 283 |
} |
| 284 |
|
| 285 |
fn write_registration( |
| 286 |
&self, |
| 287 |
cmd: &clap::Command, |
| 288 |
current_dir: Option<&std::path::Path>, |
| 289 |
shell: &dyn EnvCompleter, |
| 290 |
completer: OsString, |
| 291 |
buf: &mut dyn std::io::Write, |
| 292 |
) -> Result<(), std::io::Error> { |
| 293 |
let name = cmd.get_name(); |
| 294 |
let bin = self |
| 295 |
.bin |
| 296 |
.as_deref() |
| 297 |
.or_else(|| cmd.get_bin_name()) |
| 298 |
.unwrap_or_else(|| cmd.get_name()); |
| 299 |
let completer = if let Some(completer) = self.completer.as_deref() { |
| 300 |
completer.to_owned() |
| 301 |
} else { |
| 302 |
let mut completer = std::path::PathBuf::from(completer); |
| 303 |
if let Some(current_dir) = current_dir { |
| 304 |
if 1 < completer.components().count() { |
| 305 |
completer = current_dir.join(completer); |
| 306 |
} |
| 307 |
} |
| 308 |
completer.to_string_lossy().into_owned() |
| 309 |
}; |
| 310 |
|
| 311 |
shell.write_registration(self.var, name, bin, &completer, buf)?; |
| 312 |
|
| 313 |
Ok(()) |
| 314 |
} |
| 315 |
} |
| 316 |
|
| 317 |
/// Collection of shell-specific completers |
| 318 |
pub struct Shells<'s>(pub &'s [&'s dyn EnvCompleter]); |
| 319 |
|
| 320 |
impl<'s> Shells<'s> { |
| 321 |
/// Select all of the built-in shells |
| 322 |
pub const fn builtins() -> Self { |
| 323 |
Self(&[&Bash, &Elvish, &Fish, &Powershell, &Zsh]) |
| 324 |
} |
| 325 |
|
| 326 |
/// Find the specified [`EnvCompleter`] |
| 327 |
pub fn completer(&self, name: &str) -> Option<&dyn EnvCompleter> { |
| 328 |
self.0.iter().copied().find(|c| c.is(name)) |
| 329 |
} |
| 330 |
|
| 331 |
/// Collect all [`EnvCompleter::name`]s |
| 332 |
pub fn names(&self) -> impl Iterator<Item = &'static str> + 's { |
| 333 |
self.0.iter().map(|c| c.name()) |
| 334 |
} |
| 335 |
|
| 336 |
/// Iterate over [`EnvCompleter`]s |
| 337 |
pub fn iter(&self) -> impl Iterator<Item = &dyn EnvCompleter> { |
| 338 |
self.0.iter().copied() |
| 339 |
} |
| 340 |
} |
| 341 |
|
| 342 |
/// Shell-integration for completions |
| 343 |
/// |
| 344 |
/// This will generally be called by [`CompleteEnv`]. |
| 345 |
/// |
| 346 |
/// This handles adapting between the shell and [`completer`][crate::engine::complete()]. |
| 347 |
/// A `EnvCompleter` can choose how much of that lives within the registration script or |
| 348 |
/// lives in [`EnvCompleter::write_complete`]. |
| 349 |
pub trait EnvCompleter { |
| 350 |
/// Canonical name for this shell |
| 351 |
/// |
| 352 |
/// **Post-conditions:** |
| 353 |
/// ```rust,ignore |
| 354 |
/// assert!(completer.is(completer.name())); |
| 355 |
/// ``` |
| 356 |
fn name(&self) -> &'static str; |
| 357 |
/// Whether the name matches this shell |
| 358 |
/// |
| 359 |
/// This should match [`EnvCompleter::name`] and any alternative names, particularly used by |
| 360 |
/// `$SHELL`. |
| 361 |
fn is(&self, name: &str) -> bool; |
| 362 |
/// Register for completions |
| 363 |
/// |
| 364 |
/// Write the `buf` the logic needed for calling into `<VAR>=<shell> <cmd> --`, passing needed |
| 365 |
/// arguments to [`EnvCompleter::write_complete`] through the environment. |
| 366 |
/// |
| 367 |
/// - `var`: see [`CompleteEnv::var`] |
| 368 |
/// - `name`: an identifier to use in the script |
| 369 |
/// - `bin`: see [`CompleteEnv::bin`] |
| 370 |
/// - `completer`: see [`CompleteEnv::completer`] |
| 371 |
/// |
| 372 |
/// <div class="warning"> |
| 373 |
/// |
| 374 |
/// **WARNING:** There are no stability guarantees between the call to |
| 375 |
/// [`EnvCompleter::write_complete`] that this generates and actually calling [`EnvCompleter::write_complete`]. |
| 376 |
/// Caching the results of this call may result in invalid or no completions to be generated. |
| 377 |
/// |
| 378 |
/// </div> |
| 379 |
fn write_registration( |
| 380 |
&self, |
| 381 |
var: &str, |
| 382 |
name: &str, |
| 383 |
bin: &str, |
| 384 |
completer: &str, |
| 385 |
buf: &mut dyn std::io::Write, |
| 386 |
) -> Result<(), std::io::Error>; |
| 387 |
/// Complete the given command |
| 388 |
/// |
| 389 |
/// Adapt information from arguments and [`EnvCompleter::write_registration`]-defined env |
| 390 |
/// variables to what is needed for [`completer`][crate::engine::complete()]. |
| 391 |
/// |
| 392 |
/// Write out the [`CompletionCandidate`][crate::engine::CompletionCandidate]s in a way the shell will understand. |
| 393 |
fn write_complete( |
| 394 |
&self, |
| 395 |
cmd: &mut clap::Command, |
| 396 |
args: Vec<OsString>, |
| 397 |
current_dir: Option<&std::path::Path>, |
| 398 |
buf: &mut dyn std::io::Write, |
| 399 |
) -> Result<(), std::io::Error>; |
| 400 |
} |