Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 14 additions & 8 deletions docs/rust/completions.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,21 +45,27 @@ The installed script calls your binary back at completion time with a hidden
any parsing, so it never appears in your grammar, help, or spec. `parse()` intercepts it
automatically; with `parse_from`, call `completion_request` first and print whatever it returns.

A typical way to expose the scripts:
Mount the ready-made `Completion` command to expose the scripts. Every tool that does gets
the same `tool completion <shell>` and `tool completion <shell> --install`:

```rust
#[derive(Args)]
struct Completion {
/// Which shell to generate for
shell: String,
use usage_rs::completion::Completion;

#[derive(Subcommands)]
enum Commands {
/// Generate shell completions
Completion(Completion),
}

// in your run function:
let shell = usage_rs::complete::Shell::from_name(&completion.shell)
.expect("a supported shell name");
print!("{}", Ex::completion_script(shell));
completion.run("ex", &mut std::io::stdout())?;
```

`ex completion fish` prints the script, so `ex completion fish | source` always matches the
installed version. `ex completion fish --install` writes it where fish looks for it, and
`--force` replaces a file that was not generated by usage. The scripts hold no spec and need no
`usage` binary: they ask the installed tool for candidates on every Tab.

Shell aliases are explicit because each shell stores and expands them differently. To complete
`m` exactly like `mise`, install `Ex::completion_script_for_alias("m", shell)`. The generated
script registers `m`, but its callback executes `mise`; it does not depend on alias expansion in
Expand Down
265 changes: 265 additions & 0 deletions usage-rs/src/completion.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,265 @@
//! A ready-made `completion` subcommand.
//!
//! Every CLI that ships completions needs the same command: name a shell, print the script or
//! write it where the shell looks. Mount [`Completion`] instead of writing it again, and every
//! tool built on usage answers `tool completion <shell>` and `tool completion <shell> --install`
//! the same way.
//!
//! ```
//! use usage_rs::{Cli, Subcommands};
//! use usage_rs::completion::Completion;
//!
//! #[derive(Cli)]
//! #[usage(bin = "ex", completion)]
//! struct Ex {
//! #[usage(subcommand)]
//! command: Option<Commands>,
//! }
//!
//! #[derive(Subcommands)]
//! enum Commands {
//! /// Generate shell completions
//! Completion(Completion),
//! }
//!
//! let argv = ["completion", "fish"].map(std::ffi::OsStr::new);
//! let ex = Ex::parse_from(&argv).unwrap();
//! let Some(Commands::Completion(completion)) = ex.command else { unreachable!() };
//! let script = completion.script("ex");
//! assert!(script.contains("__complete_word__"));
//! ```
//!
//! The script it prints is the short one from [`crate::script`]: it holds no spec and needs no
//! `usage` binary, and it asks the installed tool for candidates on every Tab, so it cannot go
//! stale when the tool is upgraded.

use std::io::Write;

use usage_argv::complete::Shell;
use usage_argv::install::{self, Env, OnForeign, Wrote};

use crate::Args;

/// Arguments of a `completion` subcommand.
#[derive(Debug, Clone, Args)]
pub struct Completion {
/// Shell to generate completions for
#[usage(choices("bash", "elvish", "fish", "nu", "nushell", "powershell", "pwsh", "zsh"))]
pub shell: String,
/// Write the script where the shell looks for it instead of printing it
#[usage(long)]
pub install: bool,
/// With --install, replace a file that was not generated by usage
#[usage(long, requires = "--install")]
pub force: bool,
}

impl Completion {
/// The shell named on the command line.
///
/// # Panics
///
/// Never for a parsed value: parsing only accepts the names [`Shell::from_name`] knows.
pub fn shell(&self) -> Shell {
Shell::from_name(&self.shell).expect("parsing only accepts a supported shell")
}

/// The completion script for `bin`.
pub fn script(&self, bin: &str) -> String {
usage_argv::script::script(bin, self.shell())
}

/// Print the script, or with `--install` write it and say where it went.
///
/// `bin` is the name of the executable the script should call back, normally the CLI's own
/// `bin`. Nothing is written to a startup file; when a shell needs a line added once, it is
/// printed on `out` after the path.
pub fn run(&self, bin: &str, out: &mut impl Write) -> Result<(), Error> {
self.run_in(bin, &Env::from_process(), out)
}

/// [`Completion::run`] against a described environment instead of the process's own, which
/// is what lets a test say where an install lands without touching the real home directory.
pub fn run_in(&self, bin: &str, env: &Env, out: &mut impl Write) -> Result<(), Error> {
let shell = self.shell();
if !self.install {
return finish(out.write_all(self.script(bin).as_bytes()));
}
let on_foreign = if self.force {
OnForeign::Overwrite
} else {
OnForeign::Refuse
};
let done = install::install(bin, shell, env, on_foreign)?;
let verb = match done.wrote {
Wrote::Created => "installed",
Wrote::Updated => "updated",
Wrote::Replaced => "replaced",
_ => "already up to date:",
};
let mut report = format!("{verb} {}\n", done.plan.path.display());
if let install::Loading::Manual { line, file, why } = &done.plan.loading {
report.push_str(&format!("{why}; add this to {file}, once:\n{line}\n"));
}
if let Some(note) = done.plan.note {
report.push_str(&format!("{note}\n"));
}
finish(out.write_all(report.as_bytes()))
}
}

