2021-07-13 17:50:55 +00:00
|
|
|
//! How to parse "key=value" pairs with #[derive(Parser)].
|
2018-03-09 15:52:50 +00:00
|
|
|
|
2021-07-13 17:50:55 +00:00
|
|
|
use clap::Parser;
|
2018-03-29 22:15:22 +00:00
|
|
|
use std::error::Error;
|
2018-03-09 15:52:50 +00:00
|
|
|
|
2020-01-07 10:17:23 +00:00
|
|
|
/// Parse a single key-value pair
|
2020-10-05 16:35:45 +00:00
|
|
|
fn parse_key_val<T, U>(s: &str) -> Result<(T, U), Box<dyn Error + Send + Sync + 'static>>
|
2018-03-29 22:15:22 +00:00
|
|
|
where
|
|
|
|
T: std::str::FromStr,
|
2020-10-05 16:35:45 +00:00
|
|
|
T::Err: Error + Send + Sync + 'static,
|
2018-03-29 22:15:22 +00:00
|
|
|
U: std::str::FromStr,
|
2020-10-05 16:35:45 +00:00
|
|
|
U::Err: Error + Send + Sync + 'static,
|
2018-03-29 22:15:22 +00:00
|
|
|
{
|
2018-07-02 18:45:17 +00:00
|
|
|
let pos = s
|
|
|
|
.find('=')
|
2018-05-21 14:54:22 +00:00
|
|
|
.ok_or_else(|| format!("invalid KEY=value: no `=` found in `{}`", s))?;
|
2018-03-29 22:15:22 +00:00
|
|
|
Ok((s[..pos].parse()?, s[pos + 1..].parse()?))
|
2018-03-09 15:52:50 +00:00
|
|
|
}
|
|
|
|
|
2021-07-13 17:50:55 +00:00
|
|
|
#[derive(Parser, Debug)]
|
2018-03-09 15:52:50 +00:00
|
|
|
struct Opt {
|
2020-01-07 10:17:23 +00:00
|
|
|
// 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.
|
2021-08-30 02:52:35 +00:00
|
|
|
#[clap(short = 'D', parse(try_from_str = parse_key_val), multiple_occurrences(true), number_of_values = 1)]
|
2018-03-29 22:15:22 +00:00
|
|
|
defines: Vec<(String, i32)>,
|
2018-03-09 15:52:50 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
fn main() {
|
2018-07-02 18:45:17 +00:00
|
|
|
let opt = Opt::parse();
|
2018-03-09 15:52:50 +00:00
|
|
|
println!("{:?}", opt);
|
|
|
|
}
|