argenv-resolve 0.4.0

Resolve an argenv contract against a real invocation - argv and envp, with precedence, defaults, and linting. Depends on argenv for the declared data; argenv depends on nothing here.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
//! Everything a program ships *about* its invocation, derived from the declaration.
//!
//! A contract already says every flag, every environment variable, which subcommand each belongs
//! to, what values are legal and what each is for. Shell completions and a man page are that same
//! knowledge in other clothes, and the usual way they go wrong is by being written by hand and
//! forgotten. These generators read the declared [`Record`]s and produce:
//!
//! - completions for [bash](bash()), [zsh](zsh()), [fish](fish()) and [nushell](nushell()), in which a
//!   flag scoped to a subcommand is offered only after that subcommand, enumerated values are
//!   completed, path-valued inputs complete file names, and a positional the program lists
//!   itself ([`Asked`]) completes what the program prints when asked;
//! - a [man page](man_page()).
//!
//! The records come from `Contract::records()` (generated by [`contract!`](crate::contract!)) or from a
//! published contract document, so the artifacts cannot disagree with what the program accepts.
//!
//! # Treating the contract as untrusted
//!
//! The text these functions emit is *shell code*. A contract is data, possibly from a document
//! someone else published, so nothing in it is trusted: flag names, command names, the program
//! name and the allowed values must be plain tokens (anything else is skipped, or rejected for
//! the program and command names), and every free-text field (summaries) is quoted for the shell
//! it lands in. A summary such as `'; rm -rf ~ #` is displayed, never executed.
//!
//! ```
//! use argenv_resolve::generate::{self, Command, Program, Shell};
//!
//! let program = Program {
//!     name: "app",
//!     version: "1.0.0",
//!     about: "does things",
//!     commands: &[Command { name: "run", summary: "Run it" }],
//!     exit_status: &[("0", "done"), ("2", "the invocation is wrong")],
//!     see_also: &[],
//!     date: "2026-10-23",
//!     asked: &[],
//! };
//! # let records = vec![];
//! let bash = generate::completions(Shell::Bash, &program, &records)?;
//! assert!(bash.contains("complete -F _app app"));
//! let man = generate::man_page(&program, &records)?;
//! assert!(man.starts_with(".TH APP 1 \"2026-10-23\""));
//! # Ok::<(), generate::GenerateError>(())
//! ```

mod bash;
mod fish;
mod man;
mod nushell;
mod zsh;

use crate::Record;

pub use bash::bash;
pub use fish::fish;
pub use man::man_page;
pub use nushell::nushell;
pub use zsh::zsh;

/// A subcommand, as completions and the man page present it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Command<'a> {
    /// The word typed to run it (`create`). Must be a plain name.
    pub name: &'a str,
    /// One line saying what it does.
    pub summary: &'a str,
}

/// What the generators need to know about the program that the inputs do not say.
#[derive(Clone, Copy, Debug)]
pub struct Program<'a> {
    /// The executable's name, as typed (`snapall`).
    pub name: &'a str,
    /// The version shown in the man page footer.
    pub version: &'a str,
    /// One line, for the man page's NAME section.
    pub about: &'a str,
    /// Subcommands, in the order they should be listed. May be empty.
    pub commands: &'a [Command<'a>],
    /// `(status, meaning)` pairs for the man page's EXIT STATUS section.
    pub exit_status: &'a [(&'a str, &'a str)],
    /// Other manual pages, such as `snapper(8)`.
    pub see_also: &'a [&'a str],
    /// The man page date, `YYYY-MM-DD`. A parameter, not a clock reading, so output is
    /// reproducible.
    pub date: &'a str,
    /// Positional arguments whose values only the program knows at the moment Tab is pressed
    /// (names of files in the current folder, records in a store). May be empty.
    pub asked: &'a [Asked<'a>],
}

/// The values of positional `position` of subcommand `command` are the lines the program prints
/// when it is run with the arguments `ask`.
///
/// The completions run `<program> <ask...>` at completion time, in the user's current folder,
/// with its error output discarded, and offer each line it prints; if it fails, nothing is
/// offered. This takes precedence over the positional's enumerated values. The positional must be
/// declared (an input with `Arg::positional(position)` scoped to `command`).
///
/// `command` must be a plain name and every word of `ask` a plain token (otherwise the generators
/// refuse with [`GenerateError::InvalidName`]), so nothing in it can become shell code.
///
/// ```
/// use argenv_resolve::generate::Asked;
///
/// // `tad q <Tab>` offers what `tad statements queries` prints.
/// let asked = Asked { command: "q", position: 0, ask: &["statements", "queries"] };
/// # let _ = asked;
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Asked<'a> {
    /// The subcommand whose positional is completed (`q`).
    pub command: &'a str,
    /// Which positional of that subcommand, from zero.
    pub position: usize,
    /// The arguments the program is run with to list the values (`["statements", "queries"]`).
    /// Must not be empty.
    pub ask: &'a [&'a str],
}

