Merge pull request #3080 from epage/keyvalue

docs: Add key-value derive example
This commit is contained in:
Pavan Kumar Sunkara 2021-12-08 01:15:22 +00:00 committed by GitHub
commit ef52be81a5
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 57 additions and 0 deletions

View file

@ -136,6 +136,10 @@ required-features = ["derive"]
name = "git_derive"
required-features = ["derive"]
[[example]]
name = "keyvalue_derive"
required-features = ["derive"]
[[example]]
name = "busybox"
path = "examples/multicall_busybox.rs"

View file

@ -1,6 +1,7 @@
# Examples
- Basic demo: [derive](demo.md)
- Key-value pair arguments: [derive](keyvalue_derive.md)
- git-like interface: [builder](git.md), [derive](git_derive.md)
- pacman-like interface: [builder](git.md)
- Escaped positionals with `--`: [builder](escaped_positional.md), [derive](escaped_positional_derive.md)

View file

@ -0,0 +1,25 @@
*Jump to [source](keyvalue_derive.rs)*
```bash
$ keyvalue_derive --help
clap
USAGE:
keyvalue_derive[EXE] [OPTIONS]
OPTIONS:
-D <DEFINES>
-h, --help Print help information
$ keyvalue_derive -D Foo=10 -D Alice=30
Args { defines: [("Foo", 10), ("Alice", 30)] }
$ keyvalue_derive -D Foo
? failed
error: Invalid value for '-D <DEFINES>': invalid KEY=value: no `=` found in `Foo`
For more information try --help
$ keyvalue_derive -D Foo=Bar
? failed
error: Invalid value for '-D <DEFINES>': invalid digit found in string
For more information try --help
```

View file

@ -0,0 +1,27 @@
use clap::Parser;
use std::error::Error;
#[derive(Parser, Debug)]
struct Args {
#[clap(short = 'D', parse(try_from_str = parse_key_val), multiple_occurrences(true))]
defines: Vec<(String, i32)>,
}
/// 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()?))
}
fn main() {
let args = Args::parse();
println!("{:?}", args);
}