getopt3 2.6.1

Zero dependency 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
/*
 * Copyright (c) Radim Kolar 2013, 2018, 2023, 2025.
 * SPDX-License-Identifier: MIT
 *
 * getopt3 library is licensed under MIT license:
 *   https://spdx.org/licenses/MIT.html
*/

//!  # getopt(3) parser
//!
//!  ### Command line argument parser with GNU parsing rules and double dash '--' support.
//!
//!  `getopt3::`[`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.
//!
//!  An element that starts with '-' (and is not exactly "-" or "--") is an option element.
//!  The characters of this element (aside from the initial '-') are option characters.
//!  A double dash `--` indicates the end of options; any arguments following
//!  it are treated as positional arguments.
//!
//!  #### Example
//!  ```rust
//!  use std::env::args;
//!  use getopt3::hideBin;
//!  let rc = getopt3::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 has {} 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.
//!
//!  [`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)]

#![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)]

// If crate feature "no_std" is turned on and we are not running
//   tests, turn no_std attribute on to avoid linking with
//   std library.
#![cfg_attr(all(feature = "no_std", not(test)), no_std)]

#[cfg(not(feature = "no_std"))]
use { std::collections::HashMap,
      std::io::ErrorKind,
      std::io::Error,
      std::io::Result
};

#[cfg(feature = "no_std")]
extern crate alloc;

#[cfg(feature = "no_std")]
use {
   alloc::collections::BTreeMap as HashMap,
   alloc::vec::Vec,
   alloc::format,
   alloc::string::String,
   alloc::string::ToString,
   core::error::Error
};

/**
Parsed command line options.

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

Structure can contain options that are not listed in *optstring*
passed to [`new`] function. 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 optional values extracted from command line arguments.

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

   This map contains all recognized options.
   The presence 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, bool>
}

impl getopt {
   /**
     Returns number of command line arguments not counting options.

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

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

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

   /**
      Returns `Iterator` over command line arguments.

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

      #### Note

      Options are skipped by the `Iterator`.

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

      let getopt_rc = getopt3::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.

      It is a convenience shortcut for *getopt.options.get()*.

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

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

      let getopt_rc = getopt3::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 was supplied on command line.

      It is a convenience shortcut for *getopt.options.contains_key()*.

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

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

      let getopt_rc = getopt3::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 getopt3::hideBin;

      let getopt_rc = getopt3::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 `Iterator` over arguments.
*/
impl IntoIterator for getopt {
    type Item = String;
    type IntoIter = std::vec::IntoIter<String>;

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

/**
  Iterates over arguments without consuming getopt.
*/
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 and non-POSIX mode.
  Call [`validate`] on result to detect missing arguments and unknown options.

  POSIX parsing mode is not yet supported.

  ## 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. Can optionally start with ':' for compatibility
                   with optstring using POSIX extension allowing use '?'
                   as option character. Can not be empty or contain only ":".

  ## Parsing rules
  1. GNU argument parsing rules. This means that options can be anywhere on
     the command line before --
  1. Double dash -- support. Everything after -- is not treated as options.
  1. Long options are not supported.
  1. Multiple options not requiring argument can be chained together.
     -abc is the same as -a -b -c
  1. Last chained option can have an argument.
     -abcpasta is the same as -a -b -c pasta
  1. Argument does not require space. -wfile is the same as -w file
  1. optional argument `::` GNU optstring extension is not implemented.
  1. Strict POSIX parse mode where first non option stops option parsing is not 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 a required argument is missing function _new()_ still returns succesfully
     and the missing argument will be replaced by an empty String.

