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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
//! A minimalist library for parsing command line arguments.
//!
//! ## Features
//!
//! * Long-form boolean flags with single-character shortcuts: `--flag`, `-f`.
//! * Long-form string-valued options with single-character shortcuts: `--option <arg>`, `-o <arg>`.
//! * Condensed short-form options: `-abc <arg> <arg>`.
//! * Automatic `--help` and `--version` flags.
//! * Support for multivalued options.
//! * Support for git-style command interfaces with arbitrarily-nested commands.
//!
//! ## Example
//!
//! ```
//! # use arguably::ArgParser;
//! let mut parser = ArgParser::new()
//!     .helptext("Usage: foobar...")
//!     .version("1.0")
//!     .flag("foo f")
//!     .option("bar b");
//!
//! if let Err(err) = parser.parse() {
//!     err.exit();
//! }
//!
//! if parser.found("foo").unwrap() {
//!     println!("Found --foo/-f flag.");
//! }
//!
//! if let Some(value) = parser.value("bar").unwrap() {
//!     println!("Found --bar/-b option with value: {}", value);
//! }
//!
//! for arg in parser.args {
//!     println!("Arg: {}", arg);
//! }
//! ```

use std::collections::HashMap;
use std::fmt;
use std::error;


/// Error types returned by the library.
#[derive(Debug)]
pub enum Error {
    /// Returned when the parser detects an unregistered flag, option, or command name,
    /// either among the command line arguments or in an API call.
    InvalidName(String),

    /// Returned when the parser detects an option with a missing value.
    MissingValue(String),

    /// Returned when the parser detects a help command with a missing argument.
    MissingHelpArg,

    /// Returned when the command line arguments are not valid unicode strings.
    InvalidUnicode,
}


impl error::Error for Error {}


impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Error::InvalidName(msg) =>  write!(f, "Error: {}", msg),
            Error::MissingValue(msg) =>  write!(f, "Error: {}", msg),
            Error::MissingHelpArg => write!(f, "Error: missing argument for the help command"),
            Error::InvalidUnicode => write!(f, "Error: arguments are not valid unicode strings"),
        }
    }
}


impl Error {
    /// Prints an error message to `stderr` and exits with a non-zero status code.
    pub fn exit(self) -> ! {
        eprintln!("{}.", self);
        std::process::exit(1);
    }
}


/// An ArgParser instance can be intialized using the builder pattern.
///
/// ```
/// # use arguably::ArgParser;
/// let parser = ArgParser::new()
///     .helptext("Usage: appname...")
///     .version("1.0")
///     .flag("foo f")
///     .option("bar b");
/// ```
pub struct ArgParser {
    helptext: Option<String>,
    version: Option<String>,
    options: Vec<Opt>,
    option_map: HashMap<String, usize>,
    flags: Vec<Flag>,
    flag_map: HashMap<String, usize>,
    commands: Vec<ArgParser>,
    command_map: HashMap<String, usize>,
    callback: Option<fn(&str, &ArgParser)>,
    auto_help_cmd: bool,

    /// Stores positional arguments.
    pub args: Vec<String>,

    /// Stores the command name, if a command was found.
    pub cmd_name: Option<String>,

    /// Stores the command's `ArgParser` instance, if a command was found.
    pub cmd_parser: Option<Box<ArgParser>>,
}


impl ArgParser {
    /// Creates a new ArgParser instance.
    pub fn new() -> ArgParser {
        ArgParser {
            helptext: None,
            version: None,
            args: Vec::new(),
            options: Vec::new(),
            option_map: HashMap::new(),
            flags: Vec::new(),
            flag_map: HashMap::new(),
            commands: Vec::new(),
            command_map: HashMap::new(),
            cmd_name: None,
            callback: None,
            auto_help_cmd: false,
            cmd_parser: None,
        }
    }

    /// Sets the parser's helptext string. Supplying a helptext string activates support
    /// for an automatic `--help` flag, also a `-h` shortcut if not registered by another
    /// option.
    ///
    /// ```
    /// # use arguably::ArgParser;
    /// let parser = ArgParser::new()
    ///     .helptext("Usage: appname...");
    /// ```
    pub fn helptext<S>(mut self, text: S) -> Self where S: Into<String> {
        self.helptext = Some(text.into());
        self
    }

    /// Sets the parser's version string. Supplying a version string activates support
    /// for an automatic `--version` flag, also a `-v` shortcut if not registered by another
    /// option.
    ///
    /// ```
    /// # use arguably::ArgParser;
    /// let parser = ArgParser::new()
    ///     .version("1.0");
    /// ```
    pub fn version<S>(mut self, text: S) -> Self where S: Into<String> {
        self.version = Some(text.into());
        self
    }

    /// Registers a new option. The `name` parameter accepts an unlimited number of
    /// space-separated aliases and single-character shortcuts.
    ///
    /// ```
    /// # use arguably::ArgParser;
    /// let parser = ArgParser::new()
    ///     .option("name1 name2 n");
    /// ```
    pub fn option(mut self, name: &str) -> Self {
        self.options.push(Opt {
            values: Vec::new(),
        });
        let index = self.options.len() - 1;
        for alias in name.split_whitespace() {
            self.option_map.insert(alias.to_string(), index);
        }
        self
    }

