Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add Command::mut_group #5247

Merged
merged 1 commit into from
Dec 4, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions clap_builder/src/builder/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -298,6 +298,45 @@ impl Command {
self
}

/// Allows one to mutate an [`ArgGroup`] after it's been added to a [`Command`].
///
/// # Panics
///
/// If the argument is undefined
///
/// # Examples
///
/// ```rust
/// # use clap_builder as clap;
/// # use clap::{Command, arg, ArgGroup};
///
/// Command::new("foo")
/// .arg(arg!(--"set-ver" <ver> "set the version manually").required(false))
/// .arg(arg!(--major "auto increase major"))
/// .arg(arg!(--minor "auto increase minor"))
/// .arg(arg!(--patch "auto increase patch"))
/// .group(ArgGroup::new("vers")
/// .args(["set-ver", "major", "minor","patch"])
/// .required(true))
/// .mut_group("vers", |a| a.required(false));
/// ```
#[must_use]
#[cfg_attr(debug_assertions, track_caller)]
pub fn mut_group<F>(mut self, arg_id: impl AsRef<str>, f: F) -> Self
where
F: FnOnce(ArgGroup) -> ArgGroup,
{
let id = arg_id.as_ref();
let index = self
.groups
.iter()
.position(|g| g.get_id() == id)
.unwrap_or_else(|| panic!("Group `{id}` is undefined"));
let a = self.groups.remove(index);

self.groups.push(f(a));
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
Loading