diff --git a/Cargo.lock b/Cargo.lock index dde889e..a086879 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -311,6 +311,15 @@ dependencies = [ "strsim", ] +[[package]] +name = "clap_complete" +version = "4.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "037e2a1a92236d0aff7e845093f64661d6df4c02c9fcc61a60e9e1d736fa392f" +dependencies = [ + "clap", +] + [[package]] name = "clap_derive" version = "4.6.7" @@ -1428,6 +1437,7 @@ dependencies = [ "apple-native-keyring-store", "axum", "clap", + "clap_complete", "dbus-secret-service-keyring-store", "flate2", "jsonschema", diff --git a/Cargo.toml b/Cargo.toml index 2f96ae5..f2a2ada 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,6 +19,7 @@ path = "src/main.rs" [dependencies] anyhow = "1" clap = { version = "4", features = ["derive", "env"] } +clap_complete = "4" flate2 = "1" sha2 = "0.10" tar = "0.4" diff --git a/README.md b/README.md index 40c2e74..aa1e6a2 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,8 @@ This repository is the published distribution of the Proofline CLI. `openapi.pub On Linux and macOS, install the CLI with `curl -fsSL https://proofline.sh/cli | sh`, then run `proofline login`. Run `proofline setup` to open the browser organization selector. Pass `--organization NAME` to open that GitHub organization's installation page, or `--print` to only print its address. Cloud trust and connection changes still require a signed-in administrator browser. +`proofline completions SHELL` prints a completion script for `zsh`, `bash`, `fish`, `powershell`, or `elvish` without signing in or making a network call. For example, add `source <(proofline completions zsh)` to `~/.zshrc`. + ### Windows installation Official releases include `proofline-x86_64-pc-windows-msvc.tar.gz` with `proofline.exe`. Download the archive and `SHA256SUMS` from the same GitHub release, and compare its SHA-256 hash using `Get-FileHash -Algorithm SHA256`. Extract the archive with `tar -xzf` and put `proofline.exe` in a directory on `PATH`. Run `proofline login` to store credentials in Windows Credential Manager. To update, close running Proofline processes and replace the executable from a verified release. The Unix shell installer and self-update command do not install Windows binaries. diff --git a/src/lib.rs b/src/lib.rs index e833683..f0adc8b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -123,6 +123,17 @@ enum Command { FixPrompt { finding_id: Uuid }, /// Export one page of analytics as CSV or NDJSON. Export(tools::ExportArgs), + /// Print a shell completion script to standard output. + /// + /// For example, add `source <(proofline completions zsh)` to `~/.zshrc`, + /// `proofline completions bash > ~/.local/share/bash-completion/completions/proofline`, + /// `proofline completions fish > ~/.config/fish/completions/proofline.fish`, or + /// `proofline completions powershell | Out-String | Invoke-Expression` to a + /// PowerShell profile. + Completions { + /// The shell to complete for. + shell: clap_complete::Shell, + }, /// Install the newest official release over this installer-managed binary. Update, #[command(name = "__update-check", hide = true)] @@ -375,6 +386,10 @@ pub async fn run(cli: Cli, token: Option) -> anyhow::Result { + completions(*shell, &mut std::io::stdout().lock())?; + return Ok(Verdict::Done); + } Command::Update => return update::install().await.map(|()| Verdict::Done), Command::UpdateCheck => { update::check().await; @@ -384,6 +399,10 @@ pub async fn run(cli: Cli, token: Option) -> anyhow::Result { + completions(shell, &mut std::io::stdout().lock())?; + Ok(Verdict::Done) + } Command::Update => update::install().await.map(|()| Verdict::Done), Command::UpdateCheck => { update::check().await; @@ -556,6 +575,26 @@ async fn connect( Ok(Api::new(http, credential.token, credential.organization_id)) } +/// Writes the completion script for `shell`. It needs no origin, token or +/// network, so it works before `proofline login`. +fn completions(shell: clap_complete::Shell, out: &mut dyn std::io::Write) -> anyhow::Result<()> { + const NAME: &str = "proofline"; + let full = ::command(); + // The static generators offer hidden subcommands too, so leave them out. + let mut command = full.get_arguments().cloned().fold( + clap::Command::new(NAME).version(env!("CARGO_PKG_VERSION")), + clap::Command::arg, + ); + command = full + .get_subcommands() + .filter(|subcommand| !subcommand.is_hide_set()) + .cloned() + .fold(command, clap::Command::subcommand); + clap_complete::generate(shell, &mut command, NAME, out); + out.flush()?; + Ok(()) +} + fn say(line: &str) { // Progress goes to standard error so standard output stays the result. let mut stderr = std::io::stderr().lock(); diff --git a/src/update.rs b/src/update.rs index 427856c..d001d62 100644 --- a/src/update.rs +++ b/src/update.rs @@ -90,7 +90,8 @@ pub fn on_invocation() { let args: Vec<_> = std::env::args_os().skip(1).collect(); if args .iter() - .any(|arg| arg == "update" || arg == "__update-check") + // A shell evaluates `completions` at every start-up; keep it offline. + .any(|arg| arg == "update" || arg == "__update-check" || arg == "completions") { return; } diff --git a/tests/completions.rs b/tests/completions.rs new file mode 100644 index 0000000..733bd04 --- /dev/null +++ b/tests/completions.rs @@ -0,0 +1,74 @@ +//! `proofline completions` prints a usable script for each supported shell +//! without a token, an origin or the network. +use std::process::{Command, Output}; + +fn completions(shell: &str) -> Output { + Command::new(env!("CARGO_BIN_EXE_proofline")) + .args(["--base-url", "invalid", "completions", shell]) + .env("PROOFLINE_NO_UPDATE_CHECK", "1") + .env_remove("PROOFLINE_TOKEN") + .env_remove("PROOFLINE_ORGANIZATION_ID") + .output() + .unwrap() +} + +#[test] +fn every_shell_gets_a_script_naming_the_visible_commands() { + for (shell, marker) in [ + ("zsh", "#compdef proofline"), + ("bash", "complete -F _proofline"), + ("fish", "complete -c proofline"), + ("powershell", "Register-ArgumentCompleter"), + ] { + let output = completions(shell); + assert!(output.status.success(), "{shell}: {output:?}"); + assert!(output.stderr.is_empty(), "{shell}: {output:?}"); + let script = String::from_utf8(output.stdout).unwrap(); + assert!(script.contains(marker), "{shell} script lacks {marker:?}"); + for visible in ["review", "findings", "login", "completions", "base-url"] { + assert!(script.contains(visible), "{shell} script lacks {visible:?}"); + } + assert!( + !script.contains("__update-check"), + "{shell} script offers a hidden command" + ); + } +} + +#[test] +fn an_unknown_shell_is_refused() { + let output = completions("tcsh"); + assert!(!output.status.success()); + assert!(output.stdout.is_empty()); + assert!(String::from_utf8(output.stderr).unwrap().contains("zsh")); +} + +#[test] +fn the_bash_script_completes_subcommands() { + let Ok(probe) = Command::new("bash").arg("--version").output() else { + return; + }; + if !probe.status.success() { + return; + } + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("proofline.bash"); + std::fs::write(&path, completions("bash").stdout).unwrap(); + let output = Command::new("bash") + .arg("-c") + .arg( + r#"source "$1" +COMP_WORDS=(proofline comp) +COMP_CWORD=1 +COMP_LINE="proofline comp" +COMP_POINT=${#COMP_LINE} +_proofline proofline comp proofline +printf '%s\n' "${COMPREPLY[@]}""#, + ) + .arg("bash") + .arg(&path) + .output() + .unwrap(); + assert!(output.status.success(), "{output:?}"); + assert_eq!(String::from_utf8(output.stdout).unwrap(), "completions\n"); +}