    /// Registers a new flag. The `name` parameter accepts an unlimited number of
    /// space-separated aliases and single-character shortcuts.
    ///
    /// ```
    /// # use arguably::ArgParser;
    /// let parser = ArgParser::new()
    ///     .flag("name1 name2 n");
    /// ```
    pub fn flag(mut self, name: &str) -> Self {
        self.flags.push(Flag {
            count: 0,
        });
        let index = self.flags.len() - 1;
        for alias in name.split_whitespace() {
            self.flag_map.insert(alias.to_string(), index);
        }
        self
    }

    /// Registers a new command. The name parameter accepts an unlimited number of
    /// space-separated aliases. The command's helptext, flags, and options can be
    /// registered on the command's ArgParser instance.
    ///
    /// ```
    /// # use arguably::ArgParser;
    /// let mut parser = ArgParser::new()
    ///     .helptext("Usage: appname...")
    ///     .command("cmdname", ArgParser::new()
    ///         .helptext("Usage: appname cmdname...")
    ///         .flag("cmdflag")
    ///     );
    /// ```
    pub fn command(mut self, name: &str, cmd_parser: ArgParser) -> Self {
        if cmd_parser.helptext.is_some() {
            self.auto_help_cmd = true;
        }
        self.commands.push(cmd_parser);
        let index = self.commands.len() - 1;
        for alias in name.split_whitespace() {
            self.command_map.insert(alias.to_string(), index);
        }
        self
    }

    /// Registers a callback function on a command parser. If the command is found the
    /// function will be called and passed the command name and a reference to the
    /// command's `ArgParser` instance.
    pub fn callback(mut self, f: fn(&str, &ArgParser)) -> Self {
        self.callback = Some(f);
        self
    }

    /// Toggles support for an automatic `help` command which prints subcommand helptext. The `help`
    /// command is automatically activated when a command with helptext is registered.
    pub fn help_command(mut self, enable: bool) -> Self {
        self.auto_help_cmd = enable;
        self
    }

    /// Returns the value of the named option. Returns `Error::InvalidName` if `name` is not a
    /// registered option name. Returns `None` if the option was not found.
    pub fn value(&self, name: &str) -> Result<Option<String>, Error> {
        if let Some(index) = self.option_map.get(name) {
            if let Some(value) = self.options[*index].values.last() {
                return Ok(Some(value.to_string()));
            }
            return Ok(None);
        }
        Err(Error::InvalidName(format!("'{}' is not a registered option name", name)))
    }

    /// Returns the named option's list of values. Returns `Error::InvalidName` if `name` is not a
    /// registered option name.
    pub fn values(&self, name: &str) -> Result<Vec<String>, Error> {
        if let Some(index) = self.option_map.get(name) {
            return Ok(self.options[*index].values.clone());
        }
        Err(Error::InvalidName(format!("'{}' is not a registered option name", name)))
    }

    /// Returns the number of times the named flag or option was found. Returns `Error::InvalidName`
    /// if `name` is not a registered flag or option name.
    pub fn count(&self, name: &str) -> Result<usize, Error> {
        if let Some(index) = self.flag_map.get(name) {
            return Ok(self.flags[*index].count);
        }
        if let Some(index) = self.option_map.get(name) {
            return Ok(self.options[*index].values.len());
        }
        Err(Error::InvalidName(format!("'{}' is not a registered flag or option name", name)))
    }

    /// Returns `true` if the named flag or option was found. Returns `Error::InvalidName` if `name`
    /// is not a registered flag or option name.
    pub fn found(&self, name: &str) -> Result<bool, Error> {
        match self.count(name) {
            Ok(count) => Ok(count > 0),
            Err(err) => Err(err),
        }
    }

    /// Parse the program's command line arguments.
    ///
    /// ```
    /// # let mut parser = arguably::ArgParser::new();
    /// if let Err(err) = parser.parse() {
    ///     err.exit();
    /// }
    /// ```
    pub fn parse(&mut self) -> Result<(), Error> {
        let mut strings = Vec::<String>::new();
        for os_string in std::env::args_os().skip(1) {
            if let Ok(string) = os_string.into_string() {
                strings.push(string);
            } else {
                return Err(Error::InvalidUnicode);
            }
        }
        let mut stream = ArgStream::new(strings);
        self.parse_argstream(&mut stream)?;
        Ok(())
    }

    /// Parse a vector of strings. This function is intended for testing only.
    pub fn parse_args(&mut self, args: Vec<&str>) -> Result<(), Error> {
        let strings = args.iter().map(|s| s.to_string()).collect();
        let mut stream = ArgStream::new(strings);
        self.parse_argstream(&mut stream)?;
        Ok(())
    }

