Repository navigation
feat(lib): add a shared completion subcommand to usage-rs #1624
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
c3be79e
feat(lib): add a shared completion subcommand to usage-rs
jdx 446abc8
fix(lib): report completion output write failures
jdx 81953c1
fix(lib): require --install for --force and accept nushell and pwsh
jdx 4c9513f
test(lib): run the completion install test on Unix only
jdx File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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, | ||
| [ | ||
| ("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); | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.