cornerlibstone 0.1.0

Lib Cornerstone — a zero-dependency foundation for building command-line tools in Rust: argument parsing, nested subcommands, themeable help in multiple presets, structured errors and exit codes, config loading, interactive prompts, shell-completion and man/markdown generation, logging, JSON output, and root/destructive-operation guards.
Documentation
//! Shell completion generation. Produces a completion script for bash, zsh, or
//! fish directly from the app's declared commands and flags — no annotations
//! needed. The app exposes this through a built-in `completions <shell>` path;
//! authors can also call it directly.

use crate::spec::Command;

/// Supported shells.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Shell {
    Bash,
    Zsh,
    Fish,
}

impl Shell {
    /// Parse a shell name; accepts common spellings.
    pub fn parse(s: &str) -> Option<Shell> {
        match s.to_lowercase().as_str() {
            "bash" => Some(Shell::Bash),
            "zsh" => Some(Shell::Zsh),
            "fish" => Some(Shell::Fish),
            _ => None,
        }
    }
    pub fn all() -> [&'static str; 3] {
        ["bash", "zsh", "fish"]
    }
}

/// Generate a completion script for `app_name` given its command specs.
pub fn generate(app_name: &str, commands: &[Command], shell: Shell) -> String {
    match shell {
        Shell::Bash => bash(app_name, commands),
        Shell::Zsh => zsh(app_name, commands),
        Shell::Fish => fish(app_name, commands),
    }
}

fn command_names(commands: &[Command]) -> String {
    let mut names: Vec<&str> = commands.iter().map(|c| c.name.as_str()).collect();
    names.push("help");
    names.join(" ")
}

fn bash(app: &str, commands: &[Command]) -> String {
    let names = command_names(commands);
    let mut per_cmd = String::new();
    for c in commands {
        let mut words: Vec<String> = c
            .flags
            .iter()
            .map(|f| format!("--{}", f.long))
            .chain(c.flags.iter().filter_map(|f| f.short.map(|s| format!("-{}", s))))
            .collect();
        // For a group, its subcommand names are the primary completions.
        if c.is_group() {
            for sub in &c.subcommands {
                words.insert(0, sub.name.clone());
            }
        }
        per_cmd.push_str(&format!(
            "        {})\n            COMPREPLY=( $(compgen -W \"{}\" -- \"$cur\") )\n            return 0\n            ;;\n",
            c.name,
            words.join(" ")
        ));
    }
    format!(
        r#"# bash completion for {app}
_{app}() {{
    local cur prev words cword
    cur="${{COMP_WORDS[COMP_CWORD]}}"
    prev="${{COMP_WORDS[COMP_CWORD-1]}}"
    local commands="{names}"
    local globals="--help -h --version -V --quiet -q --verbose -v --json --dry-run"

    if [ "$COMP_CWORD" -eq 1 ]; then
        COMPREPLY=( $(compgen -W "$commands $globals" -- "$cur") )
        return 0
    fi

    local subcmd="${{COMP_WORDS[1]}}"
    case "$subcmd" in
{per_cmd}    esac
    COMPREPLY=( $(compgen -W "$globals" -- "$cur") )
    return 0
}}
complete -F _{app} {app}
"#,
        app = app,
        names = names,
        per_cmd = per_cmd
    )
}

fn zsh(app: &str, commands: &[Command]) -> String {
    let mut lines = String::new();
    for c in commands {
        lines.push_str(&format!(
            "        '{}:{}'\n",
            c.name,
            c.about.replace('\'', "")
        ));
    }
    format!(
        r#"#compdef {app}
# zsh completion for {app}
_{app}() {{
    local -a commands
    commands=(
{lines}        'help:Show help'
    )
    _arguments -C \
        '1: :->cmd' \
        '*::arg:->args'
    case $state in
        cmd) _describe 'command' commands ;;
    esac
}}
compdef _{app} {app}
"#,
        app = app,
        lines = lines
    )
}

fn fish(app: &str, commands: &[Command]) -> String {
    let mut out = format!("# fish completion for {app}\n", app = app);
    out.push_str(&format!("complete -c {app} -f\n", app = app));
    for c in commands {
        out.push_str(&format!(
            "complete -c {app} -n '__fish_use_subcommand' -a '{name}' -d '{desc}'\n",
            app = app,
            name = c.name,
            desc = c.about.replace('\'', "")
        ));
        if c.is_group() {
            // Offer the group's children when the group name has been seen.
            for sub in &c.subcommands {
                out.push_str(&format!(
                    "complete -c {app} -n '__fish_seen_subcommand_from {grp}' -a '{name}' -d '{desc}'\n",
                    app = app,
                    grp = c.name,
                    name = sub.name,
                    desc = sub.about.replace('\'', "")
                ));
            }
        }
        for f in &c.flags {
            let short = f
                .short
                .map(|s| format!(" -s {}", s))
                .unwrap_or_default();
            out.push_str(&format!(
                "complete -c {app} -n '__fish_seen_subcommand_from {name}' -l {long}{short} -d '{desc}'\n",
                app = app,
                name = c.name,
                long = f.long,
                short = short,
                desc = f.help.replace('\'', "")
            ));
        }
    }
    out
}