getopt2 0.1.0

Zero dependency strict command line argument parser
Documentation
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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
/*
 * Copyright (c) Radim Kolar 2013, 2018, 2023, 2025, 2026
 * SPDX-License-Identifier: MIT
 *
 * getopt2 library is licensed under MIT license:
 *   https://spdx.org/licenses/MIT.html
*/

//!  # getopt2 command line parser
//!
//!  # Main features
//!
//!  1. Unknown / incomplete options are turned into positional arguments.
//!  1. GNU getopt flexible argument parsing rules. Options and
//!     positional arguments can be mixed.
//!  1. Double dash `--` support for options / arguments separation.
//!  1. POSIX mode parsing when optstring starts with "+". First non option
//!     stops options parsing, rest is parsed as positional arguments.
//!  1. Optional argument support "::". Optional argument is separated by space.
//!  1. Allow use of "?" as option character.
//!     Always active, supported compatibility with getopt extension
//!     when optstring starts with ":".
//!  1. Parsing is not strict. If *optstring* is correct, parsing never fails.
//!
//!  `getopt2::`[`new`] parses the command line elements and isolates arguments from options.
//!  It returns a [`getopt`] structure where you can query options and use isolated arguments.
//!
//!  A 2 characters long element that starts with `-` (and is not exactly `--`) is an option element.
//!  The character following the initial `-` is an option character.
//!
//!  A double dash `--` can be used to indicate the end of options; any arguments following
//!  it are treated as positional arguments.
//!
//!  Option values are separated from option element with spaces.
//!
//!  #### See also
//!
//!  Alternative [getopt3 parser](https://crates.io/crates/getopt3/) have
//!  almost identical API but with different feature set. Main difference is
//!  that *getopt3* doesn't turn unrecognised / incomplete options into
//!  positional arguments.
//!
//!  #### Example
//!  ```rust
//!  use std::env::args;
//!  use getopt2::hideBin;
//!  let rc = getopt2::new(hideBin(args()), "ab:c");
//!  if let Ok(g) = rc {
//!     // command line options parsed sucessfully
//!     if let Some(str) = g.options.get(&'b') {
//!        // handle b argument
//!        println!("option -b have {} argument", str);
//!     };
//!  };
//!  ```
//!  #### Reference
//!
//!  1. [POSIX getopt](https://pubs.opengroup.org/onlinepubs/9799919799/functions/getopt.html) function.
//!  1. [GNU libc getopt](https://www.gnu.org/software/libc/manual/html_node/Using-Getopt.html) function.
//!  1. [FreeBSD getopt](https://man.freebsd.org/cgi/man.cgi?query=getopt&apropos=0&sektion=3&arch=default&format=html) function.
//!  1. [getopt3 parser](https://crates.io/crates/getopt3/) crate.
//!
//!  [`new`]: ./fn.new.html
//!  [`getopt`]: ./struct.getopt.html

#![forbid(unsafe_code)]
#![forbid(missing_docs)]
#![allow(non_camel_case_types)]
#![allow(unused_parens)]
#![allow(non_snake_case)]
#![allow(unused_doc_comments)]
#![deny(rustdoc::bare_urls)]
#![deny(rustdoc::broken_intra_doc_links)]
#![deny(rustdoc::missing_crate_level_docs)]
#![deny(rustdoc::invalid_codeblock_attributes)]
#![deny(rustdoc::invalid_rust_codeblocks)]

use std::io::Result;
use std::io::Error;
use std::io::ErrorKind;
use std::collections::HashMap;

/**
Parsed command line options.

Created by [`new`] function. Structure contains isolated
positional command line arguments and collected options
with their required or optional values.

For strict parse mode pass this structure to [`validate`] function.

[`new`]: ./fn.new.html
[`validate`]: ./fn.validate.html
*/
pub struct getopt {
   /**
   Map of command line options and their required or optional values
   extracted from command line arguments.

   If an option does not have a value, an empty String "" is stored.
   */
   pub options: HashMap<char, String>,
   /** Isolated positional command line arguments without options. */
   pub arguments: Vec<String>,
   /** Map indicating whether an option has a required or optional argument.

   This map contains all recognized options.
   Inclusion of an option in this map does not mean that the option must always
   be present or supplied as a command line argument.
   */
   pub option_has_arg: HashMap<char, argument>,
}

