From 5335f54d73eef9276c13313661fcfffb720c87cf Mon Sep 17 00:00:00 2001 From: Ed Page Date: Mon, 11 Aug 2025 14:34:17 -0500 Subject: [PATCH] feat: Add Command::mut_subcommands --- clap_builder/src/builder/command.rs | 45 +++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/clap_builder/src/builder/command.rs b/clap_builder/src/builder/command.rs index 448f7395fcc..5ac6a1d0b93 100644 --- a/clap_builder/src/builder/command.rs +++ b/clap_builder/src/builder/command.rs @@ -386,6 +386,51 @@ impl Command { self } + /// Allows one to mutate all [`Command`]s after they've been added as subcommands. + /// + /// This does not affect the built-in `--help` or `--version` arguments. + /// + /// # Examples + /// + #[cfg_attr(feature = "string", doc = "```")] + #[cfg_attr(not(feature = "string"), doc = "```ignore")] + /// # use clap_builder as clap; + /// # use clap::{Command, Arg, ArgAction}; + /// + /// let mut cmd = Command::new("foo") + /// .subcommands([ + /// Command::new("fetch"), + /// Command::new("push"), + /// ]) + /// // Allow title-case subcommands + /// .mut_subcommands(|sub| { + /// let name = sub.get_name(); + /// let alias = name.chars().enumerate().map(|(i, c)| { + /// if i == 0 { + /// c.to_ascii_uppercase() + /// } else { + /// c + /// } + /// }).collect::(); + /// sub.alias(alias) + /// }); + /// + /// let res = cmd.try_get_matches_from_mut(vec!["foo", "fetch"]); + /// assert!(res.is_ok()); + /// + /// let res = cmd.try_get_matches_from_mut(vec!["foo", "Fetch"]); + /// assert!(res.is_ok()); + /// ``` + #[must_use] + #[cfg_attr(debug_assertions, track_caller)] + pub fn mut_subcommands(mut self, f: F) -> Self + where + F: FnMut(Command) -> Command, + { + self.subcommands = self.subcommands.into_iter().map(f).collect(); + self + } + /// Adds an [`ArgGroup`] to the application. /// /// [`ArgGroup`]s are a family of related arguments.