Skip to content

Commit fc82a3e

Browse files
committed
feat(complete): Support to complete custom external subcommand
1 parent 6a09122 commit fc82a3e

File tree

4 files changed

+85
-5
lines changed

4 files changed

+85
-5
lines changed

clap_complete/src/engine/complete.rs

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ use super::custom::complete_path;
77
use super::ArgValueCandidates;
88
use super::ArgValueCompleter;
99
use super::CompletionCandidate;
10+
use super::SubcommandCandidates;
1011

1112
/// Complete the given command, shell-agnostic
1213
pub fn complete(
@@ -414,10 +415,35 @@ fn complete_subcommand(value: &str, cmd: &clap::Command) -> Vec<CompletionCandid
414415
value
415416
);
416417

417-
subcommands(cmd)
418+
let mut scs: Vec<CompletionCandidate> = subcommands(cmd)
418419
.into_iter()
419420
.filter(|x| x.get_value().starts_with(value))
420-
.collect()
421+
.collect();
422+
if cmd.is_allow_external_subcommands_set() {
423+
let external_completer = cmd.get::<SubcommandCandidates>();
424+
if let Some(completer) = external_completer {
425+
scs.extend(complete_external_subcommand(value, completer));
426+
}
427+
}
428+
429+
scs.sort();
430+
scs.dedup();
431+
scs
432+
}
433+
434+
fn complete_external_subcommand(
435+
value: &str,
436+
completer: &SubcommandCandidates,
437+
) -> Vec<CompletionCandidate> {
438+
debug!("complete_custom_arg_value: completer={completer:?}, value={value:?}");
439+
440+
let mut values = Vec::new();
441+
let custom_arg_values = completer.candidates();
442+
values.extend(custom_arg_values);
443+
444+
values.retain(|comp| comp.get_value().starts_with(value));
445+
446+
values
421447
}
422448

423449
/// Gets all the long options, their visible aliases and flags of a [`clap::Command`] with formatted `--` prefix.

clap_complete/src/engine/custom.rs

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ use std::ffi::OsStr;
33
use std::sync::Arc;
44

55
use clap::builder::ArgExt;
6+
use clap::builder::CommandExt;
67
use clap_lex::OsStrExt as _;
78

89
use super::CompletionCandidate;
@@ -131,8 +132,54 @@ impl std::fmt::Debug for ArgValueCandidates {
131132

132133
impl ArgExt for ArgValueCandidates {}
133134

135+
/// Extend [`Command`][clap::Command] with a [`ValueCandidates`]
136+
///
137+
/// # Example
138+
/// ```rust
139+
/// use clap::Parser;
140+
/// use clap_complete::engine::{SubcommandCandidates, CompletionCandidate};
141+
/// #[derive(Debug, Parser)]
142+
/// #[clap(name = "cli", add = SubcommandCandidates::new(|| { vec![
143+
/// CompletionCandidate::new("foo"),
144+
/// CompletionCandidate::new("bar"),
145+
/// CompletionCandidate::new("baz")] }))]
146+
/// struct Cli {
147+
/// #[arg(long)]
148+
/// input: Option<String>,
149+
/// }
150+
/// ```
151+
#[derive(Clone)]
152+
pub struct SubcommandCandidates(Arc<dyn ValueCandidates>);
153+
154+
impl SubcommandCandidates {
155+
/// Create a new `SubcommandCandidates` with a custom completer
156+
pub fn new<C>(completer: C) -> Self
157+
where
158+
C: ValueCandidates + 'static,
159+
{
160+
Self(Arc::new(completer))
161+
}
162+
163+
/// All potential candidates for an external subcommand.
164+
///
165+
/// See [`CompletionCandidate`] for more information.
166+
pub fn candidates(&self) -> Vec<CompletionCandidate> {
167+
self.0.candidates()
168+
}
169+
}
170+
171+
impl std::fmt::Debug for SubcommandCandidates {
172+
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
173+
f.write_str(type_name::<Self>())
174+
}
175+
}
176+
177+
impl CommandExt for SubcommandCandidates {}
178+
134179
/// User-provided completion candidates for an [`Arg`][clap::Arg], see [`ArgValueCandidates`]
135180
///
181+
/// User-provided completion candidates for an [`Subcommand`][clap::Subcommand], see [`SubcommandCandidates`]
182+
///
136183
/// This is useful when predefined value hints are not enough.
137184
pub trait ValueCandidates: Send + Sync {
138185
/// All potential candidates for an argument.

clap_complete/src/engine/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,5 +11,6 @@ pub use complete::complete;
1111
pub use custom::ArgValueCandidates;
1212
pub use custom::ArgValueCompleter;
1313
pub use custom::PathCompleter;
14+
pub use custom::SubcommandCandidates;
1415
pub use custom::ValueCandidates;
1516
pub use custom::ValueCompleter;

clap_complete/tests/testsuite/engine.rs

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ use std::path::Path;
55

66
use clap::{builder::PossibleValue, Command};
77
use clap_complete::engine::{
8-
ArgValueCandidates, ArgValueCompleter, CompletionCandidate, PathCompleter,
8+
ArgValueCandidates, ArgValueCompleter, CompletionCandidate, PathCompleter, SubcommandCandidates,
99
};
1010
use snapbox::assert_data_eq;
1111

@@ -1080,19 +1080,25 @@ pos_b
10801080
#[test]
10811081
fn suggest_external_subcommand() {
10821082
let mut cmd = Command::new("dynamic")
1083+
.allow_external_subcommands(true)
1084+
.add(SubcommandCandidates::new(|| {
1085+
vec![CompletionCandidate::new("external")]
1086+
}))
10831087
.arg(clap::Arg::new("positional").value_parser(["pos1", "pos2", "pos3"]));
10841088

10851089
assert_data_eq!(
10861090
complete!(cmd, " [TAB]"),
10871091
snapbox::str![
1088-
"--help\tPrint help
1089-
-h\tPrint help
1092+
"external
10901093
pos1
10911094
pos2
10921095
pos3
1096+
--help\tPrint help
10931097
"
10941098
]
10951099
);
1100+
1101+
assert_data_eq!(complete!(cmd, "e[TAB]"), snapbox::str!["external"]);
10961102
}
10971103

10981104
#[test]

0 commit comments

Comments
 (0)