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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
use std::{collections, env, process};
use super::*;

#[derive(Debug, Clone)]
/// The main class for parsing
pub struct ArgParser {
    /// The name of the program
    pub name: String,
    /// The author of the program
    pub author: String,
    /// The version of the program
    pub version: String,
    /// Copyright string
    pub copyright: String,
    /// Simple description of the program
    pub info: String,
    /// Example usage of the program
    pub usage: String,
    /// Vec holding all the arguments
    args: Vec<Arg>,
    /// Whether the program *has* to have arguments passed or not
    pub require_args: bool,
    /// Any extra arguments that were passed, but not parsed
    pub extra: Vec<String>,
}

impl ArgParser {
    /// Creates a new ArgParser using the first argument (the program) as the name. Creates help
    /// and version args by default
    pub fn from_argv0() -> Self {
        Self::new(&env::args().collect::<Vec<_>>()[0])
    }

    /// Creates a new ArgParser, with <name>. Creates help and version args by default
    pub fn new(name: &str) -> Self {
        let mut s = Self {
            name: String::from(name),
            author: String::new(),
            version: String::new(),
            copyright: String::new(),
            info: String::new(),
            usage: format!("{} [flags] [options]", name),
            args: Vec::new(),
            require_args: false,
            extra: Vec::new(),
        };

        s.args(vec!(
            Arg::bool("help", false)
            	.long("help")
                .help("Prints this dialogue"),
            Arg::bool("version", false)
            	.long("version")
                .help("Prints the version"),
        ));

        s
    }

    /// Sets the author
    pub fn author(&mut self, s: &str) -> &mut Self {
        self.author = String::from(s);
        self
    }

    /// Sets the version
    pub fn version(&mut self, s: &str) -> &mut Self {
        self.version = String::from(s);
        self
    }

    /// Sets the copyright
    pub fn copyright(&mut self, s: &str) -> &mut Self {
        self.copyright = String::from(s);
        self
    }

    /// Sets the info
    pub fn info(&mut self, s: &str) -> &mut Self {
        self.info = String::from(s);
        self
    }

    /// Sets the usage. Replaces all instances of {name} with the program's name.
    pub fn usage(&mut self, s: &str) -> &mut Self {
        self.usage = s.replace("{name}", &self.name);
        self
    }

    /// Sets whether the program needs arguments or not
    pub fn require_args(&mut self, b: bool) -> &mut Self {
        self.require_args = b;
        self
    }

    /// Adds the Vec<&mut Arg> to the parser's args
    pub fn args(&mut self, args: Vec<&mut Arg>) -> &mut Self{
        for arg in args {
            self.args.push(arg.clone());
        }
        self
    }

    fn set_arg(skip: &mut bool, arg: &mut Arg, next: Option<&String>) {
        if let ArgVal::Bool(b) = arg.val {
            arg.val = ArgVal::Bool(!b);
        } else if let Some(next) = next {
            if next.starts_with("--") || next.starts_with('-') {
                Self::error_exit(&format!("argument \"{}\" where value for \"{}\" should be", next, arg.name));
            }
            arg.val = ArgVal::Str(next.to_owned());
            *skip = true;
        } else {
            Self::error_exit(&format!("expected value for argument \"{}\"", arg.name));
        }
    }

    /// Returns a copy of the parser's current arguments in HashMap form using the ArgVal struct
    pub fn map_argval(&self) -> collections::HashMap<String, ArgVal> {
        let mut out = collections::HashMap::new();
        for arg in self.args.iter().cloned() {
            out.insert(arg.name, arg.val);
        }
        out
    }

    /// Returns a copy of the parser's current arguments in HashMap form using tuples
    pub fn map_tuple(&self) -> collections::HashMap<String, (bool, String)> {
        let mut out = collections::HashMap::new();
        for arg in self.args.iter().cloned() {
            let b = if let ArgVal::Bool(b) = arg.val {
                b
            } else {
                false
            };
            let s = if let ArgVal::Str(s) = arg.val {
                s
            } else {
                String::new()
            };
            out.insert(arg.name, (b, s));
        }
        out
    }

