Skip to content

Commit

Permalink
Merge pull request clap-rs#5051 from joshtriplett/mut-args
Browse files Browse the repository at this point in the history
Add `Command::mut_args` to modify all arguments of a `Command`
  • Loading branch information
epage authored Aug 1, 2023
2 parents 3641147 + 9c09026 commit 56048d8
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
46 changes: 46 additions & 0 deletions clap_builder/src/builder/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,52 @@ impl Command {
self
}

/// Allows one to mutate all [`Arg`]s after they've been added to a [`Command`].
///
/// 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")
/// .arg(Arg::new("bar")
/// .long("bar")
/// .action(ArgAction::SetTrue))
/// .arg(Arg::new("baz")
/// .long("baz")
/// .action(ArgAction::SetTrue))
/// .mut_args(|a| {
/// if let Some(l) = a.get_long().map(|l| format!("prefix-{l}")) {
/// a.long(l)
/// } else {
/// a
/// }
/// });
///
/// let res = cmd.try_get_matches_from_mut(vec!["foo", "--bar"]);
///
/// // Since we changed `bar`'s long to "prefix-bar" this should err as there
/// // is no `--bar` anymore, only `--prefix-bar`.
///
/// assert!(res.is_err());
///
/// let res = cmd.try_get_matches_from_mut(vec!["foo", "--prefix-bar"]);
/// assert!(res.is_ok());
/// ```
#[must_use]
#[cfg_attr(debug_assertions, track_caller)]
pub fn mut_args<F>(mut self, f: F) -> Self
where
F: FnMut(Arg) -> Arg,
{
self.args.mut_args(f);
self
}

/// Allows one to mutate a [`Command`] after it's been added as a subcommand.
///
/// This can be useful for modifying auto-generated arguments of nested subcommands with
Expand Down
9 changes: 9 additions & 0 deletions clap_builder/src/mkeymap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,15 @@ impl MKeyMap {
self.args.iter_mut()
}

/// Mutate every argument.
pub(crate) fn mut_args<F>(&mut self, f: F)
where
F: FnMut(Arg) -> Arg,
{
let mut args = std::mem::take(&mut self.args);
self.args.extend(args.drain(..).map(f));
}

/// We need a lazy build here since some we may change args after creating
/// the map, you can checkout who uses `args_mut`.
pub(crate) fn _build(&mut self) {
Expand Down

0 comments on commit 56048d8

Please sign in to comment.