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

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

/// Single-quote text for bash: the only character that matters inside is the quote itself.
fn quote(text: &str) -> String {
    format!("'{}'", text.replace('\'', "'\\''"))
}

/// Generate a bash completion script.
///
/// The script defines `_<program>` and registers it with `complete -F`. It completes the
/// subcommand, the flags that belong to the subcommand already typed (and the unscoped ones),
/// the values of enumerated flags, file names for path-valued flags, and enumerated or path
/// positional arguments, and the positionals the program lists itself ([`Asked`](super::Asked)).
pub fn bash(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!(
        "# bash completion for {name} (generated by argenv; do not edit by hand)\n{function}() {{\n    local cur prev cmd cmd_index i\n    cur=\"${{COMP_WORDS[COMP_CWORD]}}\"\n    prev=\"\"\n    [[ $COMP_CWORD -gt 0 ]] && prev=\"${{COMP_WORDS[COMP_CWORD-1]}}\"\n    # `--flag=value`: bash splits at `=`, so the flag is two words back.\n    if [[ \"$prev\" == \"=\" ]]; then\n        prev=\"${{COMP_WORDS[COMP_CWORD-2]}}\"\n    elif [[ \"$cur\" == \"=\" ]]; then\n        cur=\"\"\n    fi\n"
    );

    // Which subcommand has been typed.
    out.push_str("    cmd=\"\"\n    cmd_index=0\n");
    if !commands.is_empty() {
        let names = commands
            .iter()
            .map(|c| c.name)
            .collect::<Vec<_>>()
            .join("|");
        out.push_str(&format!(
            "    for ((i = 1; i < COMP_CWORD; i++)); do\n        case \"${{COMP_WORDS[i]}}\" in\n            {names}) cmd=\"${{COMP_WORDS[i]}}\"; cmd_index=$i; break ;;\n        esac\n    done\n"
        ));
    }

    // The value of the flag just typed.
    let mut value_arms = String::new();
    let mut value_flags: Vec<String> = Vec::new();
    for flag in flags.iter().filter(|f| f.takes_value) {
        // Keyed by "<subcommand>:<flag>", so the values of a flag that belongs to `create` are
        // completed after `create` and nowhere else, which is what the other shells do too.
        let pattern = flag
            .spellings()
            .iter()
            .flat_map(|spelling| {
                if flag.scope.is_empty() {
                    vec![format!("*:{spelling}")]
                } else {
                    flag.scope
                        .iter()
                        .map(|command| format!("{command}:{spelling}"))
                        .collect()
                }
            })
            .collect::<Vec<_>>()
            .join("|");
        value_flags.extend(flag.spellings());
        if !flag.values.is_empty() {
            value_arms.push_str(&format!(
                "        {pattern}) COMPREPLY=( $(compgen -W {} -- \"$cur\") ); return 0 ;;\n",
                quote(&flag.values.join(" "))
            ));
        } else if flag.path {
            value_arms.push_str(&format!(
                "        {pattern}) compopt -o filenames 2>/dev/null; COMPREPLY=( $(compgen -f -- \"$cur\") ); return 0 ;;\n"
            ));
        } else {
            value_arms.push_str(&format!("        {pattern}) COMPREPLY=(); return 0 ;;\n"));
        }
    }
    if !value_arms.is_empty() {
        out.push_str(&format!(
            "    case \"$cmd:$prev\" in\n{value_arms}    esac\n"
        ));
    }

    // The flags on offer, per subcommand.
    let words = |command: Option<&str>| -> String {
        flags
            .iter()
            .filter(|f| match command {
                Some(c) => f.available_for(c),
                None => f.scope.is_empty(),
            })
            .flat_map(|f| f.spellings())
            .collect::<Vec<_>>()
            .join(" ")
    };
    out.push_str("    local flags\n    case \"$cmd\" in\n");
    for command in &commands {
        out.push_str(&format!(
            "        {}) flags={} ;;\n",
            command.name,
            quote(&words(Some(command.name)))
        ));
    }
    out.push_str(&format!(
        "        *) flags={} ;;\n    esac\n",
        quote(&words(None))
    ));
    out.push_str("    if [[ \"$cur\" == -* ]]; then\n        COMPREPLY=( $(compgen -W \"$flags\" -- \"$cur\") )\n        return 0\n    fi\n");

    // No subcommand yet: offer them.
    if !commands.is_empty() {
        let names = commands
            .iter()
            .map(|c| c.name)
            .collect::<Vec<_>>()
            .join(" ");
        out.push_str(&format!(
            "    if [[ -z \"$cmd\" ]]; then\n        COMPREPLY=( $(compgen -W {} -- \"$cur\") )\n        return 0\n    fi\n",
            quote(&names)
        ));
    }

    // Positional arguments with something to offer: what the program prints when asked, else
    // the enumerated values, else file names.
    let mut positional_arms = String::new();
    for positional in &positionals {
        for command in commands.iter().filter(|c| positional.available_for(c.name)) {
            let arm = if let Some(words) = asked_words(program, command.name, positional.index) {
                let line = words.iter().map(|w| quote(w)).collect::<Vec<_>>().join(" ");
                format!("COMPREPLY=( $(compgen -W \"$({line} 2>/dev/null)\" -- \"$cur\") )")
            } else if !positional.values.is_empty() {
                format!(
                    "COMPREPLY=( $(compgen -W {} -- \"$cur\") )",
                    quote(&positional.values.join(" "))
                )
            } else if positional.path {
                "compopt -o filenames 2>/dev/null; COMPREPLY=( $(compgen -f -- \"$cur\") )"
                    .to_string()
            } else {
                continue;
            };
            positional_arms.push_str(&format!(
                "        {}:{}) {arm} ;;\n",
                command.name, positional.index
            ));
        }
    }
    if !positional_arms.is_empty() {
        out.push_str("    local pos=0 skip=0 w\n    for ((i = cmd_index + 1; i < COMP_CWORD; i++)); do\n        w=\"${COMP_WORDS[i]}\"\n        if [[ $skip -eq 1 ]]; then skip=0; continue; fi\n        case \"$w\" in\n");
        if !value_flags.is_empty() {
            out.push_str(&format!(
                "            {}) skip=1 ;;\n",
                value_flags.join("|")
            ));
        }
        out.push_str("            -*) ;;\n            *) pos=$((pos + 1)) ;;\n        esac\n    done\n    case \"$cmd:$pos\" in\n");
        out.push_str(&positional_arms);
        out.push_str("    esac\n");
    }
    out.push_str(&format!(
        "    return 0\n}}\ncomplete -F {function} {name}\n"
    ));
    Ok(out)
}