Debian Codegraph @

src/engine/complete.rs

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