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