Skip to main content

argenv_resolve/generate/
bash.rs

1//! bash completion.
2
3use super::{commands, identifier, model, GenerateError, Model, Program};
4use crate::Record;
5
6/// Single-quote text for bash: the only character that matters inside is the quote itself.
7fn quote(text: &str) -> String {
8    format!("'{}'", text.replace('\'', "'\\''"))
9}
10
11/// Generate a bash completion script.
12///
13/// The script defines `_<program>` and registers it with `complete -F`. It completes the
14/// subcommand, the flags that belong to the subcommand already typed (and the unscoped ones),
15/// the values of enumerated flags, file names for path-valued flags, and enumerated or path
16/// positional arguments.
17pub fn bash(program: &Program<'_>, records: &[Record]) -> Result<String, GenerateError> {
18    let commands = commands(program)?;
19    let Model { flags, positionals } = model(records);
20    let name = program.name;
21    let function = format!("_{}", identifier(name));
22
23    let mut out = format!(
24        "# 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"
25    );
26
27    // Which subcommand has been typed.
28    out.push_str("    cmd=\"\"\n    cmd_index=0\n");
29    if !commands.is_empty() {
30        let names = commands
31            .iter()
32            .map(|c| c.name)
33            .collect::<Vec<_>>()
34            .join("|");
35        out.push_str(&format!(
36            "    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"
37        ));
38    }
39
40    // The value of the flag just typed.
41    let mut value_arms = String::new();
42    let mut value_flags: Vec<String> = Vec::new();
43    for flag in flags.iter().filter(|f| f.takes_value) {
44        // Keyed by "<subcommand>:<flag>", so the values of a flag that belongs to `create` are
45        // completed after `create` and nowhere else, which is what the other shells do too.
46        let pattern = flag
47            .spellings()
48            .iter()
49            .flat_map(|spelling| {
50                if flag.scope.is_empty() {
51                    vec![format!("*:{spelling}")]
52                } else {
53                    flag.scope
54                        .iter()
55                        .map(|command| format!("{command}:{spelling}"))
56                        .collect()
57                }
58            })
59            .collect::<Vec<_>>()
60            .join("|");
61        value_flags.extend(flag.spellings());
62        if !flag.values.is_empty() {
63            value_arms.push_str(&format!(
64                "        {pattern}) COMPREPLY=( $(compgen -W {} -- \"$cur\") ); return 0 ;;\n",
65                quote(&flag.values.join(" "))
66            ));
67        } else if flag.path {
68            value_arms.push_str(&format!(
69                "        {pattern}) compopt -o filenames 2>/dev/null; COMPREPLY=( $(compgen -f -- \"$cur\") ); return 0 ;;\n"
70            ));
71        } else {
72            value_arms.push_str(&format!("        {pattern}) COMPREPLY=(); return 0 ;;\n"));
73        }
74    }
75    if !value_arms.is_empty() {
76        out.push_str(&format!(
77            "    case \"$cmd:$prev\" in\n{value_arms}    esac\n"
78        ));
79    }
80
81    // The flags on offer, per subcommand.
82    let words = |command: Option<&str>| -> String {
83        flags
84            .iter()
85            .filter(|f| match command {
86                Some(c) => f.available_for(c),
87                None => f.scope.is_empty(),
88            })
89            .flat_map(|f| f.spellings())
90            .collect::<Vec<_>>()
91            .join(" ")
92    };
93    out.push_str("    local flags\n    case \"$cmd\" in\n");
94    for command in &commands {
95        out.push_str(&format!(
96            "        {}) flags={} ;;\n",
97            command.name,
98            quote(&words(Some(command.name)))
99        ));
100    }
101    out.push_str(&format!(
102        "        *) flags={} ;;\n    esac\n",
103        quote(&words(None))
104    ));
105    out.push_str("    if [[ \"$cur\" == -* ]]; then\n        COMPREPLY=( $(compgen -W \"$flags\" -- \"$cur\") )\n        return 0\n    fi\n");
106
107    // No subcommand yet: offer them.
108    if !commands.is_empty() {
109        let names = commands
110            .iter()
111            .map(|c| c.name)
112            .collect::<Vec<_>>()
113            .join(" ");
114        out.push_str(&format!(
115            "    if [[ -z \"$cmd\" ]]; then\n        COMPREPLY=( $(compgen -W {} -- \"$cur\") )\n        return 0\n    fi\n",
116            quote(&names)
117        ));
118    }
119
120    // Positional arguments with something to offer.
121    let useful: Vec<_> = positionals
122        .iter()
123        .filter(|p| !p.values.is_empty() || p.path)
124        .collect();
125    if !useful.is_empty() && !commands.is_empty() {
126        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");
127        if !value_flags.is_empty() {
128            out.push_str(&format!(
129                "            {}) skip=1 ;;\n",
130                value_flags.join("|")
131            ));
132        }
133        out.push_str("            -*) ;;\n            *) pos=$((pos + 1)) ;;\n        esac\n    done\n    case \"$cmd:$pos\" in\n");
134        for positional in useful {
135            for command in commands.iter().filter(|c| positional.available_for(c.name)) {
136                let arm = if positional.values.is_empty() {
137                    "compopt -o filenames 2>/dev/null; COMPREPLY=( $(compgen -f -- \"$cur\") )"
138                        .to_string()
139                } else {
140                    format!(
141                        "COMPREPLY=( $(compgen -W {} -- \"$cur\") )",
142                        quote(&positional.values.join(" "))
143                    )
144                };
145                out.push_str(&format!(
146                    "        {}:{}) {arm} ;;\n",
147                    command.name, positional.index
148                ));
149            }
150        }
151        out.push_str("    esac\n");
152    }
153    out.push_str(&format!(
154        "    return 0\n}}\ncomplete -F {function} {name}\n"
155    ));
156    Ok(out)
157}