/// Why nothing was generated.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum GenerateError {
    /// The program name or a command name is not a plain token, so it cannot be put into shell
    /// code safely.
    InvalidName(String),
}

impl std::fmt::Display for GenerateError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            GenerateError::InvalidName(name) => write!(
                f,
                "`{name}` is not a plain name (letters, digits and `_ . -` only), so it cannot \
                 be written into a shell completion"
            ),
        }
    }
}

impl std::error::Error for GenerateError {}

/// Which shell to generate completions for.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Shell {
    /// GNU bash (3.2 and later).
    Bash,
    /// zsh, through `_arguments`.
    Zsh,
    /// fish.
    Fish,
    /// nushell, as `extern` definitions.
    Nushell,
}

impl Shell {
    /// Every supported shell.
    pub const ALL: [Shell; 4] = [Shell::Bash, Shell::Zsh, Shell::Fish, Shell::Nushell];

    /// The word for this shell on a command line: `bash`, `zsh`, `fish`, `nushell`.
    pub const fn token(self) -> &'static str {
        match self {
            Shell::Bash => "bash",
            Shell::Zsh => "zsh",
            Shell::Fish => "fish",
            Shell::Nushell => "nushell",
        }
    }

    /// The reverse of [`Shell::token`]; `nu` is accepted for nushell.
    pub fn parse(token: &str) -> Option<Shell> {
        match token {
            "bash" => Some(Shell::Bash),
            "zsh" => Some(Shell::Zsh),
            "fish" => Some(Shell::Fish),
            "nushell" | "nu" => Some(Shell::Nushell),
            _ => None,
        }
    }
}

/// Completions for `shell`.
pub fn completions(
    shell: Shell,
    program: &Program<'_>,
    records: &[Record],
) -> Result<String, GenerateError> {
    match shell {
        Shell::Bash => bash(program, records),
        Shell::Zsh => zsh(program, records),
        Shell::Fish => fish(program, records),
        Shell::Nushell => nushell(program, records),
    }
}

// ---------------------------------------------------------------------------------------
// the shared model

/// A flag, reduced to what completion needs.
#[derive(Clone, Debug)]
pub(crate) struct Flag {
    pub long: Option<String>,
    pub short: Option<String>,
    pub takes_value: bool,
    pub value_name: String,
    /// Legal values, when the input is an enumeration or a closed list.
    pub values: Vec<String>,
    pub path: bool,
    pub negatable: bool,
    pub summary: String,
    /// The declared default, as text, for non-boolean inputs.
    pub default: Option<String>,
    pub env: Vec<String>,
    pub group: String,
    /// The subcommands it belongs to; empty means all of them.
    pub scope: Vec<String>,
}

impl Flag {
    pub fn available_for(&self, command: &str) -> bool {
        self.scope.is_empty() || self.scope.iter().any(|s| s == command)
    }

    /// Spellings that can be typed, each as it appears on the command line (`--dry-run`, `-n`).
    pub fn spellings(&self) -> Vec<String> {
        let mut out = Vec::new();
        if let Some(s) = &self.short {
            out.push(format!("-{s}"));
        }
        if let Some(l) = &self.long {
            out.push(format!("--{l}"));
            if self.negatable {
                out.push(format!("--no-{l}"));
            }
        }
        out
    }
}

/// A positional argument, reduced to what completion needs.
#[derive(Clone, Debug)]
pub(crate) struct Positional {
    /// Position within its command (or absolute, when unscoped), from zero.
    pub index: usize,
    pub name: String,
    pub values: Vec<String>,
    pub path: bool,
    pub required: bool,
    pub summary: String,
    pub scope: Vec<String>,
}

impl Positional {
    pub fn available_for(&self, command: &str) -> bool {
        self.scope.iter().any(|s| s == command)
    }
}

/// A plain token: non-empty, and only characters that mean nothing special to any shell.
pub(crate) fn is_plain(token: &str) -> bool {
    !token.is_empty()
        && token.chars().all(|c| {
            c.is_ascii_alphanumeric()
                || matches!(c, '_' | '.' | '-' | ':' | '/' | '+' | '=' | '@' | ',')
        })
}

