Closed qtfkwk closed 3 weeks ago
There are 2 issues:
In the future, please open an issue per concern.
With num_args set to 2.. and user gives 0, it does not produce an error as it should because the minimum number of args is 2
The behavior is correct. From the docs:
Specifies the number of arguments parsed per occurrence
This isn't as obvious for positionals but for options, the behavior is more clear.
use clap::Parser;
#[derive(Parser)]
struct Cli {
/// Args
#[arg(long, value_name = "ARG", num_args = 2..)]
args: Vec<String>,
}
fn main() {
let cli = Cli::parse();
println!("{:#?}", cli.args);
}
$ # good: 2+ values
$ cmd --args asdf blah
$ # good: 2+ values
$ cmd --args asdf blah spam
$ # good: 2+ values per `--arg`
$ cmd --args asdf blah --arg spam pizza
$ # bad: too few values
$ cmd --args asdf
$ # bad: too few values for last `--arg`
$ cmd --args asdf blah --arg spam
$ # good: no occurrences
$ cmd
What you are looking for is required = true
. You also likely want to set action = ArgAction::Set
because a Vec
is automatically an Append
, see https://docs.rs/clap/latest/clap/_derive/index.html#arg-types
use clap::Parser;
use clap::builder::ArgAction;
#[derive(Parser)]
struct Cli {
/// Args
#[arg(long, value_name = "ARG", num_args = 2.., required = true, action = ArgAction::Set)]
args: Vec<String>,
}
fn main() {
let cli = Cli::parse();
println!("{:#?}", cli.args);
}
Thank you for the detailed response, @epage! Will try your suggested fix.
Please complete the following tasks
Rust Version
rustc 1.78.0 (9b00956e5 2024-04-29)
Clap Version
4.5.6
Minimal reproducible code
Steps to reproduce the bug with the above code
Error when running
cargo run -- asdf
:Shouldn't it say either of the following?
error: 1 more value required by '[ARG] [ARG]...'; only 1 was provided
error: 2 values required by '[ARG] [ARG]...'; only 1 was provided
(my personal preference is for this one)Actual Behaviour
There are 2 issues:
2..
and user gives 0, it does not produce an error as it should because the minimum number of args is 2Expected Behaviour
2..
and user gives 0, it should produce an error saying that it requires 2 args and 0 were givenAdditional Context
https://github.com/clap-rs/clap/blob/2f645d3e81c783a4e76ad17f1ccf283a58b75660/clap_builder/src/error/format.rs#L340:
should be:
remove the word "more"
Debug Output