Function bpaf::batteries::toggle_flag

source ·
pub fn toggle_flag<T: Copy + 'static>(
    a: NamedArg,
    val_a: T,
    b: NamedArg,
    val_b: T
) -> impl Parser<Option<T>>
Expand description

Pick last passed value between two different flags

Usually bpaf only allows to parse a single instance for every invocation unless you specify many or some. toggle_flag would consume multiple instances of two different flags and returns last specified value.

This function relies on a fact that selection between two different parsers prefers left most value. This helps to preserve relative order of parsrs. You can use similar approach to combine multiple flags accounting for their relative order.

Parser returns Optional<T> value, you can add a fallback with map or turn missing value info failure with a custom error message with parse.

Example

$ app --banana --no-banana --banana --banana
Some(Banana)
$ app
None

Usage

use bpaf::batteries::toggle_flag;

#[derive(Copy, Clone, Debug, PartialEq, Eq)]
enum Select {
    Banana,
    NoBanana,
}

fn pick() -> impl Parser<Option<Select>> {
    toggle_flag(long("banana"), Select::Banana, long("no-banana"), Select::NoBanana)
}