| 1 | use std::{ |
| 2 | fmt::Write as _, |
| 3 | io::{Error, Write}, |
| 4 | }; |
| 5 | |
| 6 | use clap::{Arg, Command, ValueHint}; |
| 7 | |
| 8 | use crate::generator::{Generator, utils}; |
| 9 | |
| 10 | /// Generate bash completion file |
| 11 | #[derive(Copy, Clone, PartialEq, Eq, Debug)] |
| 12 | pub struct Bash; |
| 13 | |
| 14 | impl Generator for Bash { |
| 15 | fn file_name(&self, name: &str) -> String { |
| 16 | format!("{name}.bash") |
| 17 | } |
| 18 | |
| 19 | fn generate(&self, cmd: &Command, buf: &mut dyn Write) { |
| 20 | self.try_generate(cmd, buf) |
| 21 | .expect("failed to write completion file"); |
| 22 | } |
| 23 | |
| 24 | fn try_generate(&self, cmd: &Command, buf: &mut dyn Write) -> Result<(), Error> { |
| 25 | let bin_name = cmd |
| 26 | .get_bin_name() |
| 27 | .expect("crate::generate should have set the bin_name"); |
| 28 | |
| 29 | let fn_name = bin_name.replace('-', "__"); |
| 30 | |
| 31 | write!( |
| 32 | buf, |
| 33 | "_{name}() {{ |
| 34 | local i cur prev opts cmd |
| 35 | COMPREPLY=() |
| 36 | if [[ \"${{BASH_VERSINFO[0]}}\" -ge 4 ]]; then |
| 37 | cur=\"$2\" |
| 38 | else |
| 39 | cur=\"${{COMP_WORDS[COMP_CWORD]}}\" |
| 40 | fi |
| 41 | prev=\"$3\" |
| 42 | cmd=\"\" |
| 43 | opts=\"\" |
| 44 | |
| 45 | for i in \"${{COMP_WORDS[@]:0:COMP_CWORD}}\" |
| 46 | do |
| 47 | case \"${{cmd}},${{i}}\" in |
| 48 | \",$1\") |
| 49 | cmd=\"{cmd}\" |
| 50 | ;;{subcmds} |
| 51 | *) |
| 52 | ;; |
| 53 | esac |
| 54 | done |
| 55 | |
| 56 | case \"${{cmd}}\" in |
| 57 | {cmd}) |
| 58 | opts=\"{name_opts}\" |
| 59 | if [[ ${{cur}} == -* || ${{COMP_CWORD}} -eq 1 ]] ; then |
| 60 | COMPREPLY=( $(compgen -W \"${{opts}}\" -- \"${{cur}}\") ) |
| 61 | return 0 |
| 62 | fi |
| 63 | case \"${{prev}}\" in{name_opts_details} |
| 64 | *) |
| 65 | COMPREPLY=() |
| 66 | ;; |
| 67 | esac |
| 68 | COMPREPLY=( $(compgen -W \"${{opts}}\" -- \"${{cur}}\") ) |
| 69 | return 0 |
| 70 | ;;{subcmd_details} |
| 71 | esac |
| 72 | }} |
| 73 | |
| 74 | if [[ \"${{BASH_VERSINFO[0]}}\" -eq 4 && \"${{BASH_VERSINFO[1]}}\" -ge 4 || \"${{BASH_VERSINFO[0]}}\" -gt 4 ]]; then |
| 75 | complete -F _{name} -o nosort -o bashdefault -o default {name} |
| 76 | else |
| 77 | complete -F _{name} -o bashdefault -o default {name} |
| 78 | fi |
| 79 | ", |
| 80 | name = bin_name, |
| 81 | cmd = fn_name, |
| 82 | name_opts = all_options_for_path(cmd, bin_name), |
| 83 | name_opts_details = option_details_for_path(cmd, bin_name), |
| 84 | subcmds = all_subcommands(cmd, &fn_name), |
| 85 | subcmd_details = subcommand_details(cmd) |
| 86 | ) |
| 87 | } |
| 88 | } |
| 89 | |
| 90 | fn all_subcommands(cmd: &Command, parent_fn_name: &str) -> String { |
| 91 | debug!("all_subcommands"); |
| 92 | |
| 93 | fn add_command( |
| 94 | parent_fn_name: &str, |
| 95 | cmd: &Command, |
| 96 | subcmds: &mut Vec<(String, String, String)>, |
| 97 | ) { |
| 98 | let fn_name = format!( |
| 99 | "{parent_fn_name}{CMD_SEP}{cmd_name}", |
| 100 | parent_fn_name = parent_fn_name, |
| 101 | cmd_name = cmd.get_name().to_owned().replace('-', CMD_SEP) |
| 102 | ); |
| 103 | subcmds.push(( |
| 104 | parent_fn_name.to_owned(), |
| 105 | cmd.get_name().to_owned(), |
| 106 | fn_name.clone(), |
| 107 | )); |
| 108 | for alias in cmd.get_visible_aliases() { |
| 109 | subcmds.push((parent_fn_name.to_owned(), alias.to_owned(), fn_name.clone())); |
| 110 | } |
| 111 | for subcmd in cmd.get_subcommands() { |
| 112 | add_command(&fn_name, subcmd, subcmds); |
| 113 | } |
| 114 | } |
| 115 | let mut subcmds = vec![]; |
| 116 | for subcmd in cmd.get_subcommands() { |
| 117 | add_command(parent_fn_name, subcmd, &mut subcmds); |
| 118 | } |
| 119 | subcmds.sort(); |
| 120 | |
| 121 | let mut cases = vec![String::new()]; |
| 122 | for (parent_fn_name, name, fn_name) in subcmds { |
| 123 | cases.push(format!( |
| 124 | "{parent_fn_name},{name}) |
| 125 | cmd=\"{fn_name}\" |
| 126 | ;;", |
| 127 | )); |
| 128 | } |
| 129 | |
| 130 | cases.join("\n ") |
| 131 | } |
| 132 | |
| 133 | fn subcommand_details(cmd: &Command) -> String { |
| 134 | debug!("subcommand_details"); |
| 135 | |
| 136 | let mut subcmd_dets = vec![String::new()]; |
| 137 | let mut scs = utils::all_subcommands(cmd) |
| 138 | .iter() |
| 139 | .map(|x| x.1.replace(' ', CMD_SEP)) |
| 140 | .collect::<Vec<_>>(); |
| 141 | |
| 142 | scs.sort(); |
| 143 | scs.dedup(); |
| 144 | |
| 145 | subcmd_dets.extend(scs.iter().map(|sc| { |
| 146 | format!( |
| 147 | "{subcmd}) |
| 148 | opts=\"{sc_opts}\" |
| 149 | if [[ ${{cur}} == -* || ${{COMP_CWORD}} -eq {level} ]] ; then |
| 150 | COMPREPLY=( $(compgen -W \"${{opts}}\" -- \"${{cur}}\") ) |
| 151 | return 0 |
| 152 | fi |
| 153 | case \"${{prev}}\" in{opts_details} |
| 154 | *) |
| 155 | COMPREPLY=() |
| 156 | ;; |
| 157 | esac |
| 158 | COMPREPLY=( $(compgen -W \"${{opts}}\" -- \"${{cur}}\") ) |
| 159 | return 0 |
| 160 | ;;", |
| 161 | subcmd = sc.replace('-', CMD_SEP), |
| 162 | sc_opts = all_options_for_path(cmd, sc), |
| 163 | level = sc.split(CMD_SEP).map(|_| 1).sum::<u64>(), |
| 164 | opts_details = option_details_for_path(cmd, sc) |
| 165 | ) |
| 166 | })); |
| 167 | |
| 168 | subcmd_dets.join("\n ") |
| 169 | } |
| 170 | |
| 171 | fn option_details_for_path(cmd: &Command, path: &str) -> String { |
| 172 | debug!("option_details_for_path: path={path}"); |
| 173 | |
| 174 | let p = utils::find_subcommand_with_path(cmd, path.split(CMD_SEP).skip(1).collect()); |
| 175 | let mut opts = vec![String::new()]; |
| 176 | |
| 177 | for o in p.get_opts() { |
| 178 | let compopt = match o.get_value_hint() { |
| 179 | ValueHint::FilePath => Some("compopt -o filenames"), |
| 180 | ValueHint::DirPath => Some("compopt -o plusdirs"), |
| 181 | ValueHint::Other => Some("compopt -o nospace"), |
| 182 | _ => None, |
| 183 | }; |
| 184 | |
| 185 | if let Some(longs) = o.get_long_and_visible_aliases() { |
| 186 | opts.extend(longs.iter().map(|long| { |
| 187 | let mut v = vec![format!("--{})", long)]; |
| 188 | |
| 189 | if o.get_value_hint() == ValueHint::FilePath { |
| 190 | v.extend([ |
| 191 | "local oldifs".to_owned(), |
| 192 | r#"if [ -n "${IFS+x}" ]; then"#.to_owned(), |
| 193 | r#" oldifs="$IFS""#.to_owned(), |
| 194 | "fi".to_owned(), |
| 195 | r#"IFS=$'\n'"#.to_owned(), |
| 196 | format!("COMPREPLY=({})", vals_for(o)), |
| 197 | r#"if [ -n "${oldifs+x}" ]; then"#.to_owned(), |
| 198 | r#" IFS="$oldifs""#.to_owned(), |
| 199 | "fi".to_owned(), |
| 200 | ]); |
| 201 | } else { |
| 202 | v.push(format!("COMPREPLY=({})", vals_for(o))); |
| 203 | } |
| 204 | |
| 205 | if let Some(copt) = compopt { |
| 206 | v.extend([ |
| 207 | r#"if [[ "${BASH_VERSINFO[0]}" -ge 4 ]]; then"#.to_owned(), |
| 208 | format!(" {copt}"), |
| 209 | "fi".to_owned(), |
| 210 | ]); |
| 211 | } |
| 212 | |
| 213 | v.extend(["return 0", ";;"].iter().map(|s| (*s).to_owned())); |
| 214 | v.join("\n ") |
| 215 | })); |
| 216 | } |
| 217 | |
| 218 | if let Some(shorts) = o.get_short_and_visible_aliases() { |
| 219 | opts.extend(shorts.iter().map(|short| { |
| 220 | let mut v = vec![format!("-{})", short)]; |
| 221 | |
| 222 | if o.get_value_hint() == ValueHint::FilePath { |
| 223 | v.extend([ |
| 224 | "local oldifs".to_owned(), |
| 225 | r#"if [ -n "${IFS+x}" ]; then"#.to_owned(), |
| 226 | r#" oldifs="$IFS""#.to_owned(), |
| 227 | "fi".to_owned(), |
| 228 | r#"IFS=$'\n'"#.to_owned(), |
| 229 | format!("COMPREPLY=({})", vals_for(o)), |
| 230 | r#"if [ -n "${oldifs+x}" ]; then"#.to_owned(), |
| 231 | r#" IFS="$oldifs""#.to_owned(), |
| 232 | "fi".to_owned(), |
| 233 | ]); |
| 234 | } else { |
| 235 | v.push(format!("COMPREPLY=({})", vals_for(o))); |
| 236 | } |
| 237 | |
| 238 | if let Some(copt) = compopt { |
| 239 | v.extend([ |
| 240 | r#"if [[ "${BASH_VERSINFO[0]}" -ge 4 ]]; then"#.to_owned(), |
| 241 | format!(" {copt}"), |
| 242 | "fi".to_owned(), |
| 243 | ]); |
| 244 | } |
| 245 | |
| 246 | v.extend(["return 0", ";;"].iter().map(|s| (*s).to_owned())); |
| 247 | v.join("\n ") |
| 248 | })); |
| 249 | } |
| 250 | } |
| 251 | |
| 252 | opts.join("\n ") |
| 253 | } |
| 254 | |
| 255 | fn vals_for(o: &Arg) -> String { |
| 256 | debug!("vals_for: o={}", o.get_id()); |
| 257 | |
| 258 | if let Some(vals) = utils::possible_values(o) { |
| 259 | format!( |
| 260 | "$(compgen -W \"{}\" -- \"${{cur}}\")", |
| 261 | vals.iter() |
| 262 | .filter(|pv| !pv.is_hide_set()) |
| 263 | .map(|n| n.get_name()) |
| 264 | .collect::<Vec<_>>() |
| 265 | .join(" ") |
| 266 | ) |
| 267 | } else if o.get_value_hint() == ValueHint::DirPath { |
| 268 | String::from("") // should be empty to avoid duplicate candidates |
| 269 | } else if o.get_value_hint() == ValueHint::Other { |
| 270 | String::from("\"${cur}\"") |
| 271 | } else { |
| 272 | String::from("$(compgen -f \"${cur}\")") |
| 273 | } |
| 274 | } |
| 275 | |
| 276 | fn all_options_for_path(cmd: &Command, path: &str) -> String { |
| 277 | debug!("all_options_for_path: path={path}"); |
| 278 | |
| 279 | let p = utils::find_subcommand_with_path(cmd, path.split(CMD_SEP).skip(1).collect()); |
| 280 | |
| 281 | let mut opts = String::new(); |
| 282 | for short in utils::shorts_and_visible_aliases(p) { |
| 283 | write!(&mut opts, "-{short} ").expect("writing to String is infallible"); |
| 284 | } |
| 285 | for long in utils::longs_and_visible_aliases(p) { |
| 286 | write!(&mut opts, "--{long} ").expect("writing to String is infallible"); |
| 287 | } |
| 288 | for pos in p.get_positionals() { |
| 289 | if let Some(vals) = utils::possible_values(pos) { |
| 290 | for value in vals { |
| 291 | write!(&mut opts, "{} ", value.get_name()) |
| 292 | .expect("writing to String is infallible"); |
| 293 | } |
| 294 | } |
| 295 | // A positional without possible values has no literal completion word to |
| 296 | // offer here; emitting its `<NAME>`/`[NAME]` usage placeholder would make |
| 297 | // bash glob-expand the brackets (#6407), so leave it to the `-o default` |
| 298 | // (filename) fallback instead. |
| 299 | } |
| 300 | for (sc, _) in utils::subcommands(p) { |
| 301 | write!(&mut opts, "{sc} ").expect("writing to String is infallible"); |
| 302 | } |
| 303 | opts.pop(); |
| 304 | |
| 305 | opts |
| 306 | } |
| 307 | |
| 308 | const CMD_SEP: &str = "__subcmd__"; |