mirror of
https://github.com/clap-rs/clap
synced 2024-12-14 23:02:31 +00:00
d840d5650e
Before #2005, `Clap` was a special trait that derived all clap traits it detected were relevant (including an enum getting both `ArgEnum`, `Clap`, and `Subcommand`). Now, we have elevated `Clap`, `Args`, `Subcommand`, and `ArgEnum` to be user facing but the name `Clap` isn't very descriptive. This also helps further clarify the relationships so a crate providing an item to be `#[clap(flatten)]` or `#[clap(subcommand)]` is more likely to choose the needed trait to derive. Also, my proposed fix fo #2785 includes making `App` attributes almost exclusively for `Clap`. Clarifying the names/roles will help communicate this. For prior discussion, see #2583
36 lines
1.1 KiB
Rust
36 lines
1.1 KiB
Rust
//! How to parse "key=value" pairs with #[derive(Parser)].
|
|
|
|
use clap::Parser;
|
|
use std::error::Error;
|
|
|
|
/// Parse a single key-value pair
|
|
fn parse_key_val<T, U>(s: &str) -> Result<(T, U), Box<dyn Error + Send + Sync + 'static>>
|
|
where
|
|
T: std::str::FromStr,
|
|
T::Err: Error + Send + Sync + 'static,
|
|
U: std::str::FromStr,
|
|
U::Err: Error + Send + Sync + 'static,
|
|
{
|
|
let pos = s
|
|
.find('=')
|
|
.ok_or_else(|| format!("invalid KEY=value: no `=` found in `{}`", s))?;
|
|
Ok((s[..pos].parse()?, s[pos + 1..].parse()?))
|
|
}
|
|
|
|
#[derive(Parser, Debug)]
|
|
struct Opt {
|
|
// number_of_values = 1 forces the user to repeat the -D option for each key-value pair:
|
|
// my_program -D a=1 -D b=2
|
|
// Without number_of_values = 1 you can do:
|
|
// my_program -D a=1 b=2
|
|
// but this makes adding an argument after the values impossible:
|
|
// my_program -D a=1 -D b=2 my_input_file
|
|
// becomes invalid.
|
|
#[clap(short = 'D', parse(try_from_str = parse_key_val), multiple_occurrences(true), number_of_values = 1)]
|
|
defines: Vec<(String, i32)>,
|
|
}
|
|
|
|
fn main() {
|
|
let opt = Opt::parse();
|
|
println!("{:?}", opt);
|
|
}
|