    /// Gets a String value arg by <name>. If no arg is found, default to String::new()
    pub fn get_str(&self, name: &str) -> String {
        for arg in &self.args {
            if arg.name == name {
                if let ArgVal::Str(s) = &arg.val {
                    return s.clone();
                }
            }
        }
        String::new()
    }

    /// Gets a bool value arg by <name>. If no arg is found, default to false
    pub fn get_bool(&self, name: &str) -> bool {
        for arg in &self.args {
            if arg.name == name {
                if let ArgVal::Bool(b) = &arg.val {
                    return *b;
                }
            }
        }
        false
    }

    /// Parse with env::args()
    pub fn parse(&mut self) -> &mut Self {
        let mut args = env::args();
        // First argument will always be the path to the program itself. next() removes that.
        args.next();
        self.parse_vec(args.collect::<Vec<String>>())
    }

    /// Parses a given Vec<String>
    pub fn parse_vec(&mut self, args: Vec<String>) -> &mut Self {
        if args.is_empty() && self.require_args {
            self.help_exit();
        }
        let mut skip = false;
        let mut done = false;
        for (idx,arg) in args.iter().enumerate() {
            if skip {skip = false; continue}
            if done {self.extra.push(arg.to_owned()); continue}
            if arg == "--" {done = true; continue}

            if let Some(arg) = arg.strip_prefix("--") {
                let mut exists = false;
                self.args.iter_mut()
                    .filter(|parg| parg.long != None)
                    .filter(|parg| parg.long.as_ref().unwrap() == arg)
                    .for_each(|mut parg| {Self::set_arg(&mut skip, &mut parg, args.get(idx+1)); exists = true});
                if !exists {Self::error_exit(&format!("unexpected argument \"{}\"", arg));}
            } else if let Some(arg) = arg.strip_prefix('-') {
                for ch in arg.chars() {
                    let mut exists = false;
                    self.args.iter_mut()
                        .filter(|parg| parg.short != None)
                        .filter(|parg| parg.short.unwrap() == ch)
                        .for_each(|mut parg| {Self::set_arg(&mut skip, &mut parg, args.get(idx+1)); exists = true});
                    if !exists {Self::error_exit(&format!("unexpected argument \"{}\"", arg));}
                }
            } else {
                done = true;
            }
        }
        if self.get_bool("help") {self.help_exit()}
        else if self.get_bool("version") {self.version_exit()}
        self
    }

    /// Prints help and exits
    pub fn help_exit(&self) {
        println!("{} {}\n{}\n{}\n{}\nUsage:\n\t{}\n",
            self.name,
            self.version,
            self.author,
            self.info,
            self.copyright,
            self.usage
        );

        let mut flags = Vec::new();
        let mut options = Vec::new();
        self.args.iter().for_each(|arg| {
            match arg.val {
                ArgVal::Bool(_) => flags.push(arg),
                ArgVal::Str(_) => options.push(arg),
            }
        });

        let mut longest = 0;
        self.args.iter().filter_map(|arg| arg.long.as_ref()).for_each(|l| if l.len() > longest {longest = l.len()});
        longest += 4;

        let print = |input: &Arg| {
            //               vv
            let mut long = "    ".to_string();
            let mut short = "  ".to_string();

            let input_long = if let Some(l) = &input.long {
                if input.short == None {
                    long = format!("  --{}", l);
                } else {
                    long = format!(", --{}", l);
                }
                l.clone()
            } else {
                String::new()
            };

            if let Some(ch) = input.short {
                short = format!("-{}", ch);
            }

            print!("\t{}{}", short, long);

            for _ in input_long.len()..longest {print!(" ")}
            println!("{}", input.help);
        };

        if !flags.is_empty() {
            println!("Flags:");
            flags.iter().for_each(|f| print(f));
        }

        if !options.is_empty() {
            println!("Options:");
            options.iter().for_each(|o| print(o));
        }
        process::exit(1);
    }

    /// Prints the version and exits
    pub fn version_exit(&self) {
        println!("{} {}", self.name, self.version);
        process::exit(1);
    }

    /// Prints error <message> and exits
    pub fn error_exit(message: &str) {
        eprintln!("Error: {}\nTry \"-h\" or \"--help\" for more information.", message);
        process::exit(1);
    }
}