Skip to content

Commit 747dd4c

Browse files
committed
feat(complete): Support to complete custom external subcommand
1 parent 7abe2bf commit 747dd4c

File tree

6 files changed

+102
-2
lines changed

6 files changed

+102
-2
lines changed

clap_builder/src/builder/command.rs

+24
Original file line numberDiff line numberDiff line change
@@ -1039,6 +1039,14 @@ impl Command {
10391039

10401040
Usage::new(self).create_usage_with_title(&[])
10411041
}
1042+
1043+
/// Extend [`Command`] with [`CommandExt`] data
1044+
#[cfg(feature = "unstable-ext")]
1045+
#[allow(clippy::should_implement_trait)]
1046+
pub fn add<T: CommandExt + crate::builder::ext::Extension>(mut self, tagged: T) -> Self {
1047+
self.app_ext.set(tagged);
1048+
self
1049+
}
10421050
}
10431051

10441052
/// # Application-wide Settings
@@ -3958,6 +3966,18 @@ impl Command {
39583966
pub fn is_multicall_set(&self) -> bool {
39593967
self.is_set(AppSettings::Multicall)
39603968
}
3969+
3970+
/// Access an [`CommandExt`]
3971+
#[cfg(feature = "unstable-ext")]
3972+
pub fn get<T: CommandExt + crate::builder::ext::Extension>(&self) -> Option<&T> {
3973+
self.app_ext.get::<T>()
3974+
}
3975+
3976+
/// Remove an [`CommandExt`]
3977+
#[cfg(feature = "unstable-ext")]
3978+
pub fn remove<T: CommandExt + crate::builder::ext::Extension>(mut self) -> Option<T> {
3979+
self.app_ext.remove::<T>()
3980+
}
39613981
}
39623982

39633983
// Internally used only
@@ -4921,6 +4941,10 @@ struct MaxTermWidth(usize);
49214941

49224942
impl AppTag for MaxTermWidth {}
49234943

4944+
/// User-provided data that can be attached to an [`Command`]
4945+
#[cfg(feature = "unstable-ext")]
4946+
pub trait CommandExt: crate::builder::ext::Extension {}
4947+
49244948
fn two_elements_of<I, T>(mut iter: I) -> Option<(T, T)>
49254949
where
49264950
I: Iterator<Item = T>,

clap_builder/src/builder/mod.rs

+1
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ pub use arg::ArgExt;
3333
pub use arg_group::ArgGroup;
3434
pub use arg_predicate::ArgPredicate;
3535
pub use command::Command;
36+
pub use command::CommandExt;
3637
pub use os_str::OsStr;
3738
pub use possible_value::PossibleValue;
3839
pub use range::ValueRange;

clap_complete/src/engine/complete.rs

+21
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(
@@ -363,11 +364,31 @@ fn complete_subcommand(value: &str, cmd: &clap::Command) -> Vec<CompletionCandid
363364
.into_iter()
364365
.filter(|x| x.get_value().starts_with(value))
365366
.collect::<Vec<_>>();
367+
368+
let external_completer = cmd.get::<SubcommandCandidates>();
369+
if let Some(completer) = external_completer {
370+
scs.extend(complete_external_subcommand(value, completer));
371+
}
366372
scs.sort();
367373
scs.dedup();
368374
scs
369375
}
370376

377+
fn complete_external_subcommand(
378+
value: &str,
379+
completer: &SubcommandCandidates,
380+
) -> Vec<CompletionCandidate> {
381+
debug!("complete_custom_arg_value: completer={completer:?}, value={value:?}");
382+
383+
let mut values = Vec::new();
384+
let custom_arg_values = completer.candidates();
385+
values.extend(custom_arg_values);
386+
387+
values.retain(|comp| comp.get_value().starts_with(value));
388+
389+
values
390+
}
391+
371392
/// Gets all the long options, their visible aliases and flags of a [`clap::Command`] with formatted `--` prefix.
372393
/// Includes `help` and `version` depending on the [`clap::Command`] settings.
373394
fn longs_and_visible_aliases(p: &clap::Command) -> Vec<CompletionCandidate> {

clap_complete/src/engine/custom.rs

+47
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;
@@ -52,8 +53,54 @@ impl std::fmt::Debug for ArgValueCandidates {
5253

5354
impl ArgExt for ArgValueCandidates {}
5455

56+
/// Extend [`Command`][clap::Command] with a [`ValueCandidates`]
57+
///
58+
/// # Example
59+
/// ```rust
60+
/// use clap::Parser;
61+
/// use clap_complete::engine::{SubcommandCandidates, CompletionCandidate};
62+
/// #[derive(Debug, Parser)]
63+
/// #[clap(name = "cli", add = SubcommandCandidates::new(|| { vec![
64+
/// CompletionCandidate::new("foo"),
65+
/// CompletionCandidate::new("bar"),
66+
/// CompletionCandidate::new("baz")] }))]
67+
/// struct Cli {
68+
/// #[arg(long)]
69+
/// input: Option<String>,
70+
/// }
71+
/// ```
72+
#[derive(Clone)]
73+
pub struct SubcommandCandidates(Arc<dyn ValueCandidates>);
74+
75+
impl SubcommandCandidates {
76+
/// Create a new `SubcommandCandidates` with a custom completer
77+
pub fn new<C>(completer: C) -> Self
78+
where
79+
C: ValueCandidates + 'static,
80+
{
81+
Self(Arc::new(completer))
82+
}
83+
84+
/// All potential candidates for an external subcommand.
85+
///
86+
/// See [`CompletionCandidate`] for more information.
87+
pub fn candidates(&self) -> Vec<CompletionCandidate> {
88+
self.0.candidates()
89+
}
90+
}
91+
92+
impl std::fmt::Debug for SubcommandCandidates {
93+
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
94+
f.write_str(type_name::<Self>())
95+
}
96+
}
97+
98+
impl CommandExt for SubcommandCandidates {}
99+
55100
/// User-provided completion candidates for an [`Arg`][clap::Arg], see [`ArgValueCandidates`]
56101
///
102+
/// User-provided completion candidates for an [`Subcommand`][clap::Subcommand], see [`SubcommandCandidates`]
103+
///
57104
/// This is useful when predefined value hints are not enough.
58105
pub trait ValueCandidates: Send + Sync {
59106
/// All potential candidates for an argument.

clap_complete/src/engine/mod.rs

+1
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

+8-2
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

@@ -984,7 +984,10 @@ a_pos,c_pos"
984984
#[test]
985985
fn suggest_external_subcommand() {
986986
let mut cmd = Command::new("dynamic")
987-
.arg(clap::Arg::new("positional").value_parser(["pos1", "pos2", "pos3"]));
987+
.arg(clap::Arg::new("positional").value_parser(["pos1", "pos2", "pos3"]))
988+
.add(SubcommandCandidates::new(|| {
989+
vec![CompletionCandidate::new("external")]
990+
}));
988991

989992
assert_data_eq!(
990993
complete!(cmd, " [TAB]"),
@@ -994,9 +997,12 @@ fn suggest_external_subcommand() {
994997
pos1
995998
pos2
996999
pos3
1000+
external
9971001
"
9981002
]
9991003
);
1004+
1005+
assert_data_eq!(complete!(cmd, "e[TAB]"), snapbox::str!["external"]);
10001006
}
10011007

10021008
fn complete(cmd: &mut Command, args: impl AsRef<str>, current_dir: Option<&Path>) -> String {

0 commit comments

Comments
 (0)