/**
  Information if option have an argument.
*/
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum argument {
   /** No argument */
   NO,
   /** Has required argument */
   YES,
   /** Optional argument */
   OPTIONAL,
}

impl getopt {
   /**
     Returns number of positional command line arguments.

     Its convience shortcut for getopt.arguments.len().
     Options are not included in this count.

     #### Example
     ```rust
     use std::env::args;
     use getopt2::hideBin;

     let getopt_rc = getopt2::new(hideBin(args()), "ab:c");
     if let Ok(g) = getopt_rc {
        println!("Number of command line arguments is {}", g.len());
     };
     ```
   */
   pub fn len(&self) -> usize {
      self.arguments.len()
   }

   /**
      Returns Iterator over positional command line arguments.

      #### Example
      ```rust
      use std::env::args;
      use getopt2::hideBin;

      let getopt_rc = getopt2::new(hideBin(args()), "abc");
      if let Ok(my_getopt) = getopt_rc {
         for arg in my_getopt.iter() {
            println!("Argument: {}", arg);
         }
      }
      ```
   */
   pub fn iter(&self) -> std::slice::Iter<'_, String> {
      self.arguments.iter()
   }

   /**
      Return command line option value.

      Its convience shortcut for getopt.options.get()

      #### Return value
      1. If option were supplied on command line returned value is `Some`.
      1. If option doesn't have argument or argument is
         optional, reference to empty `String` is returned.
      1. If option were not supplied by user returned value is `None`.

      #### Example
      ```rust
      use std::env::args;
      use getopt2::hideBin;

      let getopt_rc = getopt2::new(hideBin(args()), "ab:c");
      if let Ok(my_getopt) = getopt_rc {
         if let Some(b_value) = my_getopt.get('b') {
            println!("-b argument is: {}", b_value);
         }
      }
      ```
   */
   pub fn get(&self, option: char) -> Option<&String> {
      self.options.get(&option)
   }

   /**
      Check if command line option were supplied on command line.

      Its convience shortcut for getopt.options.contains_key()

      #### Return value
      1. If option were supplied on command line returned value is `true`.
      1. If option were not supplied by user returned value is `false`.

      #### Example
      ```rust
      use std::env::args;
      use getopt2::hideBin;

      let getopt_rc = getopt2::new(hideBin(args()), "ab:c");
      if let Ok(my_getopt) = getopt_rc {
         if my_getopt.has('b') {
            println!("-b argument is: {}", my_getopt.get('b').unwrap());
         }
      }
      ```
   */
   pub fn has(&self, option: char) -> bool {
      self.options.contains_key(&option)
   }

   /**
      Check if any non option arguments were supplied.

      It is a convenience shortcut for *getopt.arguments.is_empty()*.

      #### Return value
      1. If any arguments were supplied on the command line returned value is `true`.
      1. If no arguments were supplied on the command line returned value is `false`.

      #### Example
      ```rust
      use std::env::args;
      use getopt2::hideBin;

      let getopt_rc = getopt2::new(hideBin(args()), "ab:c");
      if let Ok(my_getopt) = getopt_rc {
         if !my_getopt.is_empty() {
            println!("Arguments were supplied on command line");
         }
      }
      ```
   */
   pub fn is_empty(&self) -> bool {
      self.arguments.is_empty()
   }
}

/**
  Access to positional arguments by index.
*/
impl std::ops::Index<usize> for getopt {
    type Output = String;

    fn index(&self, index: usize) -> &Self::Output {
        self.arguments.index(index)
    }
}

/**
  Consumes getopt and returns an iterator over positional arguments.
*/
impl IntoIterator for getopt {
   type Item = String;
   type IntoIter = std::vec::IntoIter<String>;

   fn into_iter(self) -> Self::IntoIter {
      self.arguments.into_iter()
   }
}

/**
  Iterator over positional arguments references.
*/
impl<'a> IntoIterator for &'a getopt {
   type Item = &'a String;
   type IntoIter = std::slice::Iter<'a, String>;

   fn into_iter(self) -> Self::IntoIter {
      self.arguments.iter()
   }
}

