Debian Codegraph @

debian/rust-vendor/clap_complete/src/aot/shells/bash.rs

raw
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 "_{fn_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 _{fn_name} -o nosort -o bashdefault -o default {name}
76 else
77 complete -F _{fn_name} -o bashdefault -o default {name}
78 fi
79 ",
80 name = bin_name,
81 fn_name = fn_name,
82 cmd = fn_name,
83 name_opts = all_options_for_path(cmd, bin_name),
84 name_opts_details = option_details_for_path(cmd, bin_name),
85 subcmds = all_subcommands(cmd, &fn_name),
86 subcmd_details = subcommand_details(cmd)
87 )
88 }
89 }
90
91 fn all_subcommands(cmd: &Command, parent_fn_name: &str) -> String {
92 debug!("all_subcommands");
93
94 fn add_command(
95 parent_fn_name: &str,
96 cmd: &Command,
97 subcmds: &mut Vec<(String, String, String)>,
98 ) {
99 let fn_name = format!(
100 "{parent_fn_name}{CMD_SEP}{cmd_name}",
101 parent_fn_name = parent_fn_name,
102 cmd_name = cmd.get_name().to_owned().replace('-', CMD_SEP)
103 );
104 subcmds.push((
105 parent_fn_name.to_owned(),
106 cmd.get_name().to_owned(),
107 fn_name.clone(),
108 ));
109 for alias in cmd.get_visible_aliases() {
110 subcmds.push((parent_fn_name.to_owned(), alias.to_owned(), fn_name.clone()));
111 }
112 for subcmd in cmd.get_subcommands() {
113 add_command(&fn_name, subcmd, subcmds);
114 }
115 }
116 let mut subcmds = vec![];
117 for subcmd in cmd.get_subcommands() {
118 add_command(parent_fn_name, subcmd, &mut subcmds);
119 }
120 subcmds.sort();
121
122 let mut cases = vec![String::new()];
123 for (parent_fn_name, name, fn_name) in subcmds {
124 cases.push(format!(
125 "{parent_fn_name},{name})
126 cmd=\"{fn_name}\"
127 ;;",
128 ));
129 }
130
131 cases.join("\n ")
132 }
133
134 fn subcommand_details(cmd: &Command) -> String {
135 debug!("subcommand_details");
136
137 let mut subcmd_dets = vec![String::new()];
138 let mut scs = utils::all_subcommands(cmd)
139 .iter()
140 .map(|x| x.1.replace(' ', CMD_SEP))
141 .collect::<Vec<_>>();
142
143 scs.sort();
144 scs.dedup();
145
146 subcmd_dets.extend(scs.iter().map(|sc| {
147 format!(
148 "{subcmd})
149 opts=\"{sc_opts}\"
150 if [[ ${{cur}} == -* || ${{COMP_CWORD}} -eq {level} ]] ; then
151 COMPREPLY=( $(compgen -W \"${{opts}}\" -- \"${{cur}}\") )
152 return 0
153 fi
154 case \"${{prev}}\" in{opts_details}
155 *)
156 COMPREPLY=()
157 ;;
158 esac
159 COMPREPLY=( $(compgen -W \"${{opts}}\" -- \"${{cur}}\") )
160 return 0
161 ;;",
162 subcmd = sc.replace('-', CMD_SEP),
163 sc_opts = all_options_for_path(cmd, sc),
164 level = sc.split(CMD_SEP).map(|_| 1).sum::<u64>(),
165 opts_details = option_details_for_path(cmd, sc)
166 )
167 }));
168
169 subcmd_dets.join("\n ")
170 }
171
172 fn option_details_for_path(cmd: &Command, path: &str) -> String {
173 debug!("option_details_for_path: path={path}");
174
175 let p = utils::find_subcommand_with_path(cmd, path.split(CMD_SEP).skip(1).collect());
176 let mut opts = vec![String::new()];
177
178 for o in p.get_opts() {
179 let compopt = match o.get_value_hint() {
180 ValueHint::FilePath => Some("compopt -o filenames"),
181 ValueHint::DirPath => Some("compopt -o plusdirs"),
182 ValueHint::Other => Some("compopt -o nospace"),
183 _ => None,
184 };
185
186 if let Some(longs) = o.get_long_and_visible_aliases() {
187 opts.extend(longs.iter().map(|long| {
188 let mut v = vec![format!("--{})", long)];
189
190 if o.get_value_hint() == ValueHint::FilePath {
191 v.extend([
192 "local oldifs".to_owned(),
193 r#"if [ -n "${IFS+x}" ]; then"#.to_owned(),
194 r#" oldifs="$IFS""#.to_owned(),
195 "fi".to_owned(),
196 r#"IFS=$'\n'"#.to_owned(),
197 format!("COMPREPLY=({})", vals_for(o)),
198 r#"if [ -n "${oldifs+x}" ]; then"#.to_owned(),
199 r#" IFS="$oldifs""#.to_owned(),
200 "fi".to_owned(),
201 ]);
202 } else {
203 v.push(format!("COMPREPLY=({})", vals_for(o)));
204 }
205
206 if let Some(copt) = compopt {
207 v.extend([
208 r#"if [[ "${BASH_VERSINFO[0]}" -ge 4 ]]; then"#.to_owned(),
209 format!(" {copt}"),
210 "fi".to_owned(),
211 ]);
212 }
213
214 v.extend(["return 0", ";;"].iter().map(|s| (*s).to_owned()));
215 v.join("\n ")
216 }));
217 }
218
219 if let Some(shorts) = o.get_short_and_visible_aliases() {
220 opts.extend(shorts.iter().map(|short| {
221 let mut v = vec![format!("-{})", short)];
222
223 if o.get_value_hint() == ValueHint::FilePath {
224 v.extend([
225 "local oldifs".to_owned(),
226 r#"if [ -n "${IFS+x}" ]; then"#.to_owned(),
227 r#" oldifs="$IFS""#.to_owned(),
228 "fi".to_owned(),
229 r#"IFS=$'\n'"#.to_owned(),
230 format!("COMPREPLY=({})", vals_for(o)),
231 r#"if [ -n "${oldifs+x}" ]; then"#.to_owned(),
232 r#" IFS="$oldifs""#.to_owned(),
233 "fi".to_owned(),
234 ]);
235 } else {
236 v.push(format!("COMPREPLY=({})", vals_for(o)));
237 }
238
239 if let Some(copt) = compopt {
240 v.extend([
241 r#"if [[ "${BASH_VERSINFO[0]}" -ge 4 ]]; then"#.to_owned(),
242 format!(" {copt}"),
243 "fi".to_owned(),
244 ]);
245 }
246
247 v.extend(["return 0", ";;"].iter().map(|s| (*s).to_owned()));
248 v.join("\n ")
249 }));
250 }
251 }
252
253 opts.join("\n ")
254 }
255
256 fn vals_for(o: &Arg) -> String {
257 debug!("vals_for: o={}", o.get_id());
258
259 if let Some(vals) = utils::possible_values(o) {
260 format!(
261 "$(compgen -W \"{}\" -- \"${{cur}}\")",
262 vals.iter()
263 .filter(|pv| !pv.is_hide_set())
264 .map(|n| n.get_name())
265 .collect::<Vec<_>>()
266 .join(" ")
267 )
268 } else if o.get_value_hint() == ValueHint::DirPath {
269 String::from("") // should be empty to avoid duplicate candidates
270 } else if o.get_value_hint() == ValueHint::Other {
271 String::from("\"${cur}\"")
272 } else {
273 String::from("$(compgen -f \"${cur}\")")
274 }
275 }
276
277 fn all_options_for_path(cmd: &Command, path: &str) -> String {
278 debug!("all_options_for_path: path={path}");
279
280 let p = utils::find_subcommand_with_path(cmd, path.split(CMD_SEP).skip(1).collect());
281
282 let mut opts = String::new();
283 for short in utils::shorts_and_visible_aliases(p) {
284 write!(&mut opts, "-{short} ").expect("writing to String is infallible");
285 }
286 for long in utils::longs_and_visible_aliases(p) {
287 write!(&mut opts, "--{long} ").expect("writing to String is infallible");
288 }
289 for pos in p.get_positionals() {
290 if let Some(vals) = utils::possible_values(pos) {
291 for value in vals {
292 write!(&mut opts, "{} ", value.get_name())
293 .expect("writing to String is infallible");
294 }
295 }
296 // A positional without possible values has no literal completion word to
297 // offer here; emitting its `<NAME>`/`[NAME]` usage placeholder would make
298 // bash glob-expand the brackets (#6407), so leave it to the `-o default`
299 // (filename) fallback instead.
300 }
301 for (sc, _) in utils::subcommands(p) {
302 write!(&mut opts, "{sc} ").expect("writing to String is infallible");
303 }
304 opts.pop();
305
306 opts
307 }
308
309 const CMD_SEP: &str = "__subcmd__";