pure/parseopt2

  Source   Edit

argument parser (akin to POSIX getopt)

Can handle:

-c c_val
-c:c_val
-c=c_val
-abcc_val
-abc c_val
-abc:c_val
-abc=c_val
--long val
--long:val
--long=val
--long=
(empty value)

-- -positional1 --positional2

  • is treated as positional

-- skipped once; everything after this is treated as positional --- is treated as long arg "-"

-: undefined behavior (separator after dash)

Types

Opt = object
  case kind*: OptKind
  of short:
      keyShort*: char

  of long:
      keyLong*: string

  of positional:
      nil

  value*: string
  error*: OptError
  Source   Edit
OptError {.pure.} = enum
  none, missing,            ## missing required value (when optValRequired) (after parsing all the args, last opt need value)
  extraneous                 ## extra value not needed (when optValNone)
  Source   Edit
OptKind {.pure.} = enum
  short,                    ## -s
  long,                     ## --long
  positional                 ## positional
  Source   Edit
OptValExpectation = enum
  optValRequired,           ## must have value
  optValNone,               ## must not have value
  optValOptional             ## value is optional
                             ## has : -k:v -k=v
                             ## has : -kv  (please don't rely on this behavior)
                             ## none: -k v
Should I expect this option to have a value or not? yes: -k=v no : -k ("bare" option)   Source   Edit

Consts

defaultOptSeparators = {'=', ':'}
  Source   Edit
posixOptSeparators = {'='}
  Source   Edit

Procs

proc `==`(a, b: Opt): bool {....raises: [], tags: [].}
  Source   Edit

Iterators

iterator opts(argv: openArray[string];
              shortDefault: OptValExpectation = optValNone;
              longDefault: OptValExpectation = optValOptional;
              shortVal: openArray[(char, OptValExpectation)] = [];
              longVal: openArray[(string, OptValExpectation)] = [];
              sep: set[char] = defaultOptSeparators): Opt {....raises: [], tags: [].}

Parse command-line arguments like POSIX getopt(3)

shortDefault: default expectation of if a short option should receive value longDefault: like shortDefault, but for long options shortVal: expectation for short options longVal: expectation for long options

See [OptValExpectation] for more info about what those parameters mean

Example:

for opt in opts(["-abc"], optValNone, shortVal={'b': optValRequired}):
  discard opt
  Source   Edit