argenv-resolve 0.3.1

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
//! 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, and path-valued inputs complete file names;
//! - 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",
//! };
//! # 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,
}

/// 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()));
    }
    program
        .commands
        .iter()
        .map(|c| {
            if is_name(c.name) {
                Ok(*c)
            } else {
                Err(GenerateError::InvalidName(c.name.to_string()))
            }
        })
        .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()
}