Skip to content

Commit

Permalink
feat: Allow defer initialization of subcommands
Browse files Browse the repository at this point in the history
This comes at the cost of 1.1 KiB of binary size

Inspired by #4774
  • Loading branch information
epage committed Mar 25, 2023
1 parent 9712987 commit 2cd26bb
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions clap_builder/src/builder/command.rs
Expand Up @@ -107,6 +107,7 @@ pub struct Command {
subcommand_heading: Option<Str>,
external_value_parser: Option<super::ValueParser>,
long_help_exists: bool,
deferred: Option<fn(Command) -> Command>,
}

/// # Basic API
Expand Down Expand Up @@ -431,6 +432,30 @@ impl Command {
self
}

/// Delay initialization for parts of the `Command`
///
/// This is useful for large applications to delay definitions of subcommands until they are
/// being invoked.
///
/// # Examples
///
/// ```rust
/// # use clap_builder as clap;
/// # use clap::{Command, arg};
/// Command::new("myprog")
/// .subcommand(Command::new("config")
/// .about("Controls configuration features")
/// .defer(|cmd| {
/// cmd.arg(arg!(<config> "Required configuration file to use"))
/// })
/// )
/// # ;
/// ```
pub fn defer(mut self, deferred: fn(Command) -> Command) -> Self {
self.deferred = Some(deferred);
self
}

/// Catch problems earlier in the development cycle.
///
/// Most error states are handled as asserts under the assumption they are programming mistake
Expand Down Expand Up @@ -3925,6 +3950,10 @@ impl Command {
pub(crate) fn _build_self(&mut self, expand_help_tree: bool) {
debug!("Command::_build: name={:?}", self.get_name());
if !self.settings.is_set(AppSettings::Built) {
if let Some(deferred) = self.deferred.take() {
*self = (deferred)(std::mem::take(self));
}

// Make sure all the globally set flags apply to us as well
self.settings = self.settings | self.g_settings;

Expand Down Expand Up @@ -4759,6 +4788,7 @@ impl Default for Command {
subcommand_heading: Default::default(),
external_value_parser: Default::default(),
long_help_exists: false,
deferred: None,
}
}
}
Expand Down

0 comments on commit 2cd26bb

Please sign in to comment.