mirror of
https://github.com/clap-rs/clap
synced 2024-11-11 07:14:15 +00:00
Merge pull request #3080 from epage/keyvalue
docs: Add key-value derive example
This commit is contained in:
commit
ef52be81a5
4 changed files with 57 additions and 0 deletions
|
@ -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"
|
||||
|
|
|
@ -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)
|
||||
|
|
25
examples/keyvalue_derive.md
Normal file
25
examples/keyvalue_derive.md
Normal 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
|
||||
```
|
27
examples/keyvalue_derive.rs
Normal file
27
examples/keyvalue_derive.rs
Normal 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);
|
||||
}
|
Loading…
Reference in a new issue