zgclp_boilerplate_with_debugging_support/
zgclp_boilerplate_with_debugging_support.rs

1// run with `cargo run --example zgclp_boilerplate_with_debugging_support -- ....`, e.g.:
2// cargo run --example zgclp_boilerplate_with_debugging_support -- -h
3// cargo run --example zgclp_boilerplate_with_debugging_support -- -n 1 xyz
4
5use std::env;
6
7use zgclp::{arg_parse_ahv, Arg};
8// use zgclp::{arg_parse, Arg}; // debug, in case you want to examine the behavior of arg_parse in more detail
9
10const DOC: &'static str = "Zgclp demonstration.
11
12Usage:
13  zgclp_boilerplate [options] [--] <arguments>...
14
15Options:
16  --help, -h        Show this message.
17  --version, -v     Show version info.
18  ....
19";
20
21fn main() {
22    let argv_store: Vec<String> = env::args().collect();
23    let argv: Vec<&str> = argv_store.iter().map(AsRef::as_ref).collect();
24
25    let mut args = Vec::<&str>::new();
26
27    // ** Sample options **
28    let mut output_file = None;
29    let mut dry_run = false;
30
31    let mut parse_results: Vec<(Arg, Option<usize>, Option<(usize, &str)>)> = Vec::new(); // debug
32
33    let mut arg_index = 1;
34    while arg_index < argv.len() {
35        let pr = arg_parse_ahv(&argv, arg_index, &mut args, DOC);
36        // let pr = arg_parse(&argv, arg_index); // debug, in case you want to examine the behavior of arg_parse in more detail
37        parse_results.push(pr); // debug
38        let eat = match pr {
39            // ** Sample option (with argument) **
40            (Arg::Option("-o" | "--output"), _, Some((eat, value))) => {
41                output_file = Some(value);
42                eat
43            }
44            // ** Sample option (w/o argument) **
45            (Arg::Option("-n" | "--dry-run"), Some(eat), _) => {
46                dry_run = true;
47                eat
48            }
49
50            // Skip arguments processed by zgclp / Error handling
51            (Arg::Processed, Some(eat), None) => eat,
52            (Arg::Option(name), _, _) => {
53                eprintln!(
54                    "Error: unknown option, or option missing argument: {}",
55                    name
56                );
57                std::process::exit(1);
58            }
59
60            // debug, in case you want to examine the behavior of arg_parse in more detail
61            (Arg::Value, None, Some((eat, _value))) => eat,
62            _ => {
63                panic!("Internal error in command-line parsing.");
64            }
65        };
66        arg_index += eat;
67    }
68
69    // debug
70    println!("parse_results:");
71    for (i, pr) in parse_results.iter().enumerate() {
72        println!("[{}] {:?}", i, pr);
73    }
74
75    // ** Sample stuff **
76    if let Some(n) = output_file {
77        println!("output_file = {}", n);
78    }
79    println!("dry_run: {:?}", dry_run);
80    println!("args = {:?}", args);
81}