Skip to content

Commit a42eebf

Browse files
authored
Merge pull request #6103 from epage/mut_subcommands
feat: Add Command::mut_subcommands
2 parents ccde9f7 + 5335f54 commit a42eebf

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

clap_builder/src/builder/command.rs

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -386,6 +386,51 @@ impl Command {
386386
self
387387
}
388388

389+
/// Allows one to mutate all [`Command`]s after they've been added as subcommands.
390+
///
391+
/// This does not affect the built-in `--help` or `--version` arguments.
392+
///
393+
/// # Examples
394+
///
395+
#[cfg_attr(feature = "string", doc = "```")]
396+
#[cfg_attr(not(feature = "string"), doc = "```ignore")]
397+
/// # use clap_builder as clap;
398+
/// # use clap::{Command, Arg, ArgAction};
399+
///
400+
/// let mut cmd = Command::new("foo")
401+
/// .subcommands([
402+
/// Command::new("fetch"),
403+
/// Command::new("push"),
404+
/// ])
405+
/// // Allow title-case subcommands
406+
/// .mut_subcommands(|sub| {
407+
/// let name = sub.get_name();
408+
/// let alias = name.chars().enumerate().map(|(i, c)| {
409+
/// if i == 0 {
410+
/// c.to_ascii_uppercase()
411+
/// } else {
412+
/// c
413+
/// }
414+
/// }).collect::<String>();
415+
/// sub.alias(alias)
416+
/// });
417+
///
418+
/// let res = cmd.try_get_matches_from_mut(vec!["foo", "fetch"]);
419+
/// assert!(res.is_ok());
420+
///
421+
/// let res = cmd.try_get_matches_from_mut(vec!["foo", "Fetch"]);
422+
/// assert!(res.is_ok());
423+
/// ```
424+
#[must_use]
425+
#[cfg_attr(debug_assertions, track_caller)]
426+
pub fn mut_subcommands<F>(mut self, f: F) -> Self
427+
where
428+
F: FnMut(Command) -> Command,
429+
{
430+
self.subcommands = self.subcommands.into_iter().map(f).collect();
431+
self
432+
}
433+
389434
/// Adds an [`ArgGroup`] to the application.
390435
///
391436
/// [`ArgGroup`]s are a family of related arguments.

0 commit comments

Comments
 (0)