/// Why [`Completion::run`] failed.
#[derive(Debug)]
#[non_exhaustive]
pub enum Error {
/// The script could not be placed where the shell looks.
Install(install::Error),
/// Writing to the output failed, for example because the disk is full.
Output(std::io::Error),
}

impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Error::Install(e) => e.fmt(f),
Error::Output(e) => write!(f, "could not write the completion output: {e}"),
}
}
}

impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Error::Install(e) => Some(e),
Error::Output(e) => Some(e),
}
}
}

impl From<install::Error> for Error {
fn from(e: install::Error) -> Self {
Error::Install(e)
}
}

/// A closed pipe is the reader's decision (`ex completion zsh | head`), so it is not a failure;
/// every other write error is, and must not look like success.
fn finish(result: std::io::Result<()>) -> Result<(), Error> {
match result {
Err(e) if e.kind() != std::io::ErrorKind::BrokenPipe => Err(Error::Output(e)),
_ => Ok(()),
}
}

#[cfg(test)]
mod tests {
use super::*;

fn parse(words: &[&str]) -> Completion {
let argv: Vec<_> = words.iter().map(std::ffi::OsStr::new).collect();
crate::parse_args_from::<Completion>(&argv).unwrap()
}

#[test]
fn prints_the_script_by_default() {
let c = parse(&["zsh"]);
let mut out = Vec::new();
c.run("ex", &mut out).unwrap();
assert_eq!(String::from_utf8(out).unwrap(), c.script("ex"));
}

struct Failing(std::io::ErrorKind);

impl Write for Failing {
fn write(&mut self, _: &[u8]) -> std::io::Result<usize> {
Err(self.0.into())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}

#[test]
fn a_failed_write_is_an_error_but_a_closed_pipe_is_not() {
let c = parse(&["fish"]);
let full = c.run("ex", &mut Failing(std::io::ErrorKind::StorageFull));
assert!(matches!(full, Err(Error::Output(_))));
let closed = c.run("ex", &mut Failing(std::io::ErrorKind::BrokenPipe));
assert!(closed.is_ok());
}

#[cfg(unix)]
fn linux_env(home: &std::path::Path) -> Env {
Env::new(
install::Platform::Linux,
Comment thread
jdx marked this conversation as resolved.
Resolved
[
("HOME".to_string(), home.into()),
("XDG_CONFIG_HOME".to_string(), home.join("config").into()),
],
)
}

#[cfg(unix)]
#[test]
fn install_creates_refuses_a_foreign_file_and_force_replaces_it() {
let home = tempfile::tempdir().unwrap();
let env = linux_env(home.path());
let target = home.path().join("config/fish/completions/ex.fish");

let mut out = Vec::new();
parse(&["fish", "--install"])
.run_in("ex", &env, &mut out)
.unwrap();
assert!(String::from_utf8(out).unwrap().starts_with("installed "));
assert_eq!(
std::fs::read_to_string(&target).unwrap(),
parse(&["fish"]).script("ex")
);

std::fs::write(&target, "# written by hand\n").unwrap();
let refused = parse(&["fish", "--install"]).run_in("ex", &env, &mut Vec::new());
assert!(matches!(
refused,
Err(Error::Install(install::Error::Foreign { .. }))
));
assert_eq!(
std::fs::read_to_string(&target).unwrap(),
"# written by hand\n"
);

let mut out = Vec::new();
parse(&["fish", "--install", "--force"])
.run_in("ex", &env, &mut out)
.unwrap();
assert!(String::from_utf8(out).unwrap().starts_with("replaced "));
assert_eq!(
std::fs::read_to_string(&target).unwrap(),
parse(&["fish"]).script("ex")
);
}

#[test]
fn force_without_install_is_an_error() {
let argv = ["fish", "--force"].map(std::ffi::OsStr::new);
assert!(crate::parse_args_from::<Completion>(&argv).is_err());
}

#[test]
fn shell_aliases_are_accepted() {
assert_eq!(parse(&["nushell"]).shell(), Shell::Nu);
assert_eq!(parse(&["pwsh"]).shell(), Shell::PowerShell);
}

#[test]
fn rejects_an_unknown_shell() {
let argv = [std::ffi::OsStr::new("tcsh")];
assert!(crate::parse_args_from::<Completion>(&argv).is_err());
}

#[test]
fn every_choice_is_a_shell() {
for name in ["bash", "elvish", "fish", "nu", "powershell", "zsh"] {
assert_eq!(parse(&[name]).shell().as_str(), name);
}
}
}
2 changes: 2 additions & 0 deletions usage-rs/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,8 @@ pub use usage_derive::{ArgGroup, Args, Cli, Subcommands, ValueEnum};
pub use usage_test as test;
#[cfg(feature = "validation")]
pub use usage_validation as validation;
#[cfg(feature = "completions")]
pub mod completion;
#[cfg(feature = "response-files")]
pub mod response;
#[cfg(feature = "config")]
Expand Down
Loading