parseopt.nim 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2015 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## This module provides the standard Nim command line parser.
  10. ## It supports one convenience iterator over all command line options and some
  11. ## lower-level features.
  12. ##
  13. ## Supported Syntax
  14. ## ================
  15. ##
  16. ## The following syntax is supported when arguments for the `shortNoVal` and
  17. ## `longNoVal` parameters, which are
  18. ## `described later<#nimshortnoval-and-nimlongnoval>`_, are not provided:
  19. ##
  20. ## 1. Short options: `-abcd`, `-e:5`, `-e=5`
  21. ## 2. Long options: `--foo:bar`, `--foo=bar`, `--foo`
  22. ## 3. Arguments: everything that does not start with a `-`
  23. ##
  24. ## These three kinds of tokens are enumerated in the
  25. ## `CmdLineKind enum<#CmdLineKind>`_.
  26. ##
  27. ## When option values begin with ':' or '=', they need to be doubled up (as in
  28. ## `--delim::`) or alternated (as in `--delim=:`).
  29. ##
  30. ## The `--` option, commonly used to denote that every token that follows is
  31. ## an argument, is interpreted as a long option, and its name is the empty
  32. ## string.
  33. ##
  34. ## Parsing
  35. ## =======
  36. ##
  37. ## Use an `OptParser<#OptParser>`_ to parse command line options. It can be
  38. ## created with `initOptParser<#initOptParser,string,set[char],seq[string]>`_,
  39. ## and `next<#next,OptParser>`_ advances the parser by one token.
  40. ##
  41. ## For each token, the parser's `kind`, `key`, and `val` fields give
  42. ## information about that token. If the token is a long or short option, `key`
  43. ## is the option's name, and `val` is either the option's value, if provided,
  44. ## or the empty string. For arguments, the `key` field contains the argument
  45. ## itself, and `val` is unused. To check if the end of the command line has
  46. ## been reached, check if `kind` is equal to `cmdEnd`.
  47. ##
  48. ## Here is an example:
  49. ##
  50. ## .. code-block::
  51. ## import std/parseopt
  52. ##
  53. ## var p = initOptParser("-ab -e:5 --foo --bar=20 file.txt")
  54. ## while true:
  55. ## p.next()
  56. ## case p.kind
  57. ## of cmdEnd: break
  58. ## of cmdShortOption, cmdLongOption:
  59. ## if p.val == "":
  60. ## echo "Option: ", p.key
  61. ## else:
  62. ## echo "Option and value: ", p.key, ", ", p.val
  63. ## of cmdArgument:
  64. ## echo "Argument: ", p.key
  65. ##
  66. ## # Output:
  67. ## # Option: a
  68. ## # Option: b
  69. ## # Option and value: e, 5
  70. ## # Option: foo
  71. ## # Option and value: bar, 20
  72. ## # Argument: file.txt
  73. ##
  74. ## The `getopt iterator<#getopt.i,OptParser>`_, which is provided for
  75. ## convenience, can be used to iterate through all command line options as well.
  76. ##
  77. ## To set a default value for a variable assigned through `getopt` and accept arguments from the cmd line.
  78. ## Assign the default value to a variable before parsing.
  79. ## Then set the variable to the new value while parsing.
  80. ##
  81. ## Here is an example:
  82. ## .. code-block::
  83. ## import std/parseopt
  84. ##
  85. ## var varName: string = "defaultValue"
  86. ##
  87. ## for kind, key, val in getopt():
  88. ## case kind
  89. ## of cmdArgument:
  90. ## discard
  91. ## of cmdLongOption, cmdShortOption:
  92. ## case key:
  93. ## of "varName": # --varName:<value> in the console when executing
  94. ## varName = val # do input sanitization in production systems
  95. ## of cmdEnd:
  96. ## discard
  97. ##
  98. ## `shortNoVal` and `longNoVal`
  99. ## ============================
  100. ##
  101. ## The optional `shortNoVal` and `longNoVal` parameters present in
  102. ## `initOptParser<#initOptParser,string,set[char],seq[string]>`_ are for
  103. ## specifying which short and long options do not accept values.
  104. ##
  105. ## When `shortNoVal` is non-empty, users are not required to separate short
  106. ## options and their values with a ':' or '=' since the parser knows which
  107. ## options accept values and which ones do not. This behavior also applies for
  108. ## long options if `longNoVal` is non-empty. For short options, `-j4`
  109. ## becomes supported syntax, and for long options, `--foo bar` becomes
  110. ## supported. This is in addition to the `previously mentioned
  111. ## syntax<#supported-syntax>`_. Users can still separate options and their
  112. ## values with ':' or '=', but that becomes optional.
  113. ##
  114. ## As more options which do not accept values are added to your program,
  115. ## remember to amend `shortNoVal` and `longNoVal` accordingly.
  116. ##
  117. ## The following example illustrates the difference between having an empty
  118. ## `shortNoVal` and `longNoVal`, which is the default, and providing
  119. ## arguments for those two parameters:
  120. ##
  121. ## .. code-block::
  122. ## import std/parseopt
  123. ##
  124. ## proc printToken(kind: CmdLineKind, key: string, val: string) =
  125. ## case kind
  126. ## of cmdEnd: doAssert(false) # Doesn't happen with getopt()
  127. ## of cmdShortOption, cmdLongOption:
  128. ## if val == "":
  129. ## echo "Option: ", key
  130. ## else:
  131. ## echo "Option and value: ", key, ", ", val
  132. ## of cmdArgument:
  133. ## echo "Argument: ", key
  134. ##
  135. ## let cmdLine = "-j4 --first bar"
  136. ##
  137. ## var emptyNoVal = initOptParser(cmdLine)
  138. ## for kind, key, val in emptyNoVal.getopt():
  139. ## printToken(kind, key, val)
  140. ##
  141. ## # Output:
  142. ## # Option: j
  143. ## # Option: 4
  144. ## # Option: first
  145. ## # Argument: bar
  146. ##
  147. ## var withNoVal = initOptParser(cmdLine, shortNoVal = {'c'},
  148. ## longNoVal = @["second"])
  149. ## for kind, key, val in withNoVal.getopt():
  150. ## printToken(kind, key, val)
  151. ##
  152. ## # Output:
  153. ## # Option and value: j, 4
  154. ## # Option and value: first, bar
  155. ##
  156. ## See also
  157. ## ========
  158. ##
  159. ## * `os module<os.html>`_ for lower-level command line parsing procs
  160. ## * `parseutils module<parseutils.html>`_ for helpers that parse tokens,
  161. ## numbers, identifiers, etc.
  162. ## * `strutils module<strutils.html>`_ for common string handling operations
  163. ## * `json module<json.html>`_ for a JSON parser
  164. ## * `parsecfg module<parsecfg.html>`_ for a configuration file parser
  165. ## * `parsecsv module<parsecsv.html>`_ for a simple CSV (comma separated value)
  166. ## parser
  167. ## * `parsexml module<parsexml.html>`_ for a XML / HTML parser
  168. ## * `other parsers<lib.html#pure-libraries-parsers>`_ for more parsers
  169. {.push debugger: off.}
  170. include "system/inclrtl"
  171. import os
  172. type
  173. CmdLineKind* = enum ## The detected command line token.
  174. cmdEnd, ## End of command line reached
  175. cmdArgument, ## An argument such as a filename
  176. cmdLongOption, ## A long option such as --option
  177. cmdShortOption ## A short option such as -c
  178. OptParser* = object of RootObj ## \
  179. ## Implementation of the command line parser.
  180. ##
  181. ## To initialize it, use the
  182. ## `initOptParser proc<#initOptParser,string,set[char],seq[string]>`_.
  183. pos: int
  184. inShortState: bool
  185. allowWhitespaceAfterColon: bool
  186. shortNoVal: set[char]
  187. longNoVal: seq[string]
  188. cmds: seq[string]
  189. idx: int
  190. kind*: CmdLineKind ## The detected command line token
  191. key*, val*: string ## Key and value pair; the key is the option
  192. ## or the argument, and the value is not "" if
  193. ## the option was given a value
  194. proc parseWord(s: string, i: int, w: var string,
  195. delim: set[char] = {'\t', ' '}): int =
  196. result = i
  197. if result < s.len and s[result] == '\"':
  198. inc(result)
  199. while result < s.len:
  200. if s[result] == '"':
  201. inc result
  202. break
  203. add(w, s[result])
  204. inc(result)
  205. else:
  206. while result < s.len and s[result] notin delim:
  207. add(w, s[result])
  208. inc(result)
  209. proc initOptParser*(cmdline: seq[string], shortNoVal: set[char] = {},
  210. longNoVal: seq[string] = @[];
  211. allowWhitespaceAfterColon = true): OptParser =
  212. ## Initializes the command line parser.
  213. ##
  214. ## If `cmdline.len == 0`, the real command line as provided by the
  215. ## `os` module is retrieved instead if it is available. If the
  216. ## command line is not available, a `ValueError` will be raised.
  217. ## Behavior of the other parameters remains the same as in
  218. ## `initOptParser(string, ...)
  219. ## <#initOptParser,string,set[char],seq[string]>`_.
  220. ##
  221. ## See also:
  222. ## * `getopt iterator<#getopt.i,seq[string],set[char],seq[string]>`_
  223. runnableExamples:
  224. var p = initOptParser()
  225. p = initOptParser(@["--left", "--debug:3", "-l", "-r:2"])
  226. p = initOptParser(@["--left", "--debug:3", "-l", "-r:2"],
  227. shortNoVal = {'l'}, longNoVal = @["left"])
  228. result.pos = 0
  229. result.idx = 0
  230. result.inShortState = false
  231. result.shortNoVal = shortNoVal
  232. result.longNoVal = longNoVal
  233. result.allowWhitespaceAfterColon = allowWhitespaceAfterColon
  234. if cmdline.len != 0:
  235. result.cmds = newSeq[string](cmdline.len)
  236. for i in 0..<cmdline.len:
  237. result.cmds[i] = cmdline[i]
  238. else:
  239. when declared(paramCount):
  240. result.cmds = newSeq[string](paramCount())
  241. for i in countup(1, paramCount()):
  242. result.cmds[i-1] = paramStr(i)
  243. else:
  244. # we cannot provide this for NimRtl creation on Posix, because we can't
  245. # access the command line arguments then!
  246. doAssert false, "empty command line given but" &
  247. " real command line is not accessible"
  248. result.kind = cmdEnd
  249. result.key = ""
  250. result.val = ""
  251. proc initOptParser*(cmdline = "", shortNoVal: set[char] = {},
  252. longNoVal: seq[string] = @[];
  253. allowWhitespaceAfterColon = true): OptParser =
  254. ## Initializes the command line parser.
  255. ##
  256. ## If `cmdline == ""`, the real command line as provided by the
  257. ## `os` module is retrieved instead if it is available. If the
  258. ## command line is not available, a `ValueError` will be raised.
  259. ##
  260. ## `shortNoVal` and `longNoVal` are used to specify which options
  261. ## do not take values. See the `documentation about these
  262. ## parameters<#nimshortnoval-and-nimlongnoval>`_ for more information on
  263. ## how this affects parsing.
  264. ##
  265. ## This does not provide a way of passing default values to arguments.
  266. ##
  267. ## See also:
  268. ## * `getopt iterator<#getopt.i,OptParser>`_
  269. runnableExamples:
  270. var p = initOptParser()
  271. p = initOptParser("--left --debug:3 -l -r:2")
  272. p = initOptParser("--left --debug:3 -l -r:2",
  273. shortNoVal = {'l'}, longNoVal = @["left"])
  274. initOptParser(parseCmdLine(cmdline), shortNoVal, longNoVal, allowWhitespaceAfterColon)
  275. proc handleShortOption(p: var OptParser; cmd: string) =
  276. var i = p.pos
  277. p.kind = cmdShortOption
  278. if i < cmd.len:
  279. add(p.key, cmd[i])
  280. inc(i)
  281. p.inShortState = true
  282. while i < cmd.len and cmd[i] in {'\t', ' '}:
  283. inc(i)
  284. p.inShortState = false
  285. if i < cmd.len and (cmd[i] in {':', '='} or
  286. card(p.shortNoVal) > 0 and p.key[0] notin p.shortNoVal):
  287. if i < cmd.len and cmd[i] in {':', '='}:
  288. inc(i)
  289. p.inShortState = false
  290. while i < cmd.len and cmd[i] in {'\t', ' '}: inc(i)
  291. p.val = substr(cmd, i)
  292. p.pos = 0
  293. inc p.idx
  294. else:
  295. p.pos = i
  296. if i >= cmd.len:
  297. p.inShortState = false
  298. p.pos = 0
  299. inc p.idx
  300. proc next*(p: var OptParser) {.rtl, extern: "npo$1".} =
  301. ## Parses the next token.
  302. ##
  303. ## `p.kind` describes what kind of token has been parsed. `p.key` and
  304. ## `p.val` are set accordingly.
  305. runnableExamples:
  306. var p = initOptParser("--left -r:2 file.txt")
  307. p.next()
  308. doAssert p.kind == cmdLongOption and p.key == "left"
  309. p.next()
  310. doAssert p.kind == cmdShortOption and p.key == "r" and p.val == "2"
  311. p.next()
  312. doAssert p.kind == cmdArgument and p.key == "file.txt"
  313. p.next()
  314. doAssert p.kind == cmdEnd
  315. if p.idx >= p.cmds.len:
  316. p.kind = cmdEnd
  317. return
  318. var i = p.pos
  319. while i < p.cmds[p.idx].len and p.cmds[p.idx][i] in {'\t', ' '}: inc(i)
  320. p.pos = i
  321. setLen(p.key, 0)
  322. setLen(p.val, 0)
  323. if p.inShortState:
  324. p.inShortState = false
  325. if i >= p.cmds[p.idx].len:
  326. inc(p.idx)
  327. p.pos = 0
  328. if p.idx >= p.cmds.len:
  329. p.kind = cmdEnd
  330. return
  331. else:
  332. handleShortOption(p, p.cmds[p.idx])
  333. return
  334. if i < p.cmds[p.idx].len and p.cmds[p.idx][i] == '-':
  335. inc(i)
  336. if i < p.cmds[p.idx].len and p.cmds[p.idx][i] == '-':
  337. p.kind = cmdLongOption
  338. inc(i)
  339. i = parseWord(p.cmds[p.idx], i, p.key, {' ', '\t', ':', '='})
  340. while i < p.cmds[p.idx].len and p.cmds[p.idx][i] in {'\t', ' '}: inc(i)
  341. if i < p.cmds[p.idx].len and p.cmds[p.idx][i] in {':', '='}:
  342. inc(i)
  343. while i < p.cmds[p.idx].len and p.cmds[p.idx][i] in {'\t', ' '}: inc(i)
  344. # if we're at the end, use the next command line option:
  345. if i >= p.cmds[p.idx].len and p.idx < p.cmds.len and
  346. p.allowWhitespaceAfterColon:
  347. inc p.idx
  348. i = 0
  349. if p.idx < p.cmds.len:
  350. p.val = p.cmds[p.idx].substr(i)
  351. elif len(p.longNoVal) > 0 and p.key notin p.longNoVal and p.idx+1 < p.cmds.len:
  352. p.val = p.cmds[p.idx+1]
  353. inc p.idx
  354. else:
  355. p.val = ""
  356. inc p.idx
  357. p.pos = 0
  358. else:
  359. p.pos = i
  360. handleShortOption(p, p.cmds[p.idx])
  361. else:
  362. p.kind = cmdArgument
  363. p.key = p.cmds[p.idx]
  364. inc p.idx
  365. p.pos = 0
  366. when declared(quoteShellCommand):
  367. proc cmdLineRest*(p: OptParser): string {.rtl, extern: "npo$1".} =
  368. ## Retrieves the rest of the command line that has not been parsed yet.
  369. ##
  370. ## See also:
  371. ## * `remainingArgs proc<#remainingArgs,OptParser>`_
  372. ##
  373. ## **Examples:**
  374. ##
  375. ## .. code-block::
  376. ## var p = initOptParser("--left -r:2 -- foo.txt bar.txt")
  377. ## while true:
  378. ## p.next()
  379. ## if p.kind == cmdLongOption and p.key == "": # Look for "--"
  380. ## break
  381. ## doAssert p.cmdLineRest == "foo.txt bar.txt"
  382. result = p.cmds[p.idx .. ^1].quoteShellCommand
  383. proc remainingArgs*(p: OptParser): seq[string] {.rtl, extern: "npo$1".} =
  384. ## Retrieves a sequence of the arguments that have not been parsed yet.
  385. ##
  386. ## See also:
  387. ## * `cmdLineRest proc<#cmdLineRest,OptParser>`_
  388. ##
  389. ## **Examples:**
  390. ##
  391. ## .. code-block::
  392. ## var p = initOptParser("--left -r:2 -- foo.txt bar.txt")
  393. ## while true:
  394. ## p.next()
  395. ## if p.kind == cmdLongOption and p.key == "": # Look for "--"
  396. ## break
  397. ## doAssert p.remainingArgs == @["foo.txt", "bar.txt"]
  398. result = @[]
  399. for i in p.idx..<p.cmds.len: result.add p.cmds[i]
  400. iterator getopt*(p: var OptParser): tuple[kind: CmdLineKind, key,
  401. val: string] =
  402. ## Convenience iterator for iterating over the given
  403. ## `OptParser<#OptParser>`_.
  404. ##
  405. ## There is no need to check for `cmdEnd` while iterating. If using `getopt`
  406. ## with case switching, checking for `cmdEnd` is required.
  407. ##
  408. ## See also:
  409. ## * `initOptParser proc<#initOptParser,string,set[char],seq[string]>`_
  410. ##
  411. ## **Examples:**
  412. ##
  413. ## .. code-block::
  414. ## # these are placeholders, of course
  415. ## proc writeHelp() = discard
  416. ## proc writeVersion() = discard
  417. ##
  418. ## var filename: string
  419. ## var p = initOptParser("--left --debug:3 -l -r:2")
  420. ##
  421. ## for kind, key, val in p.getopt():
  422. ## case kind
  423. ## of cmdArgument:
  424. ## filename = key
  425. ## of cmdLongOption, cmdShortOption:
  426. ## case key
  427. ## of "help", "h": writeHelp()
  428. ## of "version", "v": writeVersion()
  429. ## of cmdEnd: assert(false) # cannot happen
  430. ## if filename == "":
  431. ## # no filename has been given, so we show the help
  432. ## writeHelp()
  433. p.pos = 0
  434. p.idx = 0
  435. while true:
  436. next(p)
  437. if p.kind == cmdEnd: break
  438. yield (p.kind, p.key, p.val)
  439. iterator getopt*(cmdline: seq[string] = @[],
  440. shortNoVal: set[char] = {}, longNoVal: seq[string] = @[]):
  441. tuple[kind: CmdLineKind, key, val: string] =
  442. ## Convenience iterator for iterating over command line arguments.
  443. ##
  444. ## This creates a new `OptParser<#OptParser>`_. If no command line
  445. ## arguments are provided, the real command line as provided by the
  446. ## `os` module is retrieved instead.
  447. ##
  448. ## `shortNoVal` and `longNoVal` are used to specify which options
  449. ## do not take values. See the `documentation about these
  450. ## parameters<#nimshortnoval-and-nimlongnoval>`_ for more information on
  451. ## how this affects parsing.
  452. ##
  453. ## There is no need to check for `cmdEnd` while iterating. If using `getopt`
  454. ## with case switching, checking for `cmdEnd` is required.
  455. ##
  456. ## See also:
  457. ## * `initOptParser proc<#initOptParser,seq[string],set[char],seq[string]>`_
  458. ##
  459. ## **Examples:**
  460. ##
  461. ## .. code-block::
  462. ##
  463. ## # these are placeholders, of course
  464. ## proc writeHelp() = discard
  465. ## proc writeVersion() = discard
  466. ##
  467. ## var filename: string
  468. ## let params = @["--left", "--debug:3", "-l", "-r:2"]
  469. ##
  470. ## for kind, key, val in getopt(params):
  471. ## case kind
  472. ## of cmdArgument:
  473. ## filename = key
  474. ## of cmdLongOption, cmdShortOption:
  475. ## case key
  476. ## of "help", "h": writeHelp()
  477. ## of "version", "v": writeVersion()
  478. ## of cmdEnd: assert(false) # cannot happen
  479. ## if filename == "":
  480. ## # no filename has been written, so we show the help
  481. ## writeHelp()
  482. var p = initOptParser(cmdline, shortNoVal = shortNoVal,
  483. longNoVal = longNoVal)
  484. while true:
  485. next(p)
  486. if p.kind == cmdEnd: break
  487. yield (p.kind, p.key, p.val)
  488. {.pop.}