This module provides the standard Nim command line parser. It supports one convenience iterator over all command line options and some lower-level features.
Supported syntax:
-abcd
, where a, b, c, d are names--foo:bar
, --foo=bar
or --foo
CmdLineKind = enum cmdEnd, ## end of command line reached cmdArgument, ## argument detected cmdLongOption, ## a long option ``--option`` detected cmdShortOption ## a short option ``-c`` detected
OptParser = object of RootObj cmd: seq[string] pos: int remainingShortOptions: string kind*: CmdLineKind ## the dected command line token key*, val*: TaintedString ## key and value pair; ``key`` is the option ## or the argument, ``value`` is not "" if ## the option was given a value
GetoptResult = tuple[kind: CmdLineKind, key, val: TaintedString]
proc initOptParser(cmdline: seq[string]): OptParser {.gcsafe, raises: [], tags: [ReadIOEffect].}
proc initOptParser(cmdline: string): OptParser {.gcsafe, deprecated, raises: [], tags: [ReadIOEffect].}
proc initOptParser(): OptParser {.raises: [], tags: [ReadIOEffect].}
proc next(p: var OptParser) {.gcsafe, extern: "npo2$1", raises: [Exception], tags: [RootEffect].}
proc cmdLineRest(p: OptParser): TaintedString {.gcsafe, extern: "npo2$1", deprecated, raises: [], tags: [].}
iterator getopt(p: var OptParser): GetoptResult {.raises: [Exception], tags: [RootEffect].}
var p = initOptParser("--left --debug:3 -l=4 -r:2") for kind, key, val in p.getopt(): case kind of cmdArgument: filename = key of cmdLongOption, cmdShortOption: case key of "help", "h": writeHelp() of "version", "v": writeVersion() of cmdEnd: assert(false) # cannot happen if filename == "": # no filename has been given, so we show the help: writeHelp()
iterator getopt(): GetoptResult {.raises: [Exception], tags: [ReadIOEffect, RootEffect].}
for kind, key, val in getopt(): # this will iterate over all arguments passed to the cmdline. continue
© 2006–2017 Andreas Rumpf
Licensed under the MIT License.
https://nim-lang.org/docs/parseopt2.html