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
//! nushell completion: `extern` definitions with custom completers.

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

/// A nushell double-quoted string.
fn quote(text: &str) -> String {
    format!("\"{}\"", text.replace('\\', "\\\\").replace('"', "\\\""))
}

/// The nushell type for a flag or positional, naming its completer when it has one.
fn type_for(ty_path: bool, has_values: bool, completer: &str) -> String {
    if has_values {
        format!("string@{}", quote(completer))
    } else if ty_path {
        "path".to_string()
    } else {
        "string".to_string()
    }
}

fn flag_line(program: &str, flag: &Flag) -> Vec<String> {
    let completer = format!(
        "nu-complete {program} {}",
        flag.long
            .as_deref()
            .or(flag.short.as_deref())
            .unwrap_or("value")
    );
    let comment = if flag.summary.is_empty() {
        String::new()
    } else {
        format!("  # {}", flag.summary)
    };
    let mut name = match (&flag.long, &flag.short) {
        (Some(long), Some(short)) => format!("--{long}(-{short})"),
        (Some(long), None) => format!("--{long}"),
        (None, Some(short)) => format!("-{short}"),
        (None, None) => return Vec::new(),
    };
    if flag.takes_value {
        name.push_str(&format!(
            ": {}",
            type_for(flag.path, !flag.values.is_empty(), &completer)
        ));
    }
    let mut lines = vec![format!("    {name}{comment}")];
    if flag.negatable {
        if let Some(long) = &flag.long {
            lines.push(format!("    --no-{long}  # Turn off: {}", flag.summary));
        }
    }
    lines
}

fn positional_line(program: &str, command: &str, positional: &Positional, asked: bool) -> String {
    let completer = format!("nu-complete {program} {command} {}", positional.index);
    let name = identifier(&positional.name).to_lowercase();
    let optional = if positional.required { "" } else { "?" };
    let comment = if positional.summary.is_empty() {
        String::new()
    } else {
        format!("  # {}", positional.summary)
    };
    format!(
        "    {name}{optional}: {}{comment}",
        type_for(
            positional.path,
            asked || !positional.values.is_empty(),
            &completer
        )
    )
}

/// Generate a nushell completion script: a module of `extern` definitions that is brought into
/// scope when the file is sourced (or autoloaded from a vendor autoload directory).
pub fn nushell(program: &Program<'_>, records: &[Record]) -> Result<String, GenerateError> {
    let commands = commands(program)?;
    let Model { flags, positionals } = model(records);
    let name = program.name;
    let module = format!("{}_completions", identifier(name));

    let mut out = format!("# nushell completions for {name} (generated by argenv; do not edit by hand)\nmodule {module} {{\n");

    // Custom completers for enumerated flags and positionals, each defined once.
    let mut defined: Vec<String> = Vec::new();
    let mut define = |out: &mut String, completer: String, body: String| {
        if defined.contains(&completer) {
            return;
        }
        out.push_str(&format!("  def {} [] {{ {body} }}\n", quote(&completer)));
        defined.push(completer);
    };
    let list = |values: &[String]| {
        let items = values
            .iter()
            .map(|v| quote(v))
            .collect::<Vec<_>>()
            .join(" ");
        format!("[{items}]")
    };
    for flag in flags
        .iter()
        .filter(|f| f.takes_value && !f.values.is_empty())
    {
        let key = flag
            .long
            .as_deref()
            .or(flag.short.as_deref())
            .unwrap_or("value");
        define(
            &mut out,
            format!("nu-complete {name} {key}"),
            list(&flag.values),
        );
    }
    for positional in &positionals {
        for command in commands.iter().filter(|c| positional.available_for(c.name)) {
            let body = if let Some(words) = asked_words(program, command.name, positional.index) {
                // Run when Tab is pressed: each line it prints is a candidate; its error output
                // is captured and dropped, and a failure (or no such program) offers nothing.
                let line = words.iter().map(|w| quote(w)).collect::<Vec<_>>().join(" ");
                format!(
                    "try {{ let r = (run-external {line} | complete); if $r.exit_code == 0 {{ $r.stdout | lines }} else {{ [] }} }} catch {{ [] }}"
                )
            } else if !positional.values.is_empty() {
                list(&positional.values)
            } else {
                continue;
            };
            define(
                &mut out,
                format!("nu-complete {name} {} {}", command.name, positional.index),
                body,
            );
        }
    }

    // `name` itself: the unscoped flags.
    out.push_str(&format!("\n  export extern {} [\n", quote(name)));
    for flag in flags.iter().filter(|f| f.scope.is_empty()) {
        for line in flag_line(name, flag) {
            out.push_str(&format!("  {line}\n"));
        }
    }
    out.push_str("  ]\n");

    for command in &commands {
        out.push_str(&format!(
            "\n  # {}\n  export extern {} [\n",
            super::one_line(command.summary),
            quote(&format!("{name} {}", command.name))
        ));
        for flag in flags.iter().filter(|f| f.available_for(command.name)) {
            for line in flag_line(name, flag) {
                out.push_str(&format!("  {line}\n"));
            }
        }
        for positional in positionals.iter().filter(|p| p.available_for(command.name)) {
            out.push_str(&format!(
                "  {}\n",
                positional_line(
                    name,
                    command.name,
                    positional,
                    asked_words(program, command.name, positional.index).is_some(),
                )
            ));
        }
        out.push_str("  ]\n");
    }
    out.push_str(&format!("}}\n\nuse {module} *\n"));
    Ok(out)
}