Skip to content

Commit

Permalink
feat: Add CommandExt support
Browse files Browse the repository at this point in the history
  • Loading branch information
epage committed Oct 2, 2024
1 parent 32853d7 commit a767a97
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
28 changes: 28 additions & 0 deletions clap_builder/src/builder/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,8 @@ pub struct Command {
external_value_parser: Option<super::ValueParser>,
long_help_exists: bool,
deferred: Option<fn(Command) -> Command>,
#[cfg(feature = "unstable-ext")]
ext: Extensions,
app_ext: Extensions,
}

Expand Down Expand Up @@ -1040,6 +1042,14 @@ impl Command {

Usage::new(self).create_usage_with_title(&[])
}

/// Extend [`Command`] with [`CommandExt`] data
#[cfg(feature = "unstable-ext")]
#[allow(clippy::should_implement_trait)]
pub fn add<T: CommandExt + Extension>(mut self, tagged: T) -> Self {
self.ext.set(tagged);
self
}
}

/// # Application-wide Settings
Expand Down Expand Up @@ -3965,6 +3975,18 @@ impl Command {
pub fn is_multicall_set(&self) -> bool {
self.is_set(AppSettings::Multicall)
}

/// Access an [`CommandExt`]
#[cfg(feature = "unstable-ext")]
pub fn get<T: CommandExt + Extension>(&self) -> Option<&T> {
self.ext.get::<T>()
}

/// Remove an [`CommandExt`]
#[cfg(feature = "unstable-ext")]
pub fn remove<T: CommandExt + Extension>(mut self) -> Option<T> {
self.ext.remove::<T>()
}
}

// Internally used only
Expand Down Expand Up @@ -4884,6 +4906,8 @@ impl Default for Command {
external_value_parser: Default::default(),
long_help_exists: false,
deferred: None,
#[cfg(feature = "unstable-ext")]
ext: Default::default(),
app_ext: Default::default(),
}
}
Expand All @@ -4909,6 +4933,10 @@ impl fmt::Display for Command {
}
}

/// User-provided data that can be attached to an [`Arg`]
#[cfg(feature = "unstable-ext")]
pub trait CommandExt: Extension {}

#[allow(dead_code)] // atm dependent on features enabled
pub(crate) trait AppExt: Extension {}

Expand Down
4 changes: 3 additions & 1 deletion clap_builder/src/builder/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ pub use arg::ArgExt;
pub use arg_group::ArgGroup;
pub use arg_predicate::ArgPredicate;
pub use command::Command;
#[cfg(feature = "unstable-ext")]
pub use command::CommandExt;
pub use os_str::OsStr;
pub use possible_value::PossibleValue;
pub use range::ValueRange;
Expand All @@ -41,9 +43,9 @@ pub use resettable::Resettable;
pub use styled_str::StyledStr;
pub use styling::Styles;
pub use value_hint::ValueHint;
pub use value_parser::BoolValueParser;
pub use value_parser::_infer_ValueParser_for;
pub use value_parser::impl_prelude;
pub use value_parser::BoolValueParser;
pub use value_parser::BoolishValueParser;
pub use value_parser::EnumValueParser;
pub use value_parser::FalseyValueParser;
Expand Down

0 comments on commit a767a97

Please sign in to comment.