Skip to main content

cornerstone/
complete.rs

1//! Shell completion generation. Produces a completion script for bash, zsh, or
2//! fish directly from the app's declared commands and flags — no annotations
3//! needed. The app exposes this through a built-in `completions <shell>` path;
4//! authors can also call it directly.
5
6use crate::spec::Command;
7
8/// Supported shells.
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub enum Shell {
11    Bash,
12    Zsh,
13    Fish,
14}
15
16impl Shell {
17    /// Parse a shell name; accepts common spellings.
18    pub fn parse(s: &str) -> Option<Shell> {
19        match s.to_lowercase().as_str() {
20            "bash" => Some(Shell::Bash),
21            "zsh" => Some(Shell::Zsh),
22            "fish" => Some(Shell::Fish),
23            _ => None,
24        }
25    }
26    pub fn all() -> [&'static str; 3] {
27        ["bash", "zsh", "fish"]
28    }
29}
30
31/// Generate a completion script for `app_name` given its command specs.
32pub fn generate(app_name: &str, commands: &[Command], shell: Shell) -> String {
33    match shell {
34        Shell::Bash => bash(app_name, commands),
35        Shell::Zsh => zsh(app_name, commands),
36        Shell::Fish => fish(app_name, commands),
37    }
38}
39
40fn command_names(commands: &[Command]) -> String {
41    let mut names: Vec<&str> = commands.iter().map(|c| c.name.as_str()).collect();
42    names.push("help");
43    names.join(" ")
44}
45
46fn bash(app: &str, commands: &[Command]) -> String {
47    let names = command_names(commands);
48    let mut per_cmd = String::new();
49    for c in commands {
50        let mut words: Vec<String> = c
51            .flags
52            .iter()
53            .map(|f| format!("--{}", f.long))
54            .chain(c.flags.iter().filter_map(|f| f.short.map(|s| format!("-{}", s))))
55            .collect();
56        // For a group, its subcommand names are the primary completions.
57        if c.is_group() {
58            for sub in &c.subcommands {
59                words.insert(0, sub.name.clone());
60            }
61        }
62        per_cmd.push_str(&format!(
63            "        {})\n            COMPREPLY=( $(compgen -W \"{}\" -- \"$cur\") )\n            return 0\n            ;;\n",
64            c.name,
65            words.join(" ")
66        ));
67    }
68    format!(
69        r#"# bash completion for {app}
70_{app}() {{
71    local cur prev words cword
72    cur="${{COMP_WORDS[COMP_CWORD]}}"
73    prev="${{COMP_WORDS[COMP_CWORD-1]}}"
74    local commands="{names}"
75    local globals="--help -h --version -V --quiet -q --verbose -v --json --dry-run"
76
77    if [ "$COMP_CWORD" -eq 1 ]; then
78        COMPREPLY=( $(compgen -W "$commands $globals" -- "$cur") )
79        return 0
80    fi
81
82    local subcmd="${{COMP_WORDS[1]}}"
83    case "$subcmd" in
84{per_cmd}    esac
85    COMPREPLY=( $(compgen -W "$globals" -- "$cur") )
86    return 0
87}}
88complete -F _{app} {app}
89"#,
90        app = app,
91        names = names,
92        per_cmd = per_cmd
93    )
94}
95
96fn zsh(app: &str, commands: &[Command]) -> String {
97    let mut lines = String::new();
98    for c in commands {
99        lines.push_str(&format!(
100            "        '{}:{}'\n",
101            c.name,
102            c.about.replace('\'', "")
103        ));
104    }
105    format!(
106        r#"#compdef {app}
107# zsh completion for {app}
108_{app}() {{
109    local -a commands
110    commands=(
111{lines}        'help:Show help'
112    )
113    _arguments -C \
114        '1: :->cmd' \
115        '*::arg:->args'
116    case $state in
117        cmd) _describe 'command' commands ;;
118    esac
119}}
120compdef _{app} {app}
121"#,
122        app = app,
123        lines = lines
124    )
125}
126
127fn fish(app: &str, commands: &[Command]) -> String {
128    let mut out = format!("# fish completion for {app}\n", app = app);
129    out.push_str(&format!("complete -c {app} -f\n", app = app));
130    for c in commands {
131        out.push_str(&format!(
132            "complete -c {app} -n '__fish_use_subcommand' -a '{name}' -d '{desc}'\n",
133            app = app,
134            name = c.name,
135            desc = c.about.replace('\'', "")
136        ));
137        if c.is_group() {
138            // Offer the group's children when the group name has been seen.
139            for sub in &c.subcommands {
140                out.push_str(&format!(
141                    "complete -c {app} -n '__fish_seen_subcommand_from {grp}' -a '{name}' -d '{desc}'\n",
142                    app = app,
143                    grp = c.name,
144                    name = sub.name,
145                    desc = sub.about.replace('\'', "")
146                ));
147            }
148        }
149        for f in &c.flags {
150            let short = f
151                .short
152                .map(|s| format!(" -s {}", s))
153                .unwrap_or_default();
154            out.push_str(&format!(
155                "complete -c {app} -n '__fish_seen_subcommand_from {name}' -l {long}{short} -d '{desc}'\n",
156                app = app,
157                name = c.name,
158                long = f.long,
159                short = short,
160                desc = f.help.replace('\'', "")
161            ));
162        }
163    }
164    out
165}