/// A name that may be written into shell code: plain, and not starting with a dash.
pub(crate) fn is_name(token: &str) -> bool {
    is_plain(token) && !token.starts_with('-')
}

/// Free text on one line: whitespace runs, newlines and control characters become one space.
pub(crate) fn one_line(text: &str) -> String {
    text.split(|c: char| c.is_whitespace() || c.is_control())
        .filter(|part| !part.is_empty())
        .collect::<Vec<_>>()
        .join(" ")
}

/// The part of the model every shell reads.
pub(crate) struct Model {
    pub flags: Vec<Flag>,
    pub positionals: Vec<Positional>,
}

pub(crate) fn model(records: &[Record]) -> Model {
    let mut flags = Vec::new();
    let mut positionals = Vec::new();
    for record in records {
        let Some(arg) = &record.arg else { continue };
        let values: Vec<String> = if matches!(record.ty.as_str(), "enum" | "list") {
            record
                .allowed
                .iter()
                .filter(|v| is_plain(v))
                .cloned()
                .collect()
        } else {
            Vec::new()
        };
        let summary = one_line(record.summary.as_deref().unwrap_or(""));
        let scope: Vec<String> = record
            .subcommands
            .iter()
            .filter(|s| is_name(s))
            .cloned()
            .collect();
        if let Some(position) = arg.position {
            positionals.push(Positional {
                index: usize::from(position),
                name: arg
                    .value_name
                    .clone()
                    .filter(|n| is_plain(n))
                    .unwrap_or_else(|| record.key.to_uppercase()),
                values,
                path: record.ty == "path",
                required: record.required,
                summary,
                scope,
            });
            continue;
        }
        let long = arg.long.clone().filter(|l| is_name(l));
        let short = arg
            .short
            .clone()
            .filter(|s| s.chars().count() == 1 && is_name(s));
        if long.is_none() && short.is_none() {
            continue;
        }
        flags.push(Flag {
            long,
            short,
            takes_value: arg.arity > 0,
            value_name: arg
                .value_name
                .clone()
                .filter(|n| is_plain(n))
                .unwrap_or_else(|| "VALUE".to_string()),
            values,
            path: record.ty == "path",
            negatable: arg.negatable,
            summary,
            default: record.default.as_ref().and_then(|v| match v {
                serde_json::Value::String(text) => Some(text.clone()),
                serde_json::Value::Number(n) => Some(n.to_string()),
                _ => None,
            }),
            env: record
                .env_names()
                .iter()
                .filter(|n| is_plain(n))
                .map(|n| (*n).to_string())
                .collect(),
            group: record
                .group
                .clone()
                .unwrap_or_else(|| "options".to_string()),
            scope,
        });
    }
    positionals.sort_by_key(|p| p.index);
    Model { flags, positionals }
}

/// The subcommands to offer: the program's own list, validated.
pub(crate) fn commands<'a>(program: &Program<'a>) -> Result<Vec<Command<'a>>, GenerateError> {
    if !is_name(program.name) {
        return Err(GenerateError::InvalidName(program.name.to_string()));
    }
    for asked in program.asked {
        if !is_name(asked.command) {
            return Err(GenerateError::InvalidName(asked.command.to_string()));
        }
        if asked.ask.is_empty() {
            return Err(GenerateError::InvalidName(String::new()));
        }
        if let Some(bad) = asked.ask.iter().find(|word| !is_plain(word)) {
            return Err(GenerateError::InvalidName((*bad).to_string()));
        }
    }
    program
        .commands
        .iter()
        .map(|c| {
            if is_name(c.name) {
                Ok(*c)
            } else {
                Err(GenerateError::InvalidName(c.name.to_string()))
            }
        })
        .collect()
}

/// The command line that lists the values of `command`'s positional `index`, when the program
/// declared one: the program name, then the `ask` words. All are plain tokens (checked by
/// [`commands`]); each shell still quotes them, as it quotes everything else.
pub(crate) fn asked_words<'a>(
    program: &Program<'a>,
    command: &str,
    index: usize,
) -> Option<Vec<&'a str>> {
    program
        .asked
        .iter()
        .find(|a| a.command == command && a.position == index)
        .map(|a| {
            std::iter::once(program.name)
                .chain(a.ask.iter().copied())
                .collect()
        })
}

/// A shell identifier from a program name (`my-prog` becomes `my_prog`).
pub(crate) fn identifier(name: &str) -> String {
    name.chars()
        .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
        .collect()
}