summaryrefslogtreecommitdiff
path: root/src/main.rs
blob: 4cfbcc787a84cab00513eeabe87e481ff94cd04a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
mod args;

use std::process::ExitCode;

fn guess_parser(args: &mut dyn Iterator<Item = String>) -> Box<dyn args::Parser> {
    for arg in args {
        if arg.len() > 2 && arg.starts_with("--") {
            // --C.. can only be ShortAndLong
            return Box::new(args::ShortAndLongParser::new());
        }
    }
    // TODO: Can we make more guesses?
    Box::new(args::LongOnlyParser::new())
}

fn parse_args() -> Result<bool, String> {
    let mut options = args::Options::new();
    let help_idx = options.push(
        args::OptionBuilder::default()
            .short('h')
            .long("help")
            .description("display this and exit")
            .build()
            .unwrap(),
    );
    let version_idx = options.push(
        args::OptionBuilder::default()
            .short('V')
            .long("version")
            .description("display version and exit")
            .build()
            .unwrap(),
    );
    let verbose_idx = options.push(
        args::OptionBuilder::default()
            .long("verbose")
            .description("be verbose")
            .build()
            .unwrap(),
    );

    let parser = guess_parser(&mut std::env::args());
    let maybe_args = parser.run(&mut options, &mut std::env::args());

    // help is special, check for it even if parser#run returned error.
    let ref help = options[help_idx];
    if help.is_set() {
        parser.print_help(&options);
        return Ok(true);
    }

    let args = maybe_args?;
    let ref version = options[version_idx];
    if version.is_set() {
        println!("Version is 0.0.1");
        return Ok(true);
    }
    let ref verbose = options[verbose_idx];
    println!("verbose: {}", verbose.is_set());
    println!("args: {:?}", args.args);
    Ok(false)
}

fn main() -> ExitCode {
    match parse_args() {
        Ok(exit) => {
            if exit {
                return ExitCode::SUCCESS;
            }
        }
        Err(msg) => {
            eprintln!("{}", msg);
            return ExitCode::FAILURE;
        }
    }

    ExitCode::SUCCESS
}