top_to_bottom/
top_to_bottom.rs

1//! A somewhat comprehensive example of a typical `bpaf` usage.
2//! Since those can be functions - order doesn't really matter
3
4use bpaf::*;
5use std::path::PathBuf;
6
7#[allow(dead_code)]
8#[derive(Debug, Clone)]
9struct Out {
10    debug: bool,
11    verbose: usize,
12    speed: f64,
13    output: PathBuf,
14    nb_cars: u32,
15    files_to_process: Vec<PathBuf>,
16}
17
18fn main() {
19    // packing things in a struct assumes parser for each field is in scope.
20    let opt = (construct!(Out {
21        debug(),
22        verbose(),
23        speed(),
24        output(),
25        nb_cars(),
26        files_to_process()
27    }))
28    .to_options()
29    .run();
30    println!("{:#?}", opt);
31}
32// A flag, true if used in the command line. Can be required, this one is optional
33fn debug() -> impl Parser<bool> {
34    short('d')
35        .long("debug")
36        .help("Activate debug mode")
37        .switch()
38}
39// number of occurrences of the v/verbose flag capped at 3
40fn verbose() -> impl Parser<usize> {
41    short('v')
42        .long("verbose")
43        .help("Increase the verbosity\nYou can specify it up to 3 times\neither as -v -v -v or as -vvv")
44        .req_flag(())
45        .many()
46        .map(|xs| xs.len())
47        .guard(|&x| x <= 3, "It doesn't get any more verbose than this")
48}
49
50// an argument, parsed and with default value
51fn speed() -> impl Parser<f64> {
52    short('s')
53        .long("speed")
54        .help("Set speed")
55        .argument::<f64>("SPEED")
56        .fallback(42.0)
57}
58
59fn output() -> impl Parser<PathBuf> {
60    short('o')
61        .long("output")
62        .help("output file")
63        .argument::<PathBuf>("OUTPUT")
64}
65
66// no magical name transmogrifications.
67fn nb_cars() -> impl Parser<u32> {
68    short('n').long("nb-cars").argument::<u32>("N")
69}
70
71fn files_to_process() -> impl Parser<Vec<PathBuf>> {
72    short('f')
73        .long("file")
74        .help("File to process")
75        .argument::<PathBuf>("FILE")
76        .many()
77}