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
//! zsh completion.

use super::{commands, identifier, model, Flag, GenerateError, Model, Positional, Program};
use crate::Record;

/// Single-quote text for zsh (inside single quotes only `'` is special).
fn quote(text: &str) -> String {
    format!("'{}'", text.replace('\'', "'\\''"))
}

/// Text for the `[description]` or `description` part of an `_arguments` / `_describe` spec:
/// the characters those parsers treat as syntax are backslash-escaped.
fn spec_text(text: &str) -> String {
    let mut out = String::new();
    for c in text.chars() {
        if matches!(c, '\\' | '[' | ']' | ':') {
            out.push('\\');
        }
        out.push(c);
    }
    out
}

/// One `_arguments` spec for a flag.
fn flag_spec(flag: &Flag) -> Vec<String> {
    let description = spec_text(&flag.summary);
    let action = if !flag.values.is_empty() {
        format!("({})", flag.values.join(" "))
    } else if flag.path {
        "_files".to_string()
    } else {
        " ".to_string()
    };
    let value = if flag.takes_value {
        format!(":{}:{action}", spec_text(&flag.value_name))
    } else {
        String::new()
    };
    let eq = if flag.takes_value { "=" } else { "" };
    let mut specs = Vec::new();
    match (&flag.short, &flag.long) {
        (Some(short), Some(long)) => {
            // `{-s,--long}` expands to two specs that exclude each other.
            specs.push(format!(
                "'(-{short} --{long})'{{-{short},--{long}{eq}}}{}",
                quote(&format!("[{description}]{value}"))
            ));
        }
        (None, Some(long)) => specs.push(quote(&format!("--{long}{eq}[{description}]{value}"))),
        (Some(short), None) => specs.push(quote(&format!("-{short}[{description}]{value}"))),
        (None, None) => {}
    }
    if flag.negatable {
        if let Some(long) = &flag.long {
            specs.push(quote(&format!(
                "--no-{long}[{}]",
                spec_text(&format!("Turn off: {}", flag.summary))
            )));
        }
    }
    specs
}

fn positional_spec(index: usize, positional: &Positional) -> String {
    let action = if !positional.values.is_empty() {
        format!("({})", positional.values.join(" "))
    } else if positional.path {
        "_files".to_string()
    } else {
        " ".to_string()
    };
    quote(&format!(
        "{}:{}:{action}",
        index + 1,
        spec_text(&positional.name)
    ))
}

/// Generate a zsh completion script, for `fpath` as `_<program>`.
pub fn zsh(program: &Program<'_>, records: &[Record]) -> Result<String, GenerateError> {
    let commands = commands(program)?;
    let Model { flags, positionals } = model(records);
    let name = program.name;
    let function = format!("_{}", identifier(name));

    let mut out = format!(
        "#compdef {name}\n# zsh completion for {name} (generated by argenv; do not edit by hand)\n{function}() {{\n  local curcontext=\"$curcontext\" state line ret=1\n  typeset -A opt_args\n\n  _arguments -C \\\n"
    );
    for flag in flags.iter().filter(|f| f.scope.is_empty()) {
        for spec in flag_spec(flag) {
            out.push_str(&format!("    {spec} \\\n"));
        }
    }
    if commands.is_empty() {
        out.push_str("    '*:: :->args' && ret=0\n");
    } else {
        out.push_str("    '1: :->command' \\\n    '*:: :->args' && ret=0\n");
    }

    out.push_str("\n  case $state in\n");
    if !commands.is_empty() {
        out.push_str("    command)\n      local -a commands\n      commands=(\n");
        for command in &commands {
            out.push_str(&format!(
                "        {}\n",
                quote(&format!(
                    "{}:{}",
                    command.name,
                    spec_text(&super::one_line(command.summary))
                ))
            ));
        }
        out.push_str(&format!(
            "      )\n      _describe -t commands '{name} command' commands && ret=0\n      ;;\n"
        ));
        out.push_str("    args)\n      case $words[1] in\n");
        for command in &commands {
            out.push_str(&format!(
                "        {})\n          _arguments \\\n",
                command.name
            ));
            for flag in flags.iter().filter(|f| f.available_for(command.name)) {
                for spec in flag_spec(flag) {
                    out.push_str(&format!("            {spec} \\\n"));
                }
            }
            for positional in positionals.iter().filter(|p| p.available_for(command.name)) {
                out.push_str(&format!(
                    "            {} \\\n",
                    positional_spec(positional.index, positional)
                ));
            }
            out.push_str("            && ret=0\n          ;;\n");
        }
        out.push_str("      esac\n      ;;\n");
    } else {
        out.push_str("    args)\n      ;;\n");
    }
    out.push_str(&format!("  esac\n  return ret\n}}\n\n{function} \"$@\"\n"));
    Ok(out)
}