pub fn pure_with<T, F, E>(val: F) -> ParsePureWith<T, F, E>
Expand description
Wrap a calculated value into a Parser
This parser represents a possibly failing equivalent to pure
.
It produces T
by invoking the provided callback without consuming anything from the command
line, which can be useful with construct!
. As with any parsers, T
should be Clone
and Debug
.
Both pure
and pure_with
are designed to put values into structures, to generate fallback
you should be using fallback
and fallback_with
.
See also pure
for a pure computation that can’t fail.
Combinatoric example
#[derive(Debug, Clone)]
pub struct Options {
name: String,
money: u32,
}
fn starting_money() -> Result<u32, &'static str> {
Ok(330)
}
pub fn options() -> OptionParser<Options> {
// User can customise a name
let name = long("name").help("Use a custom user name").argument("NAME");
// but not starting amount of money
let money = pure_with(starting_money);
construct!(Options { name, money }).to_options()
}
fn main() {
println!("{:?}", options().run())
}
Derive example
#[derive(Debug, Clone, Bpaf)]
#[bpaf(options)]
pub struct Options {
#[bpaf(argument("NAME"))]
/// Use a custom user name
name: String,
#[bpaf(pure_with(starting_money))]
money: u32,
}
fn starting_money() -> Result<u32, &'static str> {
Ok(330)
}
fn main() {
println!("{:?}", options().run())
}
Output
pure
does not show up in --help
message
$ app --help
Usage: app --name=NAME
Available options:
- --name=NAME
- Use a custom user name
- -h, --help
- Prints help information
And there’s no way to alter the value from the command line
$ app --name Bob
Options { name: "Bob", money: 330 }
Options { name: "Bob", money: 330 }
Any attempts to do so would result in an error :)
$ app --money 100000 --name Hackerman
Error: --money is not expected in this context
Error: --money is not expected in this context