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