Skip to content

Commit

Permalink
feat(parser): Provide convenience for SetTrue
Browse files Browse the repository at this point in the history
I wanted to make `bool` a defaulted type parameter but
rust-lang/rust#36887
  • Loading branch information
epage committed Sep 2, 2022
1 parent d2a1f5a commit 2d5fea5
Show file tree
Hide file tree
Showing 8 changed files with 48 additions and 33 deletions.
7 changes: 2 additions & 5 deletions examples/derive_ref/augment_args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,10 @@ fn main() {
let cli = DerivedArgs::augment_args(cli);

let matches = cli.get_matches();
println!(
"Value of built: {:?}",
*matches.get_one::<bool>("built").unwrap()
);
println!("Value of built: {:?}", matches.get_flag("built"));
println!(
"Value of derived via ArgMatches: {:?}",
*matches.get_one::<bool>("derived").unwrap()
matches.get_flag("derived")
);

// Since DerivedArgs implements FromArgMatches, we can extract it from the unstructured ArgMatches.
Expand Down
8 changes: 4 additions & 4 deletions examples/derive_ref/flatten_hand_args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ impl FromArgMatches for CliArgs {
}
fn from_arg_matches_mut(matches: &mut ArgMatches) -> Result<Self, Error> {
Ok(Self {
foo: *matches.get_one::<bool>("foo").expect("defaulted by clap"),
bar: *matches.get_one::<bool>("bar").expect("defaulted by clap"),
foo: matches.get_flag("foo"),
bar: matches.get_flag("bar"),
quuz: matches.remove_one::<String>("quuz"),
})
}
Expand All @@ -25,8 +25,8 @@ impl FromArgMatches for CliArgs {
self.update_from_arg_matches_mut(&mut matches)
}
fn update_from_arg_matches_mut(&mut self, matches: &mut ArgMatches) -> Result<(), Error> {
self.foo |= *matches.get_one::<bool>("foo").expect("defaulted by clap");
self.bar |= *matches.get_one::<bool>("bar").expect("defaulted by clap");
self.foo |= matches.get_flag("foo");
self.bar |= matches.get_flag("bar");
if let Some(quuz) = matches.remove_one::<String>("quuz") {
self.quuz = Some(quuz);
}
Expand Down
5 changes: 1 addition & 4 deletions examples/escaped-positional.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,7 @@ fn main() {
// This is what will happen with `myprog -f -p=bob -- sloppy slop slop`...

// -f used: true
println!(
"-f used: {:?}",
*matches.get_one::<bool>("eff").expect("defaulted by clap")
);
println!("-f used: {:?}", matches.get_flag("eff"));
// -p's value: Some("bob")
println!("-p's value: {:?}", matches.get_one::<String>("pea"));
// 'slops' values: Some(["sloppy", "slop", "slop"])
Expand Down
5 changes: 1 addition & 4 deletions examples/pacman.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,10 +89,7 @@ fn main() {
.collect();
let values = packages.join(", ");

if *sync_matches
.get_one::<bool>("info")
.expect("defaulted by clap")
{
if sync_matches.get_flag("info") {
println!("Retrieving info for {}...", values);
} else {
println!("Installing {}...", values);
Expand Down
7 changes: 1 addition & 6 deletions examples/tutorial_builder/03_01_flag_bool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,5 @@ fn main() {
)
.get_matches();

println!(
"verbose: {:?}",
*matches
.get_one::<bool>("verbose")
.expect("defaulted by clap")
);
println!("verbose: {:?}", matches.get_flag("verbose"));
}
6 changes: 3 additions & 3 deletions examples/tutorial_builder/04_03_relations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,9 @@ fn main() {
} else {
// Increment the one requested (in a real program, we'd reset the lower numbers)
let (maj, min, pat) = (
*matches.get_one::<bool>("major").expect("defaulted by clap"),
*matches.get_one::<bool>("minor").expect("defaulted by clap"),
*matches.get_one::<bool>("patch").expect("defaulted by clap"),
matches.get_flag("major"),
matches.get_flag("minor"),
matches.get_flag("patch"),
);
match (maj, min, pat) {
(true, _, _) => major += 1,
Expand Down
11 changes: 4 additions & 7 deletions examples/tutorial_builder/04_04_custom.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,7 @@ fn main() {

// See if --set-ver was used to set the version manually
let version = if let Some(ver) = matches.get_one::<String>("set-ver") {
if *matches.get_one::<bool>("major").expect("defaulted by clap")
|| *matches.get_one::<bool>("minor").expect("defaulted by clap")
|| *matches.get_one::<bool>("patch").expect("defaulted by clap")
{
if matches.get_flag("major") || matches.get_flag("minor") || matches.get_flag("patch") {
cmd.error(
ErrorKind::ArgumentConflict,
"Can't do relative and absolute version change",
Expand All @@ -48,9 +45,9 @@ fn main() {
} else {
// Increment the one requested (in a real program, we'd reset the lower numbers)
let (maj, min, pat) = (
*matches.get_one::<bool>("major").expect("defaulted by clap"),
*matches.get_one::<bool>("minor").expect("defaulted by clap"),
*matches.get_one::<bool>("patch").expect("defaulted by clap"),
matches.get_flag("major"),
matches.get_flag("minor"),
matches.get_flag("patch"),
);
match (maj, min, pat) {
(true, false, false) => major += 1,
Expand Down
32 changes: 32 additions & 0 deletions src/parser/matches/arg_matches.rs
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,38 @@ impl ArgMatches {
.expect("ArgAction::Count is defaulted")
}

/// Gets the value of a specific [`ArgAction::SetTrue`][crate::ArgAction::SetTrue] or [`ArgAction::SetFalse`][crate::ArgAction::SetFalse] flag
///
/// # Panic
///
/// If the argument's action is not [`ArgAction::SetTrue`][crate::ArgAction::SetTrue] or [`ArgAction::SetFalse`][crate::ArgAction::SetFalse]
///
/// # Examples
///
/// ```rust
/// # use clap::Command;
/// # use clap::Arg;
/// let cmd = Command::new("mycmd")
/// .arg(
/// Arg::new("flag")
/// .long("flag")
/// .action(clap::ArgAction::SetTrue)
/// );
///
/// let matches = cmd.clone().try_get_matches_from(["mycmd", "--flag", "--flag"]).unwrap();
/// assert!(matches.contains_id("flag"));
/// assert_eq!(
/// matches.get_flag("flag"),
/// true
/// );
/// ```
#[track_caller]
pub fn get_flag(&self, id: &str) -> bool {
*self
.get_one::<bool>(id)
.expect("ArgAction::SetTrue / ArgAction::SetFalse is defaulted")
}

/// Iterate over values of a specific option or positional argument.
///
/// i.e. an argument that takes multiple values at runtime.
Expand Down

0 comments on commit 2d5fea5

Please sign in to comment.