Clap dependent arguments

I am using clap (3.2.23) to make a CLI application and I want to be able to specify two arguments like this:

--arg1 --arg2 VALUE

But when you only specify --arg2 VALUE then it should error saying something like:

--arg2 can only be used when --arg1 is specified

But when you only specify --arg1 or none of the two it does not complain about anything.

I know about argument groups and also the requires derive but as far as I know they cannot achieve this sort of behaviour.

is Arg::requires what you want?

// builder api
let cli = Command::new("progname")
	.arg(Arg::new("arg1").long("arg1").action(ArgAction::SetTrue))
	.arg(Arg::new("arg2").long("arg2").requires("arg1"));
// derive api
#[derive(clap::Parser)]
struct Cli {
	#[arg(long)]
	arg1: bool,
	#[arg(long, requires("arg1"))]
	arg2: Option<String>,
}

it has the behavior as described, but will give only generic error messages like "required argument not provided". if the special error message is required, you'll have to format the message yourself, see e.g. the example in the custom validation section of the documentation:

I did exactly that but it always panicks on me saying: Argument or group 'arg1' specified in 'requires*' for 'arg2' does not exist.

What I have:

#[derive(Parser, Debug)]
#[clap(author, version, about, long_about = None)]
struct Args {
    #[clap(long)]
    arg1: bool,

    #[clap(
        long,
        requires = "arg1",
    )]
    arg2: String,
}

than you must have done something wrong elsewhere. it compiles and runs without problem on the playground:

1 Like

I don't really get it but I am using the newest version now and it works.
Makes no sense as it should work in 3.2.23 where I would have a colored help page but I guess I'll have to live without it.
stupid

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.