Skip to main content

argenv_resolve/generate/
mod.rs

1//! Everything a program ships *about* its invocation, derived from the declaration.
2//!
3//! A contract already says every flag, every environment variable, which subcommand each belongs
4//! to, what values are legal and what each is for. Shell completions and a man page are that same
5//! knowledge in other clothes, and the usual way they go wrong is by being written by hand and
6//! forgotten. These generators read the declared [`Record`]s and produce:
7//!
8//! - completions for [bash](bash()), [zsh](zsh()), [fish](fish()) and [nushell](nushell()), in which a
9//!   flag scoped to a subcommand is offered only after that subcommand, enumerated values are
10//!   completed, path-valued inputs complete file names, and a positional the program lists
11//!   itself ([`Asked`]) completes what the program prints when asked;
12//! - a [man page](man_page()).
13//!
14//! The records come from `Contract::records()` (generated by [`contract!`](crate::contract!)) or from a
15//! published contract document, so the artifacts cannot disagree with what the program accepts.
16//!
17//! # Treating the contract as untrusted
18//!
19//! The text these functions emit is *shell code*. A contract is data, possibly from a document
20//! someone else published, so nothing in it is trusted: flag names, command names, the program
21//! name and the allowed values must be plain tokens (anything else is skipped, or rejected for
22//! the program and command names), and every free-text field (summaries) is quoted for the shell
23//! it lands in. A summary such as `'; rm -rf ~ #` is displayed, never executed.
24//!
25//! ```
26//! use argenv_resolve::generate::{self, Command, Program, Shell};
27//!
28//! let program = Program {
29//!     name: "app",
30//!     version: "1.0.0",
31//!     about: "does things",
32//!     commands: &[Command { name: "run", summary: "Run it" }],
33//!     exit_status: &[("0", "done"), ("2", "the invocation is wrong")],
34//!     see_also: &[],
35//!     date: "2026-10-23",
36//!     asked: &[],
37//! };
38//! # let records = vec![];
39//! let bash = generate::completions(Shell::Bash, &program, &records)?;
40//! assert!(bash.contains("complete -F _app app"));
41//! let man = generate::man_page(&program, &records)?;
42//! assert!(man.starts_with(".TH APP 1 \"2026-10-23\""));
43//! # Ok::<(), generate::GenerateError>(())
44//! ```
45
46mod bash;
47mod fish;
48mod man;
49mod nushell;
50mod zsh;
51
52use crate::Record;
53
54pub use bash::bash;
55pub use fish::fish;
56pub use man::man_page;
57pub use nushell::nushell;
58pub use zsh::zsh;
59
60/// A subcommand, as completions and the man page present it.
61#[derive(Clone, Copy, Debug, PartialEq, Eq)]
62pub struct Command<'a> {
63    /// The word typed to run it (`create`). Must be a plain name.
64    pub name: &'a str,
65    /// One line saying what it does.
66    pub summary: &'a str,
67}
68
69/// What the generators need to know about the program that the inputs do not say.
70#[derive(Clone, Copy, Debug)]
71pub struct Program<'a> {
72    /// The executable's name, as typed (`snapall`).
73    pub name: &'a str,
74    /// The version shown in the man page footer.
75    pub version: &'a str,
76    /// One line, for the man page's NAME section.
77    pub about: &'a str,
78    /// Subcommands, in the order they should be listed. May be empty.
79    pub commands: &'a [Command<'a>],
80    /// `(status, meaning)` pairs for the man page's EXIT STATUS section.
81    pub exit_status: &'a [(&'a str, &'a str)],
82    /// Other manual pages, such as `snapper(8)`.
83    pub see_also: &'a [&'a str],
84    /// The man page date, `YYYY-MM-DD`. A parameter, not a clock reading, so output is
85    /// reproducible.
86    pub date: &'a str,
87    /// Positional arguments whose values only the program knows at the moment Tab is pressed
88    /// (names of files in the current folder, records in a store). May be empty.
89    pub asked: &'a [Asked<'a>],
90}
91
92/// The values of positional `position` of subcommand `command` are the lines the program prints
93/// when it is run with the arguments `ask`.
94///
95/// The completions run `<program> <ask...>` at completion time, in the user's current folder,
96/// with its error output discarded, and offer each line it prints; if it fails, nothing is
97/// offered. This takes precedence over the positional's enumerated values. The positional must be
98/// declared (an input with `Arg::positional(position)` scoped to `command`).
99///
100/// `command` must be a plain name and every word of `ask` a plain token (otherwise the generators
101/// refuse with [`GenerateError::InvalidName`]), so nothing in it can become shell code.
102///
103/// ```
104/// use argenv_resolve::generate::Asked;
105///
106/// // `tad q <Tab>` offers what `tad statements queries` prints.
107/// let asked = Asked { command: "q", position: 0, ask: &["statements", "queries"] };
108/// # let _ = asked;
109/// ```
110#[derive(Clone, Copy, Debug, PartialEq, Eq)]
111pub struct Asked<'a> {
112    /// The subcommand whose positional is completed (`q`).
113    pub command: &'a str,
114    /// Which positional of that subcommand, from zero.
115    pub position: usize,
116    /// The arguments the program is run with to list the values (`["statements", "queries"]`).
117    /// Must not be empty.
118    pub ask: &'a [&'a str],
119}
120
121/// Why nothing was generated.
122#[derive(Clone, Debug, PartialEq, Eq)]
123pub enum GenerateError {
124    /// The program name or a command name is not a plain token, so it cannot be put into shell
125    /// code safely.
126    InvalidName(String),
127}
128
129impl std::fmt::Display for GenerateError {
130    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
131        match self {
132            GenerateError::InvalidName(name) => write!(
133                f,
134                "`{name}` is not a plain name (letters, digits and `_ . -` only), so it cannot \
135                 be written into a shell completion"
136            ),
137        }
138    }
139}
140
141impl std::error::Error for GenerateError {}
142
143/// Which shell to generate completions for.
144#[derive(Clone, Copy, Debug, PartialEq, Eq)]
145pub enum Shell {
146    /// GNU bash (3.2 and later).
147    Bash,
148    /// zsh, through `_arguments`.
149    Zsh,
150    /// fish.
151    Fish,
152    /// nushell, as `extern` definitions.
153    Nushell,
154}
155
156impl Shell {
157    /// Every supported shell.
158    pub const ALL: [Shell; 4] = [Shell::Bash, Shell::Zsh, Shell::Fish, Shell::Nushell];
159
160    /// The word for this shell on a command line: `bash`, `zsh`, `fish`, `nushell`.
161    pub const fn token(self) -> &'static str {
162        match self {
163            Shell::Bash => "bash",
164            Shell::Zsh => "zsh",
165            Shell::Fish => "fish",
166            Shell::Nushell => "nushell",
167        }
168    }
169
170    /// The reverse of [`Shell::token`]; `nu` is accepted for nushell.
171    pub fn parse(token: &str) -> Option<Shell> {
172        match token {
173            "bash" => Some(Shell::Bash),
174            "zsh" => Some(Shell::Zsh),
175            "fish" => Some(Shell::Fish),
176            "nushell" | "nu" => Some(Shell::Nushell),
177            _ => None,
178        }
179    }
180}
181
182/// Completions for `shell`.
183pub fn completions(
184    shell: Shell,
185    program: &Program<'_>,
186    records: &[Record],
187) -> Result<String, GenerateError> {
188    match shell {
189        Shell::Bash => bash(program, records),
190        Shell::Zsh => zsh(program, records),
191        Shell::Fish => fish(program, records),
192        Shell::Nushell => nushell(program, records),
193    }
194}
195
196// ---------------------------------------------------------------------------------------
197// the shared model
198
199/// A flag, reduced to what completion needs.
200#[derive(Clone, Debug)]
201pub(crate) struct Flag {
202    pub long: Option<String>,
203    pub short: Option<String>,
204    pub takes_value: bool,
205    pub value_name: String,
206    /// Legal values, when the input is an enumeration or a closed list.
207    pub values: Vec<String>,
208    pub path: bool,
209    pub negatable: bool,
210    pub summary: String,
211    /// The declared default, as text, for non-boolean inputs.
212    pub default: Option<String>,
213    pub env: Vec<String>,
214    pub group: String,
215    /// The subcommands it belongs to; empty means all of them.
216    pub scope: Vec<String>,
217}
218
219impl Flag {
220    pub fn available_for(&self, command: &str) -> bool {
221        self.scope.is_empty() || self.scope.iter().any(|s| s == command)
222    }
223
224    /// Spellings that can be typed, each as it appears on the command line (`--dry-run`, `-n`).
225    pub fn spellings(&self) -> Vec<String> {
226        let mut out = Vec::new();
227        if let Some(s) = &self.short {
228            out.push(format!("-{s}"));
229        }
230        if let Some(l) = &self.long {
231            out.push(format!("--{l}"));
232            if self.negatable {
233                out.push(format!("--no-{l}"));
234            }
235        }
236        out
237    }
238}
239
240/// A positional argument, reduced to what completion needs.
241#[derive(Clone, Debug)]
242pub(crate) struct Positional {
243    /// Position within its command (or absolute, when unscoped), from zero.
244    pub index: usize,
245    pub name: String,
246    pub values: Vec<String>,
247    pub path: bool,
248    pub required: bool,
249    pub summary: String,
250    pub scope: Vec<String>,
251}
252
253impl Positional {
254    pub fn available_for(&self, command: &str) -> bool {
255        self.scope.iter().any(|s| s == command)
256    }
257}
258
259/// A plain token: non-empty, and only characters that mean nothing special to any shell.
260pub(crate) fn is_plain(token: &str) -> bool {
261    !token.is_empty()
262        && token.chars().all(|c| {
263            c.is_ascii_alphanumeric()
264                || matches!(c, '_' | '.' | '-' | ':' | '/' | '+' | '=' | '@' | ',')
265        })
266}
267
268/// A name that may be written into shell code: plain, and not starting with a dash.
269pub(crate) fn is_name(token: &str) -> bool {
270    is_plain(token) && !token.starts_with('-')
271}
272
273/// Free text on one line: whitespace runs, newlines and control characters become one space.
274pub(crate) fn one_line(text: &str) -> String {
275    text.split(|c: char| c.is_whitespace() || c.is_control())
276        .filter(|part| !part.is_empty())
277        .collect::<Vec<_>>()
278        .join(" ")
279}
280
281/// The part of the model every shell reads.
282pub(crate) struct Model {
283    pub flags: Vec<Flag>,
284    pub positionals: Vec<Positional>,
285}
286
287pub(crate) fn model(records: &[Record]) -> Model {
288    let mut flags = Vec::new();
289    let mut positionals = Vec::new();
290    for record in records {
291        let Some(arg) = &record.arg else { continue };
292        let values: Vec<String> = if matches!(record.ty.as_str(), "enum" | "list") {
293            record
294                .allowed
295                .iter()
296                .filter(|v| is_plain(v))
297                .cloned()
298                .collect()
299        } else {
300            Vec::new()
301        };
302        let summary = one_line(record.summary.as_deref().unwrap_or(""));
303        let scope: Vec<String> = record
304            .subcommands
305            .iter()
306            .filter(|s| is_name(s))
307            .cloned()
308            .collect();
309        if let Some(position) = arg.position {
310            positionals.push(Positional {
311                index: usize::from(position),
312                name: arg
313                    .value_name
314                    .clone()
315                    .filter(|n| is_plain(n))
316                    .unwrap_or_else(|| record.key.to_uppercase()),
317                values,
318                path: record.ty == "path",
319                required: record.required,
320                summary,
321                scope,
322            });
323            continue;
324        }
325        let long = arg.long.clone().filter(|l| is_name(l));
326        let short = arg
327            .short
328            .clone()
329            .filter(|s| s.chars().count() == 1 && is_name(s));
330        if long.is_none() && short.is_none() {
331            continue;
332        }
333        flags.push(Flag {
334            long,
335            short,
336            takes_value: arg.arity > 0,
337            value_name: arg
338                .value_name
339                .clone()
340                .filter(|n| is_plain(n))
341                .unwrap_or_else(|| "VALUE".to_string()),
342            values,
343            path: record.ty == "path",
344            negatable: arg.negatable,
345            summary,
346            default: record.default.as_ref().and_then(|v| match v {
347                serde_json::Value::String(text) => Some(text.clone()),
348                serde_json::Value::Number(n) => Some(n.to_string()),
349                _ => None,
350            }),
351            env: record
352                .env_names()
353                .iter()
354                .filter(|n| is_plain(n))
355                .map(|n| (*n).to_string())
356                .collect(),
357            group: record
358                .group
359                .clone()
360                .unwrap_or_else(|| "options".to_string()),
361            scope,
362        });
363    }
364    positionals.sort_by_key(|p| p.index);
365    Model { flags, positionals }
366}
367
368/// The subcommands to offer: the program's own list, validated.
369pub(crate) fn commands<'a>(program: &Program<'a>) -> Result<Vec<Command<'a>>, GenerateError> {
370    if !is_name(program.name) {
371        return Err(GenerateError::InvalidName(program.name.to_string()));
372    }
373    for asked in program.asked {
374        if !is_name(asked.command) {
375            return Err(GenerateError::InvalidName(asked.command.to_string()));
376        }
377        if asked.ask.is_empty() {
378            return Err(GenerateError::InvalidName(String::new()));
379        }
380        if let Some(bad) = asked.ask.iter().find(|word| !is_plain(word)) {
381            return Err(GenerateError::InvalidName((*bad).to_string()));
382        }
383    }
384    program
385        .commands
386        .iter()
387        .map(|c| {
388            if is_name(c.name) {
389                Ok(*c)
390            } else {
391                Err(GenerateError::InvalidName(c.name.to_string()))
392            }
393        })
394        .collect()
395}
396
397/// The command line that lists the values of `command`'s positional `index`, when the program
398/// declared one: the program name, then the `ask` words. All are plain tokens (checked by
399/// [`commands`]); each shell still quotes them, as it quotes everything else.
400pub(crate) fn asked_words<'a>(
401    program: &Program<'a>,
402    command: &str,
403    index: usize,
404) -> Option<Vec<&'a str>> {
405    program
406        .asked
407        .iter()
408        .find(|a| a.command == command && a.position == index)
409        .map(|a| {
410            std::iter::once(program.name)
411                .chain(a.ask.iter().copied())
412                .collect()
413        })
414}
415
416/// A shell identifier from a program name (`my-prog` becomes `my_prog`).
417pub(crate) fn identifier(name: &str) -> String {
418    name.chars()
419        .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
420        .collect()
421}