/**
  Parse command line arguments.

  Parses command line arguments using GNU getopt(3) parsing rules with
  double dash "--" support.
  Long arguments starting with double dash "--" are not supported.

  Parsing is done in non strict mode. POSIX parsing mode
  can be activated if optstring starts with plus "+".

  Call [`validate`] on result to detect unknown options or
  missing required option values.

  ## Arguments

  * `arg` - String Iterator with command line arguments. Can be empty.

  * `optstring` - List of legitimate alphanumeric plus '?' option characters.
    If character is followed by colon, the option requires
    an argument. If character is followed by double colon, the option
    have optional value argument.
    optstring must not be empty and must include at least one option.
  ## Parsing rules
  1. GNU argument parsing rules.
     It means that options and arguments can be anywhere in command line
     before double dash `--`.
  1. Double dash `--` support. Everything after `--` is not treated as options.
  1. Long options are not supported.
  1. Multiple options *can not* be grouped together.
     Example: writing *-abc* instead of *-a -b -c* is not supported.
  1. Option value *must be* separated by space. Example: *-w file*
  1. Optional argument `::` GNU optstring extension is implemented, argument
     must be separated by space.
  1. POSIX parse mode where first non option stops option parsing is supported.
     This mode is triggered in GNU getopt by setting `POSIXLY_CORRECT` variable or by
     optstring starting with a plus sign `+`.
  1. The POSIX-specified extension for the *getopt* function, which allows the optstring to
     start with a colon (:), is always supported.
     This extension enables the use of the '?' character as a command-line option.
     We *always allow* use of the '?' as option without need to manually activate it using
     optstring.
     Starting optstring with ':' is possible and supported as valid syntax.

  ## Errors
  1. Parsing error **only happens** if optstring parameter is invalid or empty.
  1. If required argument is missing function _new()_ still returns succesfully
     and turns option into positional argument.
  1. Unrecognised options are turned into positional arguments as well.

  ### See also
  1. [GNU libc getopt](https://www.gnu.org/software/libc/manual/html_node/Using-Getopt.html) function.
  1. [POSIX getopt](https://pubs.opengroup.org/onlinepubs/9799919799/functions/getopt.html) function.
  1. [FreeBSD getopt](https://man.freebsd.org/cgi/man.cgi?query=getopt&apropos=0&sektion=3&arch=default&format=html) function.

[`validate`]: ./fn.validate.html
*/
pub fn new(arg: impl IntoIterator<Item = impl AsRef<str>>, optstring: impl AsRef<str>) -> Result<getopt> {
   /** output options values */
   let mut opts = HashMap::new();
   /** output argument list */
   let mut args = Vec::new();
   /** option for previous loop iteration */
   let mut next_opt: Option<char> = None;
   /** are we still parsing or we just copying rest of arguments */
   let mut stop_parsing = false;
   /** map of options -> having an argument */
   let options_map: HashMap<char,argument> = build_options_map(validate_optstring(optstring.as_ref())?);
   /** is posix mode enabled */
   let posix: bool = optstring.as_ref().starts_with("+") || std::env::var("POSIXLY_CORRECT").is_ok();

   for el in arg {
      let element = el.as_ref();
      if stop_parsing {
         // we do not parse options anymore all what's left
         // are arguments
         args.push(element.to_string());
      } else if let Some(next_opt_char) = next_opt {
         // option with possible parameter in previous loop iteration
         match options_map.get(&next_opt_char) {
            Some(argument::YES) => {
               // option with mandatory argument
               opts.insert(next_opt_char, element.to_string());
               next_opt = None;
            },
            Some(argument::OPTIONAL) => {
               // option with an optional argument
               if is_option(element, &options_map) {
                  // current element is an option
                  // push prev. option without an arg
                  opts.insert(next_opt_char, String::from(""));
                  next_opt = Some(element.as_bytes()[1] as char);
               } else if element.eq("--") {
                  // current element is a separator
                  // push prev. option without an arg
                  opts.insert(next_opt_char, String::from(""));
                  // and stop parsing
                  stop_parsing = true;
                  next_opt = None;
               } else {
                  // current element is an argument
                  opts.insert(next_opt_char, element.to_string());
                  next_opt = None;
               }
            },
            Some(argument::NO) => {
               // previous option have no argument
               // push it to opts
               opts.insert(next_opt_char, String::from(""));
               // is current element option or argument
               if is_option(element, &options_map) {
                  next_opt = Some(element.as_bytes()[1] as char);
               } else if element.eq("--") {
                  stop_parsing = true;
                  next_opt = None;
               } else {
                 args.push(element.to_string());
                 next_opt = None;
                 if ( posix ) { stop_parsing = true; };
               }
            }
            None => {
               // unknown option, should not happen
               let mut s = String::from("-");
               s.push(next_opt_char);
               args.push(s);
            }
         }
      } else if element.eq("--") {
         stop_parsing = true;
         next_opt = None;
      } else {
               // is current element option or argument
               if is_option(element, &options_map) {
                  next_opt = Some(element.as_bytes()[1] as char);
               } else {
                 args.push(element.to_string());
                 if ( posix ) { stop_parsing = true };
               }

      }
   }

   // HANDLE MISSING ARGUMENT FOR LAST OPTION
   if let Some(next_opt_char) = next_opt {
      match options_map.get(&next_opt_char) {
            Some(argument::YES) | None => {
               // option with mandatory argument
               // option argument is no more possible
               // push option as argument
               let mut s = String::from("-");
               s.push(next_opt_char);
               args.push(s);
            },
            Some(argument::NO) | Some(argument::OPTIONAL) => {
               // store option itself
               opts.insert(next_opt_char, String::from(""));
            }
      }
   }

   Ok(getopt {
      options: opts,
      arguments: args,
      option_has_arg: options_map,
   })
}

