verbose/verbose.rs
1//! Several ways of creating more fancier flags from primitive components
2//! In practice for "verbose" you'd use a builder pattern and define the variable only once, for
3//! trim on/off you need to define the variables but they can be in a local scope with {}
4use bpaf::*;
5
6#[derive(Debug, Clone, Copy)]
7enum Trim {
8 On,
9 Off,
10}
11
12fn main() {
13 // program takes one or more -v or --verbose flags, more flags = higher verbosity.
14 // parser handles number and produces a single flag.
15 //
16 // let's create it without using any single purpose magical functions
17
18 // Let's staty by creating a simple parser that handles a single -v / --verbose
19 // and fails otherwise;
20 let verbose = short('v').long("verbose").req_flag(());
21
22 // Try to apply the inner parser as many times as it succeeds, return the number
23 let verbose = verbose.count();
24
25 // And add a simple sanity checker.
26 // By this time when this parser succeeds - it will contain verbosity in 0..3 range, inclusive.
27 let verbose = verbose.guard(|&x| x <= 3, "it doesn't get any more verbose than 3");
28
29 // program takes --trimor --no-trimflag, but not both at once. If none is given -
30 // fallback value is to disable trimming. Trim enum is set accordingly
31
32 // this flag succeeds iff --no-trim is given and produces Trim::Off
33 let trim_off = long("no-trim").req_flag(Trim::Off);
34
35 // this flag handles two remaining cases: --trim is given (Trim::On) an fallback (Trim::Off)
36 let trim_on = long("trim").flag(Trim::On, Trim::Off);
37
38 // combination of previous two.
39 // if trim_off succeeds - trim_on never runs, otherwise trim_on tries to handle the remaining
40 // case before falling back to Trim:Off.
41 // If both --trim and --no-trim are given trim_off succeeds, trim_off never runs and --trim
42 // remains unused - parser fails
43 let trim = construct!([trim_off, trim_on]);
44
45 let parser = construct!(verbose, trim);
46
47 let opt = parser.to_options().run();
48 println!("{:#?}", opt);
49}