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:
- short options - -abcd, where a, b, c, d are names
- long option - --foo:bar, --foo=bar or --foo
- argument - everything else
Types
CmdLineKind = enum cmdEnd, ## end of command line reached cmdArgument, ## argument detected cmdLongOption, ## a long option ``--option`` detected cmdShortOption ## a short option ``-c`` detected
- the detected command line token Source Edit
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
- this object implements the command line parser Source Edit
GetoptResult = tuple[kind: CmdLineKind, key, val: TaintedString]
- Source Edit
Procs
proc initOptParser(cmdline: seq[string]): OptParser {.
gcsafe, raises: [], tags: [ReadIOEffect].}- Initalizes option parses with cmdline. cmdline should not contain argument 0 - program name. If cmdline == nil default to current command line arguments. Source Edit
proc initOptParser(cmdline: string): OptParser {.
gcsafe, deprecated, raises: [], tags: [ReadIOEffect].}- Initalizes option parses with cmdline. Splits cmdline in on spaces and calls initOptParser(openarray[string]) Do not use. Source Edit
proc initOptParser(): OptParser {.
raises: [], tags: [ReadIOEffect].}- Initializes option parser from current command line arguments. Source Edit
proc next(p: var OptParser) {.
gcsafe, extern: "npo2$1", raises: [Exception], tags: [RootEffect].}- Source Edit
proc cmdLineRest(p: OptParser): TaintedString {.
gcsafe, extern: "npo2$1", deprecated, raises: [], tags: [].}- Returns part of command line string that has not been parsed yet. Do not use - does not correctly handle whitespace. Source Edit
Iterators
iterator getopt(): GetoptResult {.
raises: [Exception], tags: [ReadIOEffect, RootEffect].}-
This is an convenience iterator for iterating over the command line. This uses the OptParser object. Example:
var filename = "" for kind, key, val in 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()
Source Edit