    fn parse_argstream(&mut self, argstream: &mut ArgStream) -> Result<(), Error> {
        let mut is_first_arg = true;

        while argstream.has_next() {
            let arg = argstream.next();

            if arg == "--" {
                while argstream.has_next() {
                    self.args.push(argstream.next());
                }
            }

            else if arg.starts_with("--") {
                if arg.contains("=") {
                    self.handle_equals_opt(&arg)?;
                } else {
                    self.handle_long_opt(&arg, argstream)?;
                }
            }

            else if arg.starts_with("-") {
                if arg == "-" || arg.chars().nth(1).unwrap().is_numeric() {
                    self.args.push(arg);
                } else if arg.contains("=") {
                    self.handle_equals_opt(&arg)?;
                } else {
                    self.handle_short_opt(&arg, argstream)?;
                }
            }

            else if is_first_arg && self.command_map.contains_key(&arg) {
                let index = self.command_map.get(&arg).unwrap();
                let mut cmd_parser = self.commands.remove(*index);
                self.command_map.clear();
                self.commands.clear();
                cmd_parser.parse_argstream(argstream)?;
                if let Some(callback) = cmd_parser.callback {
                    callback(&arg, &cmd_parser);
                }
                self.cmd_name = Some(arg);
                self.cmd_parser = Some(Box::new(cmd_parser));
            }

            else if is_first_arg && arg == "help" && self.auto_help_cmd {
                if argstream.has_next() {
                    let name = argstream.next();
                    if let Some(index) = self.command_map.get(&name) {
                        let cmd_parser = &mut self.commands[*index];
                        let helptext = cmd_parser.helptext.as_deref().unwrap_or("").trim();
                        println!("{}", helptext);
                        std::process::exit(0);
                    } else {
                        return Err(Error::InvalidName(
                            format!("'{}' is not a recognised command name", &name)
                        ));
                    }
                } else {
                    return Err(Error::MissingHelpArg);
                }
            }

            else {
                self.args.push(arg);
            }

            is_first_arg = false;
        }

        Ok(())
    }

    fn handle_long_opt(&mut self, arg: &str, argstream: &mut ArgStream) -> Result<(), Error> {
        if let Some(index) = self.flag_map.get(&arg[2..]) {
            self.flags[*index].count += 1;
        } else if let Some(index) = self.option_map.get(&arg[2..]) {
            if argstream.has_next() {
                self.options[*index].values.push(argstream.next());
            } else {
                return Err(Error::MissingValue(format!("missing value for {}", arg)));
            }
        } else if arg == "--help" && self.helptext.is_some() {
            println!("{}", self.helptext.as_ref().unwrap().trim());
            std::process::exit(0);
        } else if arg == "--version" && self.version.is_some() {
            println!("{}", self.version.as_ref().unwrap().trim());
            std::process::exit(0);
        } else {
            return Err(Error::InvalidName(
                format!("{} is not a recognised flag or option name", arg)
            ));
        }
        Ok(())
    }

    fn handle_short_opt(&mut self, arg: &str, argstream: &mut ArgStream) -> Result<(), Error> {
        for c in arg.chars().skip(1) {
            if let Some(index) = self.flag_map.get(&c.to_string()) {
                self.flags[*index].count += 1;
            } else if let Some(index) = self.option_map.get(&c.to_string()) {
                if argstream.has_next() {
                    self.options[*index].values.push(argstream.next());
                } else {
                    let msg = if arg.chars().count() > 2 {
                        format!("missing value for '{}' in {}", c, arg)
                    } else {
                        format!("missing value for {}", arg)
                    };
                    return Err(Error::MissingValue(msg));
                }
            } else if c == 'h' && self.helptext.is_some() {
                println!("{}", self.helptext.as_ref().unwrap().trim());
                std::process::exit(0);
            } else if c == 'v' && self.version.is_some() {
                println!("{}", self.version.as_ref().unwrap().trim());
                std::process::exit(0);
            } else {
                let msg = if arg.chars().count() > 2 {
                    format!("'{}' in {} is not a recognised flag or option name", c, arg)
                } else {
                    format!("{} is not a recognised flag or option name", arg)
                };
                return Err(Error::InvalidName(msg));
            }
        }
        Ok(())
    }

    fn handle_equals_opt(&mut self, arg: &str) -> Result<(), Error> {
        let splits: Vec<&str> = arg.splitn(2, '=').collect();
        let name = splits[0];
        let value = splits[1];

        if let Some(index) = self.option_map.get(name.trim_start_matches('-')) {
            if value == "" {
                return Err(Error::MissingValue(format!("missing value for {}", name)));
            } else {
                self.options[*index].values.push(value.to_string());
                return Ok(());
            }
        }
        return Err(Error::InvalidName(format!("{} is not a recognised option name", name)));
    }
}


struct ArgStream {
    args: Vec<String>,
    index: usize,
}


impl ArgStream {
    fn new(args: Vec<String>) -> ArgStream {
        ArgStream {
            args: args,
            index: 0,
        }
    }

    fn has_next(&self) -> bool {
        self.index < self.args.len()
    }

    fn next(&mut self) -> String {
        self.index += 1;
        self.args[self.index - 1].clone()
    }
}


struct Opt {
    values: Vec<String>,
}


struct Flag {
    count: usize,
}