Debian Codegraph @

debian/missing-sources/clap_complete/src/engine/complete.rs

raw
1 use std::ffi::OsStr;
2 use std::ffi::OsString;
3
4 use clap_lex::OsStrExt as _;
5
6 use super::custom::complete_path;
7 use super::ArgValueCandidates;
8 use super::ArgValueCompleter;
9 use super::CompletionCandidate;
10 use super::SubcommandCandidates;
11
12 /// Complete the given command, shell-agnostic
13 pub fn complete(
14 cmd: &mut clap::Command,
15 args: Vec<OsString>,
16 arg_index: usize,
17 current_dir: Option<&std::path::Path>,
18 ) -> Result<Vec<CompletionCandidate>, std::io::Error> {
19 debug!("complete: args={args:?}, arg_index={arg_index:?}, current_dir={current_dir:?}");
20 cmd.build();
21
22 let raw_args = clap_lex::RawArgs::new(args);
23 let mut cursor = raw_args.cursor();
24 let mut target_cursor = raw_args.cursor();
25 raw_args.seek(
26 &mut target_cursor,
27 clap_lex::SeekFrom::Start(arg_index as u64),
28 );
29 // As we loop, `cursor` will always be pointing to the next item
30 raw_args.next_os(&mut target_cursor);
31 debug!("complete: target_cursor={target_cursor:?}");
32
33 // TODO: Multicall support
34 if !cmd.is_no_binary_name_set() {
35 raw_args.next_os(&mut cursor);
36 }
37
38 let mut current_cmd = &*cmd;
39 let mut pos_index = 1;
40 let mut is_escaped = false;
41 let mut next_state = ParseState::ValueDone;
42 while let Some(arg) = raw_args.next(&mut cursor) {
43 let current_state = next_state;
44 next_state = ParseState::ValueDone;
45 debug!(
46 "complete::next: arg={:?}, current_state={current_state:?}, cursor={cursor:?}",
47 arg.to_value_os(),
48 );
49 if cursor == target_cursor {
50 return complete_arg(
51 &arg,
52 current_cmd,
53 current_dir,
54 pos_index,
55 is_escaped,
56 current_state,
57 );
58 }
59
60 if let Ok(value) = arg.to_value() {
61 if let Some(next_cmd) = current_cmd.find_subcommand(value) {
62 current_cmd = next_cmd;
63 pos_index = 1;
64 continue;
65 }
66 }
67
68 if is_escaped {
69 (next_state, pos_index) =
70 parse_positional(current_cmd, pos_index, is_escaped, current_state);
71 } else if arg.is_escape() {
72 is_escaped = true;
73 } else if opt_allows_hyphen(&current_state, &arg) {
74 match current_state {
75 ParseState::Opt((opt, count)) => next_state = parse_opt_value(opt, count),
76 _ => unreachable!("else branch is only reachable in Opt state"),
77 }
78 } else if let Some((flag, value)) = arg.to_long() {
79 if let Ok(flag) = flag {
80 let opt = current_cmd.get_arguments().find(|a| {
81 let longs = a.get_long_and_visible_aliases();
82 let is_find = longs.map(|v| {
83 let mut iter = v.into_iter();
84 let s = iter.find(|s| *s == flag);
85 s.is_some()
86 });
87 is_find.unwrap_or(false)
88 });
89
90 if let Some(opt) = opt {
91 if opt.get_num_args().expect("built").takes_values() && value.is_none() {
92 next_state = ParseState::Opt((opt, 1));
93 };
94 } else if pos_allows_hyphen(current_cmd, pos_index) {
95 (next_state, pos_index) =
96 parse_positional(current_cmd, pos_index, is_escaped, current_state);
97 }
98 }
99 } else if let Some(short) = arg.to_short() {
100 let (_, takes_value_opt, mut short) = parse_shortflags(current_cmd, short);
101 if let Some(opt) = takes_value_opt {
102 if short.next_value_os().is_none() {
103 next_state = ParseState::Opt((opt, 1));
104 }
105 } else if pos_allows_hyphen(current_cmd, pos_index) {
106 (next_state, pos_index) =
107 parse_positional(current_cmd, pos_index, is_escaped, current_state);
108 }
109 } else {
110 match current_state {
111 ParseState::ValueDone | ParseState::Pos(..) => {
112 (next_state, pos_index) =
113 parse_positional(current_cmd, pos_index, is_escaped, current_state);
114 }
115 ParseState::Opt((opt, count)) => next_state = parse_opt_value(opt, count),
116 }
117 }
118 }
119
120 Err(std::io::Error::new(
121 std::io::ErrorKind::Other,
122 "no completion generated",
123 ))
124 }
125
126 #[derive(Debug, PartialEq, Eq, Clone)]
127 enum ParseState<'a> {
128 /// Parsing a value done, there is no state to record.
129 ValueDone,
130
131 /// Parsing a positional argument after `--`. `Pos(pos_index`, `takes_num_args`)
132 Pos((usize, usize)),
133
134 /// Parsing a optional flag argument
135 Opt((&'a clap::Arg, usize)),
136 }
137
138 fn complete_arg(
139 arg: &clap_lex::ParsedArg<'_>,
140 cmd: &clap::Command,
141 current_dir: Option<&std::path::Path>,
142 pos_index: usize,
143 is_escaped: bool,
144 state: ParseState<'_>,
145 ) -> Result<Vec<CompletionCandidate>, std::io::Error> {
146 debug!(
147 "complete_arg: arg={:?}, cmd={:?}, current_dir={:?}, pos_index={:?}, state={:?}",
148 arg,
149 cmd.get_name(),
150 current_dir,
151 pos_index,
152 state
153 );
154 let mut completions = Vec::<CompletionCandidate>::new();
155
156 match state {
157 ParseState::ValueDone => {
158 if let Ok(value) = arg.to_value() {
159 completions.extend(complete_subcommand(value, cmd));
160 }
161
162 if let Some(positional) = cmd
163 .get_positionals()
164 .find(|p| p.get_index() == Some(pos_index))
165 {
166 completions.extend(complete_arg_value(arg.to_value(), positional, current_dir));
167 }
168 if !is_escaped {
169 completions.extend(complete_option(arg, cmd, current_dir));
170 }
171 }
172 ParseState::Pos((_, num_arg)) => {
173 if let Some(positional) = cmd
174 .get_positionals()
175 .find(|p| p.get_index() == Some(pos_index))
176 {
177 completions.extend(complete_arg_value(arg.to_value(), positional, current_dir));
178 if positional
179 .get_num_args()
180 .is_some_and(|num_args| num_arg >= num_args.min_values())
181 {
182 completions.extend(complete_option(arg, cmd, current_dir));
183 }
184 }
185 }
186 ParseState::Opt((opt, count)) => {
187 completions.extend(complete_arg_value(arg.to_value(), opt, current_dir));
188 let min = opt.get_num_args().map(|r| r.min_values()).unwrap_or(0);
189 if count > min {
190 // Also complete this raw_arg as a positional argument, flags, options and subcommand.
191 completions.extend(complete_arg(
192 arg,
193 cmd,
194 current_dir,
195 pos_index,
196 is_escaped,
197 ParseState::ValueDone,
198 )?);
199 }
200 }
201 }
202 if completions.iter().any(|a| !a.is_hide_set()) {
203 completions.retain(|a| !a.is_hide_set());
204 }
205 let mut seen_ids = std::collections::HashSet::new();
206 completions.retain(move |a| {
207 if let Some(id) = a.get_id().cloned() {
208 seen_ids.insert(id)
209 } else {
210 true
211 }
212 });
213
214 let mut tags = Vec::new();
215 for candidate in &completions {
216 let tag = candidate.get_tag().cloned();
217 if !tags.contains(&tag) {
218 tags.push(tag);
219 }
220 }
221 completions.sort_by_key(|c| {
222 (
223 tags.iter().position(|t| c.get_tag() == t.as_ref()),
224 c.get_display_order(),
225 )
226 });
227
228 Ok(completions)
229 }
230
231 fn complete_option(
232 arg: &clap_lex::ParsedArg<'_>,
233 cmd: &clap::Command,
234 current_dir: Option<&std::path::Path>,
235 ) -> Vec<CompletionCandidate> {
236 let mut completions = Vec::<CompletionCandidate>::new();
237 if arg.is_empty() {
238 completions.extend(longs_and_visible_aliases(cmd));
239 completions.extend(hidden_longs_aliases(cmd));
240
241 let dash_or_arg = if arg.is_empty() {
242 "-".into()
243 } else {
244 arg.to_value_os().to_string_lossy()
245 };
246 completions.extend(
247 shorts_and_visible_aliases(cmd)
248 .into_iter()
249 .map(|comp| comp.add_prefix(dash_or_arg.to_string())),
250 );
251 } else if arg.is_stdio() {
252 // HACK: Assuming knowledge of is_stdio
253 let dash_or_arg = if arg.is_empty() {
254 "-".into()
255 } else {
256 arg.to_value_os().to_string_lossy()
257 };
258 completions.extend(
259 shorts_and_visible_aliases(cmd)
260 .into_iter()
261 .map(|comp| comp.add_prefix(dash_or_arg.to_string())),
262 );
263
264 completions.extend(longs_and_visible_aliases(cmd));
265 completions.extend(hidden_longs_aliases(cmd));
266 } else if arg.is_escape() {
267 // HACK: Assuming knowledge of is_escape
268 completions.extend(longs_and_visible_aliases(cmd));
269 completions.extend(hidden_longs_aliases(cmd));
270 } else if let Some((flag, value)) = arg.to_long() {
271 if let Ok(flag) = flag {
272 if let Some(value) = value {
273 if let Some(arg) = cmd.get_arguments().find(|a| a.get_long() == Some(flag)) {
274 completions.extend(
275 complete_arg_value(value.to_str().ok_or(value), arg, current_dir)
276 .into_iter()
277 .map(|comp| comp.add_prefix(format!("--{flag}="))),
278 );
279 }
280 } else {
281 completions.extend(
282 longs_and_visible_aliases(cmd)
283 .into_iter()
284 .filter(|comp| comp.get_value().starts_with(format!("--{flag}").as_str())),
285 );
286 completions.extend(
287 hidden_longs_aliases(cmd)
288 .into_iter()
289 .filter(|comp| comp.get_value().starts_with(format!("--{flag}").as_str())),
290 );
291 }
292 }
293 } else if let Some(short) = arg.to_short() {
294 if !short.is_negative_number() {
295 // Find the first takes_values option.
296 let (leading_flags, takes_value_opt, mut short) = parse_shortflags(cmd, short);
297
298 // Clone `short` to `peek_short` to peek whether the next flag is a `=`.
299 if let Some(opt) = takes_value_opt {
300 let mut peek_short = short.clone();
301 let has_equal = if let Some(Ok('=')) = peek_short.next_flag() {
302 short.next_flag();
303 true
304 } else {
305 false
306 };
307
308 let value = short.next_value_os().unwrap_or(OsStr::new(""));
309 completions.extend(
310 complete_arg_value(value.to_str().ok_or(value), opt, current_dir)
311 .into_iter()
312 .map(|comp| {
313 let sep = if has_equal { "=" } else { "" };
314 comp.add_prefix(format!("-{leading_flags}{sep}"))
315 }),
316 );
317 } else {
318 completions.extend(
319 shorts_and_visible_aliases(cmd)
320 .into_iter()
321 .map(|comp| comp.add_prefix(format!("-{leading_flags}"))),
322 );
323 }
324 }
325 }
326 completions
327 }
328
329 fn complete_arg_value(
330 value: Result<&str, &OsStr>,
331 arg: &clap::Arg,
332 current_dir: Option<&std::path::Path>,
333 ) -> Vec<CompletionCandidate> {
334 let mut values = Vec::new();
335 debug!("complete_arg_value: arg={arg:?}, value={value:?}");
336
337 let (prefix, value) =
338 rsplit_delimiter(value, arg.get_value_delimiter()).unwrap_or((None, value));
339
340 let value_os = match value {
341 Ok(value) => OsStr::new(value),
342 Err(value_os) => value_os,
343 };
344
345 if let Some(completer) = arg.get::<ArgValueCompleter>() {
346 values.extend(completer.complete(value_os));
347 } else if let Some(completer) = arg.get::<ArgValueCandidates>() {
348 values.extend(complete_custom_arg_value(value_os, completer));
349 } else if let Some(possible_values) = possible_values(arg) {
350 if let Ok(value) = value {
351 values.extend(possible_values.into_iter().filter_map(|p| {
352 let name = p.get_name();
353 name.starts_with(value).then(|| {
354 CompletionCandidate::new(OsString::from(name))
355 .help(p.get_help().cloned())
356 .hide(p.is_hide_set())
357 })
358 }));
359 }
360 } else {
361 match arg.get_value_hint() {
362 clap::ValueHint::Unknown | clap::ValueHint::Other => {
363 // Should not complete
364 }
365 clap::ValueHint::AnyPath => {
366 values.extend(complete_path(value_os, current_dir, &|_| true));
367 }
368 clap::ValueHint::FilePath => {
369 values.extend(complete_path(value_os, current_dir, &|p| p.is_file()));
370 }
371 clap::ValueHint::DirPath => {
372 values.extend(complete_path(value_os, current_dir, &|p| p.is_dir()));
373 }
374 clap::ValueHint::ExecutablePath => {
375 use is_executable::IsExecutable;
376 values.extend(complete_path(value_os, current_dir, &|p| p.is_executable()));
377 }
378 clap::ValueHint::CommandName
379 | clap::ValueHint::CommandString
380 | clap::ValueHint::CommandWithArguments
381 | clap::ValueHint::Username
382 | clap::ValueHint::Hostname
383 | clap::ValueHint::Url
384 | clap::ValueHint::EmailAddress => {
385 // No completion implementation
386 }
387 _ => {
388 // Safe-ish fallback
389 values.extend(complete_path(value_os, current_dir, &|_| true));
390 }
391 }
392
393 values.sort();
394 }
395
396 if let Some(prefix) = prefix {
397 values = values
398 .into_iter()
399 .map(|comp| comp.add_prefix(prefix))
400 .collect();
401 }
402 values = values
403 .into_iter()
404 .map(|comp| {
405 if comp.get_tag().is_some() {
406 comp
407 } else {
408 comp.tag(Some(arg.to_string().into()))
409 }
410 })
411 .collect();
412
413 values
414 }
415
416 fn rsplit_delimiter<'s, 'o>(
417 value: Result<&'s str, &'o OsStr>,
418 delimiter: Option<char>,
419 ) -> Option<(Option<&'s str>, Result<&'s str, &'o OsStr>)> {
420 let delimiter = delimiter?;
421 let value = value.ok()?;
422 let pos = value.rfind(delimiter)?;
423 let (prefix, value) = value.split_at(pos + delimiter.len_utf8());
424 Some((Some(prefix), Ok(value)))
425 }
426
427 fn complete_custom_arg_value(
428 value: &OsStr,
429 completer: &ArgValueCandidates,
430 ) -> Vec<CompletionCandidate> {
431 debug!("complete_custom_arg_value: completer={completer:?}, value={value:?}");
432
433 let mut values = completer.candidates();
434 values.retain(|comp| comp.get_value().starts_with(&value.to_string_lossy()));
435 values
436 }
437
438 fn complete_subcommand(value: &str, cmd: &clap::Command) -> Vec<CompletionCandidate> {
439 debug!(
440 "complete_subcommand: cmd={:?}, value={:?}",
441 cmd.get_name(),
442 value
443 );
444
445 let mut scs: Vec<CompletionCandidate> = subcommands(cmd)
446 .into_iter()
447 .filter(|x| x.get_value().starts_with(value))
448 .collect();
449 if cmd.is_allow_external_subcommands_set() {
450 let external_completer = cmd.get::<SubcommandCandidates>();
451 if let Some(completer) = external_completer {
452 scs.extend(complete_external_subcommand(value, completer));
453 }
454 }
455
456 scs.sort();
457 scs.dedup();
458 scs
459 }
460
461 fn complete_external_subcommand(
462 value: &str,
463 completer: &SubcommandCandidates,
464 ) -> Vec<CompletionCandidate> {
465 debug!("complete_custom_arg_value: completer={completer:?}, value={value:?}");
466
467 let mut values = Vec::new();
468 let custom_arg_values = completer.candidates();
469 values.extend(custom_arg_values);
470
471 values.retain(|comp| comp.get_value().starts_with(value));
472
473 values
474 }
475
476 /// Gets all the long options, their visible aliases and flags of a [`clap::Command`] with formatted `--` prefix.
477 /// Includes `help` and `version` depending on the [`clap::Command`] settings.
478 fn longs_and_visible_aliases(p: &clap::Command) -> Vec<CompletionCandidate> {
479 debug!("longs: name={}", p.get_name());
480
481 p.get_arguments()
482 .filter_map(|a| {
483 a.get_long_and_visible_aliases().map(|longs| {
484 longs
485 .into_iter()
486 .map(|s| populate_arg_candidate(CompletionCandidate::new(format!("--{s}")), a))
487 })
488 })
489 .flatten()
490 .collect()
491 }
492
493 /// Gets all the long hidden aliases and flags of a [`clap::Command`].
494 fn hidden_longs_aliases(p: &clap::Command) -> Vec<CompletionCandidate> {
495 debug!("longs: name={}", p.get_name());
496
497 p.get_arguments()
498 .filter_map(|a| {
499 a.get_aliases().map(|longs| {
500 longs.into_iter().map(|s| {
501 populate_arg_candidate(CompletionCandidate::new(format!("--{s}")), a).hide(true)
502 })
503 })
504 })
505 .flatten()
506 .collect()
507 }
508
509 /// Gets all the short options, their visible aliases and flags of a [`clap::Command`].
510 /// Includes `h` and `V` depending on the [`clap::Command`] settings.
511 fn shorts_and_visible_aliases(p: &clap::Command) -> Vec<CompletionCandidate> {
512 debug!("shorts: name={}", p.get_name());
513
514 p.get_arguments()
515 .filter_map(|a| {
516 a.get_short_and_visible_aliases().map(|shorts| {
517 shorts.into_iter().map(|s| {
518 populate_arg_candidate(CompletionCandidate::new(s.to_string()), a).help(
519 a.get_help()
520 .cloned()
521 .or_else(|| a.get_long().map(|long| format!("--{long}").into())),
522 )
523 })
524 })
525 })
526 .flatten()
527 .collect()
528 }
529
530 fn populate_arg_candidate(candidate: CompletionCandidate, arg: &clap::Arg) -> CompletionCandidate {
531 candidate
532 .help(arg.get_help().cloned())
533 .id(Some(format!("arg::{}", arg.get_id())))
534 .tag(Some(
535 arg.get_help_heading()
536 .unwrap_or("Options")
537 .to_owned()
538 .into(),
539 ))
540 .display_order(Some(arg.get_display_order()))
541 .hide(arg.is_hide_set())
542 }
543
544 /// Get the possible values for completion
545 fn possible_values(a: &clap::Arg) -> Option<Vec<clap::builder::PossibleValue>> {
546 if !a.get_num_args().expect("built").takes_values() {
547 None
548 } else {
549 a.get_value_parser()
550 .possible_values()
551 .map(|pvs| pvs.collect())
552 }
553 }
554
555 /// Gets subcommands of [`clap::Command`] in the form of `("name", "bin_name")`.
556 ///
557 /// Subcommand `rustup toolchain install` would be converted to
558 /// `("install", "rustup toolchain install")`.
559 fn subcommands(p: &clap::Command) -> Vec<CompletionCandidate> {
560 debug!("subcommands: name={}", p.get_name());
561 debug!("subcommands: Has subcommands...{:?}", p.has_subcommands());
562 p.get_subcommands()
563 .flat_map(|sc| {
564 sc.get_name_and_visible_aliases()
565 .into_iter()
566 .map(|s| populate_command_candidate(CompletionCandidate::new(s.to_string()), p, sc))
567 .chain(sc.get_aliases().map(|s| {
568 populate_command_candidate(CompletionCandidate::new(s.to_string()), p, sc)
569 .hide(true)
570 }))
571 })
572 .collect()
573 }
574
575 fn populate_command_candidate(
576 candidate: CompletionCandidate,
577 cmd: &clap::Command,
578 subcommand: &clap::Command,
579 ) -> CompletionCandidate {
580 candidate
581 .help(subcommand.get_about().cloned())
582 .id(Some(format!("command::{}", subcommand.get_name())))
583 .tag(Some(
584 cmd.get_subcommand_help_heading()
585 .unwrap_or("Commands")
586 .to_owned()
587 .into(),
588 ))
589 .display_order(Some(subcommand.get_display_order()))
590 .hide(subcommand.is_hide_set())
591 }
592
593 /// Parse the short flags and find the first `takes_values` option.
594 fn parse_shortflags<'c, 's>(
595 cmd: &'c clap::Command,
596 mut short: clap_lex::ShortFlags<'s>,
597 ) -> (String, Option<&'c clap::Arg>, clap_lex::ShortFlags<'s>) {
598 let takes_value_opt;
599 let mut leading_flags = String::new();
600 // Find the first takes_values option.
601 loop {
602 match short.next_flag() {
603 Some(Ok(opt)) => {
604 leading_flags.push(opt);
605 let opt = cmd.get_arguments().find(|a| {
606 let shorts = a.get_short_and_visible_aliases();
607 let is_find = shorts.map(|v| {
608 let mut iter = v.into_iter();
609 let c = iter.find(|c| *c == opt);
610 c.is_some()
611 });
612 is_find.unwrap_or(false)
613 });
614 if opt
615 .map(|o| o.get_num_args().expect("built").takes_values())
616 .unwrap_or(false)
617 {
618 takes_value_opt = opt;
619 break;
620 }
621 }
622 Some(Err(_)) | None => {
623 takes_value_opt = None;
624 break;
625 }
626 }
627 }
628
629 (leading_flags, takes_value_opt, short)
630 }
631
632 /// Parse the positional arguments. Return the new state and the new positional index.
633 fn parse_positional<'a>(
634 cmd: &clap::Command,
635 pos_index: usize,
636 is_escaped: bool,
637 state: ParseState<'a>,
638 ) -> (ParseState<'a>, usize) {
639 let pos_arg = cmd
640 .get_positionals()
641 .find(|p| p.get_index() == Some(pos_index));
642 let num_args = pos_arg
643 .and_then(|a| a.get_num_args().map(|r| r.max_values()))
644 .unwrap_or(1);
645
646 let update_state_with_new_positional = |pos_index| -> (ParseState<'a>, usize) {
647 if num_args > 1 {
648 (ParseState::Pos((pos_index, 1)), pos_index)
649 } else {
650 if is_escaped {
651 (ParseState::Pos((pos_index, 1)), pos_index + 1)
652 } else {
653 (ParseState::ValueDone, pos_index + 1)
654 }
655 }
656 };
657 match state {
658 ParseState::ValueDone => {
659 update_state_with_new_positional(pos_index)
660 },
661 ParseState::Pos((prev_pos_index, num_arg)) => {
662 if prev_pos_index == pos_index {
663 if num_arg + 1 < num_args {
664 (ParseState::Pos((pos_index, num_arg + 1)), pos_index)
665 } else {
666 if is_escaped {
667 (ParseState::Pos((pos_index, 1)), pos_index + 1)
668 } else {
669 (ParseState::ValueDone, pos_index + 1)
670 }
671 }
672 } else {
673 update_state_with_new_positional(pos_index)
674 }
675 }
676 ParseState::Opt(..) => unreachable!(
677 "This branch won't be hit,
678 because ParseState::Opt should not be seen as a positional argument and passed to this function."
679 ),
680 }
681 }
682
683 /// Parse optional flag argument. Return new state
684 fn parse_opt_value(opt: &clap::Arg, count: usize) -> ParseState<'_> {
685 let range = opt.get_num_args().expect("built");
686 let max = range.max_values();
687 if count < max {
688 ParseState::Opt((opt, count + 1))
689 } else {
690 ParseState::ValueDone
691 }
692 }
693
694 fn pos_allows_hyphen(cmd: &clap::Command, pos_index: usize) -> bool {
695 cmd.get_positionals()
696 .find(|a| a.get_index() == Some(pos_index))
697 .map(|p| p.is_allow_hyphen_values_set())
698 .unwrap_or(false)
699 }
700
701 fn opt_allows_hyphen(state: &ParseState<'_>, arg: &clap_lex::ParsedArg<'_>) -> bool {
702 let val = arg.to_value_os();
703 if val.starts_with("-") {
704 if let ParseState::Opt((opt, _)) = state {
705 return opt.is_allow_hyphen_values_set();
706 }
707 }
708
709 false
710 }