Open drmikehenry opened 1 year ago
For reference, in Cargo.toml
is:
[dependencies]
clap = { version = "4.1.6", features = ["debug", "derive"] }
Using ArgPredicate::Equals("true".into())
instead of ArgPredicate::IsPresent
does what you are trying to achieve.
use clap::{builder::ArgPredicate, Parser};
#[derive(Parser, Debug)]
struct Cli {
#[arg(
long,
default_value_if("imply_both", ArgPredicate::Equals("true".into()), Some("true"))
)]
flag1: bool,
/// imply both --flag1 and --flag2
#[arg(long)]
imply_both: bool,
#[arg(
long,
default_value_if("imply_both", ArgPredicate::Equals("true".into()), Some("true"))
)]
flag2: bool,
}
fn main() {
let cli = Cli::parse();
println!("{:#?}", cli);
}
$ cargo run -q --
Cli {
flag1: false,
imply_both: false,
flag2: false,
}
$ cargo run -q -- --imply-both
Cli {
flag1: true,
imply_both: true,
flag2: true,
}
I am not sure what is happening here with ArgPredicate::IsPresent
. It looks like ArgPredicate::IsPresent
also includes if the argument has already been defined and has a default value.
Thanks for the explanation; your suggestion works perfectly.
@mattmadeofpasta thanks for providing that answer!
I'm going to re-open though as generally the ArgPredicate::IsPresent
means "it is explicitly present" which excludes defaults (but includes env variables) but default_value_if
is not doing an explicit check.
I went ahead and marked this as a breaking change and scheduled it for 5.0. This is one of those cases where the line between bug fix and breaking change is unclear, so I marked it as the more extreme case until a more thorough determination can be made.
Past changes like this were treated as non-breaking
Please complete the following tasks
Rust Version
rustc 1.65.0 (897e37553 2022-11-02)
Clap Version
4.1.6
Minimal reproducible code
Steps to reproduce the bug with the above code
Actual Behaviour
This output is generated when no options are given:
Note that
flag2
is true.Expected Behaviour
I expected that
flag1
,flag2
, andimply_both
would all befalse
.Note that when I move the
imply_both
argument to the end of theCli
struct, it works as I expect:But with this ordering, the automatically generated help is not in my preferred order.
Additional Context
No response
Debug Output