basic/
basic.rs

1//! A somewhat comprehensive example of a typical combinatoric `bpaf` usage in combinatoric mode
2
3use bpaf::*;
4use std::path::PathBuf;
5
6#[allow(dead_code)]
7#[derive(Debug, Clone)]
8struct Out {
9    debug: bool,
10    verbose: usize,
11    speed: f64,
12    output: PathBuf,
13    nb_cars: u32,
14    files_to_process: Vec<PathBuf>,
15}
16
17fn opts() -> OptionParser<Out> {
18    // A flag, true if used in the command line. Can be required, this one is optional
19
20    let debug = short('d') // start with a short name
21        .long("debug") // also add a long name
22        .help("Activate debug mode") // and a help message to use
23        .switch(); // turn this into a switch
24
25    // number of occurrences of the v/verbose flag capped at 3 with an error here but you can also
26    // use `max` inside `map`
27    let verbose = short('v')
28        .long("verbose")
29        .help("Increase the verbosity\n You can specify it up to 3 times\n either as -v -v -v or as -vvv")
30        .req_flag(())
31        .many()
32        .map(|xs| xs.len())
33        .guard(|&x| x <= 3, "It doesn't get any more verbose than this");
34
35    // an argument, parsed and with default value
36    let speed = short('s')
37        .long("speed")
38        .help("Set speed")
39        .argument::<f64>("SPEED") // you can specify a type to parse
40        .fallback(42.0)
41        .display_fallback();
42
43    let output = short('o')
44        .long("output")
45        .help("output file")
46        .argument::<PathBuf>("OUTPUT") // but it's optional when rustc can derive it
47        .complete_shell(ShellComp::File { mask: None });
48
49    // no magical name transmogrifications in combinatoric API,
50    let nb_cars = short('n')
51        .long("nb-cars")
52        .help("Number of items to process")
53        .argument::<u32>("N")
54        .fallback(1)
55        .display_fallback();
56
57    // a parser that consumes one argument
58    // you can build the inner parser in one go or as multiple steps giving each step a name
59    // you can also add some static shell completion functionality
60    let file_to_proces = short('f')
61        .long("file")
62        .help("File to process")
63        .argument::<PathBuf>("FILE")
64        .complete_shell(ShellComp::File { mask: Some("*.rs") });
65
66    let files_to_process = file_to_proces.many();
67
68    // packing things in a struct assumes parser for each field is in scope.
69    construct!(Out {
70        debug,
71        verbose,
72        speed,
73        output,
74        nb_cars,
75        files_to_process
76    })
77    .to_options()
78    .descr("This is a description")
79}
80
81fn main() {
82    let opts = opts().fallback_to_usage().run();
83    println!("{:#?}", opts);
84}