caress/lib.rs
1// SPDX-License-Identifier: EUPL-1.2
2
3//! shell completions and man pages for [`pound`] commands
4//!
5//! # completions
6//!
7//! call [`handle`] first thing in `main`. a shell's completion script runs the
8//! program with `COMPLETE` set, and [`handle`] answers and exits before the
9//! program does anything else. completion runs pound's own parser over the
10//! line, so it agrees with what the program will accept, and an arg's
11//! `#[pound(complete = ...)]` completer sees every other arg already typed.
12//!
13//! ```no_run
14//! use pound::Parse;
15//!
16//! #[derive(Parse)]
17//! struct Grab {
18//! url: Vec<String>,
19//! }
20//!
21//! caress::handle(Grab::SPEC);
22//! let grab = Grab::parse();
23//! ```
24//!
25//! users register completion by sourcing the script the program prints when
26//! `COMPLETE` names a shell and no words follow.
27//!
28//! | shell | setup |
29//! |------------|--------------------------------------------------------------------------------------------------------|
30//! | bash | `source <(COMPLETE=bash grab)` |
31//! | zsh | `COMPLETE=zsh grab > ~/.zfunc/_grab`, with it in `fpath` |
32//! | fish | `COMPLETE=fish grab \| source` |
33//! | nu | `COMPLETE=nu grab \| save grab.nu`, then `source` it |
34//! | elvish | `eval (COMPLETE=elvish grab \| slurp)` |
35//! | powershell | `$env:COMPLETE='powershell'; grab \| Out-String \| Invoke-Expression`, then `Remove-Item Env:COMPLETE` |
36//!
37//! packagers can write the same scripts at build time with [`Shell::script`]
38//! and install them with the other completion files.
39//!
40//! # startup
41//!
42//! every TAB runs the program, so its startup is the completion latency.
43//! answering takes caress about 10 µs. the rest is the process itself,
44//! measured on x86-64 Linux at about 180 µs for exec and the Rust runtime,
45//! plus about 350 µs more when the binary is dynamically linked, for the
46//! loader to resolve glibc. two things keep it short.
47//!
48//! - call [`handle`] before anything else in `main`. config loading, logging
49//! setup, or a lock taken earlier lands on every TAB.
50//! - link the binary statically when completion latency matters, with
51//! `RUSTFLAGS='-C target-feature=+crt-static'` or a musl target, or
52//! `pkgsStatic` in nix. that took a full bash TAB from 0.9 ms to 0.55 ms.
53//!
54//! # man pages
55//!
56//! [`man::pages`] renders an mdoc page for the command and each subcommand.
57
58extern crate alloc;
59
60mod engine;
61pub mod man;
62mod shell;
63
64use std::{
65 env::{
66 args_os,
67 var,
68 var_os,
69 },
70 ffi::OsStr,
71 io::{
72 Write as _,
73 stderr,
74 stdout,
75 },
76 path::Path,
77 process::exit,
78};
79
80pub use engine::{
81 Completions,
82 Fallback,
83 Line,
84};
85use pound::spec::CommandSpec;
86pub use shell::{
87 Shell,
88 UnknownShell,
89};
90
91/// answer a completion request and exit, when `COMPLETE` names a shell
92///
93/// returns without doing anything when `COMPLETE` is unset, empty, or `0`,
94/// see [`Request::from_env`].
95#[expect(
96 clippy::exit,
97 reason = "completion requests must exit before application startup"
98)]
99pub fn handle(spec: &CommandSpec) {
100 let Some(request) = Request::from_env(spec) else {
101 return;
102 };
103
104 let code = match request {
105 Ok(parsed) => {
106 let answer = parsed.answer(spec);
107 i32::from(stdout().write_all(answer.as_bytes()).is_err())
108 },
109 Err(error) => {
110 let _write_result = writeln!(stderr(), "error: {error}");
111 2
112 },
113 };
114 exit(code);
115}
116
117/// what a shell asked the program for
118#[derive(Clone, Debug, PartialEq, Eq)]
119#[non_exhaustive]
120pub enum Request {
121 /// the shell's registration script, for the name the program ran as
122 Script { shell: Shell, program: String },
123 /// candidates for the word under the cursor
124 Complete { shell: Shell, line: Line },
125}
126
127impl Request {
128 /// the request `COMPLETE` and the process arguments make, or `None` when
129 /// `COMPLETE` is unset, empty, or `0`. a program run without a name is
130 /// named after `spec`.
131 #[must_use]
132 pub fn from_env(spec: &CommandSpec) -> Option<Result<Self, UnknownShell>> {
133 let shell_name = var_os("COMPLETE").filter(|value| !value.is_empty() && value != "0")?;
134 let parsed_shell = match shell_name.to_string_lossy().parse::<Shell>() {
135 Ok(parsed) => parsed,
136 Err(error) => return Some(Err(error)),
137 };
138
139 let mut arguments = args_os();
140 let program = arguments
141 .next()
142 .and_then(|arg0| program_name(&arg0))
143 .unwrap_or_else(|| spec.name.to_owned());
144 let rest = arguments.map(|arg| arg.to_string_lossy().into_owned());
145 let cursor = var("COMPLETE_INDEX")
146 .ok()
147 .and_then(|index| index.parse().ok());
148 Some(Ok(Self::from_args(parsed_shell, program, rest, cursor)))
149 }
150
151 /// the request in the arguments after the program name, a line after
152 /// `--` and the script otherwise. the word at `cursor`, or else the last,
153 /// is under the cursor.
154 #[must_use]
155 pub fn from_args(
156 shell: Shell,
157 program: String,
158 args: impl IntoIterator<Item = String>,
159 cursor: Option<usize>,
160 ) -> Self {
161 let mut arguments = args.into_iter();
162 if arguments.next().as_deref() != Some("--") {
163 return Self::Script { shell, program };
164 }
165
166 let mut words = arguments.collect::<Vec<_>>();
167 let typed = match cursor {
168 Some(at) => {
169 let typed = words.get(at).cloned().unwrap_or_default();
170 words.truncate(at);
171 typed
172 },
173 None => words.pop().unwrap_or_default(),
174 };
175 Self::Complete {
176 shell,
177 line: Line::new(words, typed),
178 }
179 }
180
181 /// what to print for the shell, completing against `spec`
182 #[must_use]
183 pub fn answer(&self, spec: &CommandSpec) -> String {
184 match self {
185 Self::Script { shell, program } => shell.script(program),
186 Self::Complete { shell, line } => shell.render(&line.complete(spec)),
187 }
188 }
189}
190
191fn program_name(arg0: &OsStr) -> Option<String> {
192 let name = Path::new(arg0).file_name()?.to_string_lossy();
193 (!name.is_empty()).then(|| name.into_owned())
194}
195
196#[cfg(test)]
197mod tests {
198 use super::*;
199
200 #[test]
201 fn words_after_dashes_are_a_line_with_the_cursor_last() {
202 let args = ["--", "open", "db"].map(String::from);
203 let request = Request::from_args(Shell::Fish, "vault".to_owned(), args, None);
204 let line = Line::new(vec!["open".to_owned()], "db".to_owned());
205 assert_eq!(request, Request::Complete {
206 shell: Shell::Fish,
207 line,
208 });
209 let script = Request::from_args(Shell::Fish, "vault".to_owned(), [], None);
210 assert!(matches!(script, Request::Script { .. }));
211 }
212}