  ### 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.

[`validate`]: ./fn.validate.html
*/
pub fn new(arg: impl IntoIterator<Item=impl AsRef<str>>, optstring: impl AsRef<str>) -> Result<getopt> {
    let mut opts = HashMap::new();
    let mut args = Vec::new();
    let mut next_opt: Option<char> = None;
    let mut stop_parsing = false;

    let options_map = build_options_map(validate_optstring(optstring.as_ref())?);

    for element in arg {
        let element = element.as_ref();
        if stop_parsing {
            args.push(element.to_string());
        } else if let Some(next_opt_char) = next_opt {
            opts.insert(next_opt_char, element.to_string());
            next_opt = None;
        } else {
            match parseElement(&element, &options_map) {
                Ok((omap, el, nopt)) => {
                    opts.extend(omap);
                    if let Some(el_str) = el {
                        args.push(el_str);
                    }
                    next_opt = nopt;
                }
                Err(_) => stop_parsing = true,
            }
        }
    }

    // HANDLE MISSING ARGUMENT FOR LAST OPTION
    if let Some(next_opt_char) = next_opt {
        opts.insert(next_opt_char, String::new());
    }

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

/**
  Checks if optstring is valid.

  optstring can't have double "::", be empty or be only ":".
  allowed optstring characters are 7-bit ASCII letters, digits and '?'.
*/
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 {
      for c in optstring.chars() {
         match c {
            'a'..='z' => Ok(()),
            'A'..='Z' => Ok(()),
            '0'..='9' => Ok(()),
                 '?'  => Ok(()),
                 ':'  => Ok(()),
                   _  => Err(Error::new(ErrorKind::InvalidInput, "unsupported characters in optstring"))
         }?
      }
      if optstring.contains("::") {
         Err(Error::new(ErrorKind::InvalidInput, "double ':' are not permited in optstring"))
      } else {
         Ok(optstring)
      }
   }
}

/**
 * Build options map from validated optstring.
 *
 * returns map <option,hasArgument>
*/
fn build_options_map(optstring: &str) -> HashMap<char, bool> {
   let mut rc : HashMap<char, bool> = HashMap::with_capacity(optstring.len());
   let mut previous: char = ':';
   let mut insert_one = |c:char| -> () { match c {
         ':' if previous != ':' => rc.insert(*&previous,true),
          _  if previous != ':' => rc.insert(*&previous,false),
          _ => None
   }; previous = 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
}

/**
   parse Command line Element

   @param element command line element (one word on command line)
   @returns map(Option->value). If option is unknown value is null, otherwise
              value is option or "" if option do not have argument.
            String - command line argument or null if element is option type.
            Character - what option will be next element or null for none.
*/
fn parseElement(element: &str, options_map: &HashMap<char, bool>) ->
         Result<(HashMap<char,String>, Option<String>, Option<char>)> {

      if( element == "--" ) {
        Err( Error::new(ErrorKind::UnexpectedEof, "no more arguments") )
      } else
      if( element.is_empty() ) {
        Err( Error::new(ErrorKind::InvalidInput, "element must not be empty") )
      } else
      if( ! element.starts_with('-') || element == "-" ) {
         Ok( (HashMap::new(), Some(element.to_string()), None ) )
      } else
      {
           // parsing options block starting with -
           let mut opts = HashMap::<char,String>::new();
           let mut argfollows = false;
           let mut opt_name: Option<char> = None;
           let mut opt_argument = String::new();

           for opt in element.chars().skip(1) {
              if( argfollows == true ) {
               // ARGUMENT FOLLOWS TO END OF ELEMENT
               opt_argument.push(opt);
             } else {
                match options_map.get(&opt) {
                   None => {
                      // UNKNOWN OPTION
                      opts.insert(opt, String::new());
                   }
                   Some(optarg) => {
                      // KNOWN OPTION
                      if( *optarg == true ) {
                         // OPTION WITH ARGUMENT
                         argfollows = true;
                         opt_name = Some(opt);
                       } else {
                         // OPTION WITHOUT ARGUMENT
                         opts.insert(opt, String::new());
                      }
                   }
                }
             }
           }
           // RETURN RESULT
           if ( argfollows == true ) {
              if ( opt_argument.is_empty() ) {
                 // ARGUMENT FOLLOWS IN NEXT ELEMENT
                 Ok ( (opts, None, opt_name) )
              } else {
                 // SAVE ARGUMENT INTO MAP
                 opts.insert(opt_name.unwrap(), opt_argument);
                 Ok ( ( opts, None, None ) )
              }
           } else {
              // ONLY SHORT OPTIONS
              Ok ( (opts, None, None ) )
           }
      }
}


/**
* Validate parsed options in strict mode.
*
* ## Success
*
*   If strict mode validation passes, unchanged argument wrapped in a [`Result`]
*   is returned.
*
* ## Errors
*
*   Returns [`Err`] if option not listed in optstring is encountered or
*   required argument for an option is missing.
*
* #### Example
* ```rust
* use std::env::args;
* use getopt3::hideBin;
*
* let rc = getopt3::new(hideBin(args()), "ab:c");
* if let Ok(g) = rc {
*    // command line parsed sucessfully
*    // validate options for missing arguments
*    if let Ok(g) = getopt3::validate(g) {
*       // command arguments are valid, we can use them
*       if let Some(_) = g.get('b') {
*          // -a option found on command line
*       };
*    };
*  };
* ```
**/
pub fn validate(getopt: getopt) -> Result<getopt> {
    // validate unknown options
    for opt in getopt.options.keys() {
        if !getopt.option_has_arg.contains_key(opt) {
            return Err(Error::new(ErrorKind::InvalidInput, format!("Unknown option -{}", opt)));
        }
    }

    // validate missing arguments
    for (opt,_) in getopt.option_has_arg.iter().filter(|(_,arg)| **arg) {
        if let Some(val) = getopt.options.get(opt) {
            if val.is_empty() {
                return Err(Error::new(ErrorKind::InvalidInput, format!("Option -{} does not have required argument", 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 getopt3::hideBin;
 *
 * let rc = getopt3::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)
}

// include posix mode parsing code (work in progress)
#[cfg(feature = "posix")]
include!("getopt_posix.rs");

// unit tests

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

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

#[cfg(test)]
#[path = "getopt_validate_tests.rs"]
mod validations;

#[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 idx;