Skip to content

Commit e3e8fc5

Browse files
committed
feat: Add Command::mut_subcommands
1 parent ccde9f7 commit e3e8fc5

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

clap_builder/src/builder/command.rs

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -386,6 +386,55 @@ 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, mut f: F) -> Self
427+
where
428+
F: FnMut(Command) -> Command,
429+
{
430+
self.subcommands = self
431+
.subcommands
432+
.into_iter()
433+
.map(move |sub| f(sub))
434+
.collect();
435+
self
436+
}
437+
389438
/// Adds an [`ArgGroup`] to the application.
390439
///
391440
/// [`ArgGroup`]s are a family of related arguments.

0 commit comments

Comments
 (0)