multiple_fallback/
multiple_fallback.rs

1//! Multi level fallback example:
2//!
3//! Fallback to one of several values
4//! - the command line argument
5//! - the environmental variable
6//! - the config file
7//! - the hard-coded default
8
9#![allow(dead_code)]
10use bpaf::*;
11
12#[derive(Clone, Debug)]
13struct Config {
14    field1: u32,
15    field2: u64,
16}
17
18/// Here this is a constant but it can be OnceCell from `once_cell`
19/// that reads the config and deals with substituting missing falues with defaults
20const DEFAULT_CONFIG: Config = Config {
21    field1: 42,
22    field2: 10,
23};
24
25pub fn main() {
26    let field1 = long("field1")
27        .env("FIELD1")
28        .help("Field 1")
29        .argument::<u32>("ARG")
30        .fallback(DEFAULT_CONFIG.field1);
31    let field2 = long("field2")
32        .env("FIELD2")
33        .help("Field 2")
34        .argument::<u64>("ARG")
35        .fallback(DEFAULT_CONFIG.field2);
36
37    let opts = construct!(Config { field1, field2 }).to_options().run();
38
39    // At this point if you get opts - it should be taken from one of
40    // - the command line argument
41    // - the environmental variable
42    // - the config file
43    // - the hard-coded default (from config parser)
44    println!("{:?}", opts);
45}