/**
  Check if string reference is an option.

  To pass check following conditions must be true:
  1. string is exactly 2 characters long
  1. string must start with a '-'
  1. second char must be in options map
*/
fn is_option(opt: &str, options_map: &HashMap<char, argument>) -> bool {
  if ( opt.chars().count() == 2 ) {
    if ( opt.starts_with('-') ) {
      let second_char: char = opt.chars().nth(1).unwrap();
      options_map.contains_key(&second_char)
    } else {
      // not starts with a '-'
      false
   }
  } else {
    // length not 2
    false
  }
}

/**
  Check if string reference can be an option.

  To pass check following conditions must be true:
  1. string reference is exactly 2 characters long
  1. string must start with a '-'
  1. opstring validation must pass
*/
fn is_possible_option(opt: &str) -> bool {
  if ( opt.chars().count() == 2 ) {
    if ( opt.starts_with('-') ) {
      let possible_optstring: String = opt.chars().skip(1).collect();
      validate_optstring(&possible_optstring).is_ok()
    } else {
      // not starts with a '-'
      false
   }
  } else {
    // length not 2
    false
  }
}


/**
  Checks if optstring is valid.

  ### Validation rules
  1. optstring can't contain triple ':::'
  1. optstring can't be empty
  1. allowed option characters are a-z A-Z 0-9 and '?'

  ### Implemented extensions
  1. if optstring starts with ':' then use of '?' is allowed.
     This extension is always active; You do not need to start
     optstring with ':' to enable '?'.
  1. optional arguments. If two semicolons '::' follows argument, it is an
     optional argument.
  1. POSIX mode. If string *starts with* '+' then parser will run in
     strict POSIX mode. In this case ':' extension can be second character
     '+:'. If '+' appears at any other position validation fails.
*/
fn validate_optstring(optstring: &str) -> Result<&str> {
   if optstring.is_empty() {
      Err(Error::new(ErrorKind::UnexpectedEof, "optstring can't be empty"))
   } else if optstring.eq(":") {
      Err(Error::new(ErrorKind::UnexpectedEof, "optstring can't be only ':'"))
   } else if optstring.eq("+") {
      Err(Error::new(ErrorKind::UnexpectedEof, "optstring can't be only '+'"))
   } else if optstring.eq("+:") {
      Err(Error::new(ErrorKind::UnexpectedEof, "optstring can't be only '+:'"))
   } else {
      // check for valid optstring characters
      for c in optstring.chars() {
         match c {
            'a'..='z' => Ok(()),
            'A'..='Z' => Ok(()),
            '0'..='9' => Ok(()),
            '?' => Ok(()),
            ':' => Ok(()),
            '+' => Ok(()),
            _ => Err(Error::new(
               ErrorKind::InvalidInput,
               "unsupported character in optstring. Only a-z A-Z 0-9 and ?:+ are allowed",
            )),
         }?
      }
      let plus = optstring.rfind("+");
      if plus.unwrap_or(0) > 0 {
         Err(Error::new(ErrorKind::InvalidInput, "plus sign '+' must be first character"))
      } else if optstring.contains(":::") {
         Err(Error::new(ErrorKind::InvalidInput, "triple ':' are not permited in optstring"))
      } else if optstring.starts_with("::") {
         Err(Error::new(ErrorKind::InvalidInput, "optstring can't start with '::'"))
      } else if optstring.starts_with("+::") {
         Err(Error::new(ErrorKind::InvalidInput, "optstring can't start with '+::'"))
      } else {
         Ok(optstring)
      }
   }
}

/**
 * Build options map from *validated* optstring.
 *
 * returns map <option,argument>
*/
fn build_options_map(optstring: &str) -> HashMap<char, argument> {
   let mut rc: HashMap<char, argument> = HashMap::with_capacity(optstring.len());
   let mut previous1: char = ':';
   let mut previous2: char = ':';
   let mut insert_one = |c: char| -> () {
      match c {
         ':' if previous1 != ':' && previous1 != '+' => rc.insert(*&previous1, argument::YES),
         ':' if previous1 == ':' && previous2 != ':' => rc.insert(*&previous2, argument::OPTIONAL),
         '+' => None,
         _ if previous1 != ':' && previous1 != '+' => rc.insert(*&previous1, argument::NO),
         _ => None,
      };
      previous2 = previous1;
      previous1 = c;
   };

   for c in optstring.chars() {
      insert_one(c);
   }
   // re-run option map building logic on last character in optstring if it is not ':'
   // if last character is ':', it has been already inserted to map and running it
   // again would cause insertion of ':' into options map because it is previous character
   optstring.chars().last().filter(|c| *c != ':').into_iter().for_each(|c| insert_one(c));
   rc
}

/**
  Validate parsed options in strict mode.

  Function is doing two validations:
  1. checks if some required option arguments are missing.
  1. checks for options used but not listed in optstring.

  ## Success

  If strict mode validation passes, unchanged argument wrapped in [`Result`]
  is returned.

  ## Errors

  Returns [`Err`] if:
  1. option not listed in optstring is encountered or
  1. required argument for an option is missing.
*/
pub fn validate(getopt: getopt) -> Result<getopt> {
   // validate missing required arguments
   for (opt, _) in getopt.option_has_arg.iter().filter(|(_, arg)| **arg == argument::YES) {
      let mut opt_string = String::from("-");
      opt_string.push(*opt);
      if getopt.arguments.contains(&opt_string) {
            return Err(Error::new(
               ErrorKind::InvalidInput,
               format!("Option -{} does not have required argument", opt),
            ));
      }
   }

   // validate unknown options
   for opt in getopt.arguments.iter() {
      if is_possible_option(opt) {
         return Err(Error::new(ErrorKind::InvalidInput, format!("Unknown option -{}", opt)));
      }
   }

   Ok(getopt)
}

/**
 * Removes first element from the IntoIterator.
 *
 * This utility function is supposed to be used on value returned by
 * `std::env::args()` before passing it to [`new`].
 *
 * First argument returned by `args()` corresponds to the program
 * executable name and its undesirable to have program name included
 * between parsed arguments.
 *
 * This function exists for making code more readable and because
 * widely used [yargs npm](https://www.npmjs.com/package/yargs) argument
 * parser have same function.
 *
 * `hideBin` function can be replaced by calling `.skip(1)`
 * on `Iterator` before passing it to [`new`]. Choose what is more
 * readable for you.
 *
 * #### Example
 * ```rust
 * use std::env::args;
 * use getopt2::hideBin;
 *
 * let rc = getopt2::new(hideBin(args()), "ab:c");
 * if let Ok(g) = rc {
 *    // command line options parsed sucessfully
 *    if let Some(_) = g.options.get(&'a') {
 *       // -a option found on command line
 *    };
 *  };
 * ```
 * [`new`]: ./fn.new.html
*/
pub fn hideBin(argv: impl IntoIterator<Item = String>) -> impl IntoIterator<Item = String> {
   argv.into_iter().skip(1)
}

// unit tests

#[cfg(test)]
#[path = "getopt_helpers_tests.rs"]
mod helpers;

#[cfg(test)]
#[path = "getopt_tests.rs"]
mod tests;

#[cfg(test)]
#[path = "getopt_posix_tests.rs"]
mod posix_tests;

#[cfg(test)]
#[path = "getopt_validate_api_tests.rs"]
mod validateapi;

#[cfg(test)]
#[path = "getopt_hidebin_tests.rs"]
mod hidebin;

#[cfg(test)]
#[path = "getopt_doubledash_tests.rs"]
mod doubledash;

#[cfg(test)]
#[path = "getopt_iterator_tests.rs"]
mod it;

#[cfg(test)]
#[path = "getopt_index_tests.rs"]
mod index;