Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

README.md 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  1. A light, featureful and explicit option parsing library for node.js.
  2. [Why another one? See below](#why). tl;dr: The others I've tried are one of
  3. too loosey goosey (not explicit), too big/too many deps, or ill specified.
  4. YMMV.
  5. Follow <a href="https://twitter.com/intent/user?screen_name=trentmick" target="_blank">@trentmick</a>
  6. for updates to node-dashdash.
  7. # Install
  8. npm install dashdash
  9. # Usage
  10. ```javascript
  11. var dashdash = require('dashdash');
  12. // Specify the options. Minimally `name` (or `names`) and `type`
  13. // must be given for each.
  14. var options = [
  15. {
  16. // `names` or a single `name`. First element is the `opts.KEY`.
  17. names: ['help', 'h'],
  18. // See "Option specs" below for types.
  19. type: 'bool',
  20. help: 'Print this help and exit.'
  21. }
  22. ];
  23. // Shortcut form. As called it infers `process.argv`. See below for
  24. // the longer form to use methods like `.help()` on the Parser object.
  25. var opts = dashdash.parse({options: options});
  26. console.log("opts:", opts);
  27. console.log("args:", opts._args);
  28. ```
  29. # Longer Example
  30. A more realistic [starter script "foo.js"](./examples/foo.js) is as follows.
  31. This also shows using `parser.help()` for formatted option help.
  32. ```javascript
  33. var dashdash = require('./lib/dashdash');
  34. var options = [
  35. {
  36. name: 'version',
  37. type: 'bool',
  38. help: 'Print tool version and exit.'
  39. },
  40. {
  41. names: ['help', 'h'],
  42. type: 'bool',
  43. help: 'Print this help and exit.'
  44. },
  45. {
  46. names: ['verbose', 'v'],
  47. type: 'arrayOfBool',
  48. help: 'Verbose output. Use multiple times for more verbose.'
  49. },
  50. {
  51. names: ['file', 'f'],
  52. type: 'string',
  53. help: 'File to process',
  54. helpArg: 'FILE'
  55. }
  56. ];
  57. var parser = dashdash.createParser({options: options});
  58. try {
  59. var opts = parser.parse(process.argv);
  60. } catch (e) {
  61. console.error('foo: error: %s', e.message);
  62. process.exit(1);
  63. }
  64. console.log("# opts:", opts);
  65. console.log("# args:", opts._args);
  66. // Use `parser.help()` for formatted options help.
  67. if (opts.help) {
  68. var help = parser.help({includeEnv: true}).trimRight();
  69. console.log('usage: node foo.js [OPTIONS]\n'
  70. + 'options:\n'
  71. + help);
  72. process.exit(0);
  73. }
  74. // ...
  75. ```
  76. Some example output from this script (foo.js):
  77. ```
  78. $ node foo.js -h
  79. # opts: { help: true,
  80. _order: [ { name: 'help', value: true, from: 'argv' } ],
  81. _args: [] }
  82. # args: []
  83. usage: node foo.js [OPTIONS]
  84. options:
  85. --version Print tool version and exit.
  86. -h, --help Print this help and exit.
  87. -v, --verbose Verbose output. Use multiple times for more verbose.
  88. -f FILE, --file=FILE File to process
  89. $ node foo.js -v
  90. # opts: { verbose: [ true ],
  91. _order: [ { name: 'verbose', value: true, from: 'argv' } ],
  92. _args: [] }
  93. # args: []
  94. $ node foo.js --version arg1
  95. # opts: { version: true,
  96. _order: [ { name: 'version', value: true, from: 'argv' } ],
  97. _args: [ 'arg1' ] }
  98. # args: [ 'arg1' ]
  99. $ node foo.js -f bar.txt
  100. # opts: { file: 'bar.txt',
  101. _order: [ { name: 'file', value: 'bar.txt', from: 'argv' } ],
  102. _args: [] }
  103. # args: []
  104. $ node foo.js -vvv --file=blah
  105. # opts: { verbose: [ true, true, true ],
  106. file: 'blah',
  107. _order:
  108. [ { name: 'verbose', value: true, from: 'argv' },
  109. { name: 'verbose', value: true, from: 'argv' },
  110. { name: 'verbose', value: true, from: 'argv' },
  111. { name: 'file', value: 'blah', from: 'argv' } ],
  112. _args: [] }
  113. # args: []
  114. ```
  115. See the ["examples"](examples/) dir for a number of starter examples using
  116. some of dashdash's features.
  117. # Environment variable integration
  118. If you want to allow environment variables to specify options to your tool,
  119. dashdash makes this easy. We can change the 'verbose' option in the example
  120. above to include an 'env' field:
  121. ```javascript
  122. {
  123. names: ['verbose', 'v'],
  124. type: 'arrayOfBool',
  125. env: 'FOO_VERBOSE', // <--- add this line
  126. help: 'Verbose output. Use multiple times for more verbose.'
  127. },
  128. ```
  129. then the **"FOO_VERBOSE" environment variable** can be used to set this
  130. option:
  131. ```shell
  132. $ FOO_VERBOSE=1 node foo.js
  133. # opts: { verbose: [ true ],
  134. _order: [ { name: 'verbose', value: true, from: 'env' } ],
  135. _args: [] }
  136. # args: []
  137. ```
  138. Boolean options will interpret the empty string as unset, '0' as false
  139. and anything else as true.
  140. ```shell
  141. $ FOO_VERBOSE= node examples/foo.js # not set
  142. # opts: { _order: [], _args: [] }
  143. # args: []
  144. $ FOO_VERBOSE=0 node examples/foo.js # '0' is false
  145. # opts: { verbose: [ false ],
  146. _order: [ { key: 'verbose', value: false, from: 'env' } ],
  147. _args: [] }
  148. # args: []
  149. $ FOO_VERBOSE=1 node examples/foo.js # true
  150. # opts: { verbose: [ true ],
  151. _order: [ { key: 'verbose', value: true, from: 'env' } ],
  152. _args: [] }
  153. # args: []
  154. $ FOO_VERBOSE=boogabooga node examples/foo.js # true
  155. # opts: { verbose: [ true ],
  156. _order: [ { key: 'verbose', value: true, from: 'env' } ],
  157. _args: [] }
  158. # args: []
  159. ```
  160. Non-booleans can be used as well. Strings:
  161. ```shell
  162. $ FOO_FILE=data.txt node examples/foo.js
  163. # opts: { file: 'data.txt',
  164. _order: [ { key: 'file', value: 'data.txt', from: 'env' } ],
  165. _args: [] }
  166. # args: []
  167. ```
  168. Numbers:
  169. ```shell
  170. $ FOO_TIMEOUT=5000 node examples/foo.js
  171. # opts: { timeout: 5000,
  172. _order: [ { key: 'timeout', value: 5000, from: 'env' } ],
  173. _args: [] }
  174. # args: []
  175. $ FOO_TIMEOUT=blarg node examples/foo.js
  176. foo: error: arg for "FOO_TIMEOUT" is not a positive integer: "blarg"
  177. ```
  178. With the `includeEnv: true` config to `parser.help()` the environment
  179. variable can also be included in **help output**:
  180. usage: node foo.js [OPTIONS]
  181. options:
  182. --version Print tool version and exit.
  183. -h, --help Print this help and exit.
  184. -v, --verbose Verbose output. Use multiple times for more verbose.
  185. Environment: FOO_VERBOSE=1
  186. -f FILE, --file=FILE File to process
  187. # Bash completion
  188. Dashdash provides a simple way to create a Bash completion file that you
  189. can place in your "bash_completion.d" directory -- sometimes that is
  190. "/usr/local/etc/bash_completion.d/"). Features:
  191. - Support for short and long opts
  192. - Support for knowing which options take arguments
  193. - Support for subcommands (e.g. 'git log <TAB>' to show just options for the
  194. log subcommand). See
  195. [node-cmdln](https://github.com/trentm/node-cmdln#bash-completion) for
  196. how to integrate that.
  197. - Does the right thing with "--" to stop options.
  198. - Custom optarg and arg types for custom completions.
  199. Dashdash will return bash completion file content given a parser instance:
  200. var parser = dashdash.createParser({options: options});
  201. console.log( parser.bashCompletion({name: 'mycli'}) );
  202. or directly from a `options` array of options specs:
  203. var code = dashdash.bashCompletionFromOptions({
  204. name: 'mycli',
  205. options: OPTIONS
  206. });
  207. Write that content to "/usr/local/etc/bash_completion.d/mycli" and you will
  208. have Bash completions for `mycli`. Alternatively you can write it to
  209. any file (e.g. "~/.bashrc") and source it.
  210. You could add a `--completion` hidden option to your tool that emits the
  211. completion content and document for your users to call that to install
  212. Bash completions.
  213. See [examples/ddcompletion.js](examples/ddcompletion.js) for a complete
  214. example, including how one can define bash functions for completion of custom
  215. option types. Also see [node-cmdln](https://github.com/trentm/node-cmdln) for
  216. how it uses this for Bash completion for full multi-subcommand tools.
  217. - TODO: document specExtra
  218. - TODO: document includeHidden
  219. - TODO: document custom types, `function complete\_FOO` guide, completionType
  220. - TODO: document argtypes
  221. # Parser config
  222. Parser construction (i.e. `dashdash.createParser(CONFIG)`) takes the
  223. following fields:
  224. - `options` (Array of option specs). Required. See the
  225. [Option specs](#option-specs) section below.
  226. - `interspersed` (Boolean). Optional. Default is true. If true this allows
  227. interspersed arguments and options. I.e.:
  228. node ./tool.js -v arg1 arg2 -h # '-h' is after interspersed args
  229. Set it to false to have '-h' **not** get parsed as an option in the above
  230. example.
  231. - `allowUnknown` (Boolean). Optional. Default is false. If false, this causes
  232. unknown arguments to throw an error. I.e.:
  233. node ./tool.js -v arg1 --afe8asefksjefhas
  234. Set it to true to treat the unknown option as a positional
  235. argument.
  236. **Caveat**: When a shortopt group, such as `-xaz` contains a mix of
  237. known and unknown options, the *entire* group is passed through
  238. unmolested as a positional argument.
  239. Consider if you have a known short option `-a`, and parse the
  240. following command line:
  241. node ./tool.js -xaz
  242. where `-x` and `-z` are unknown. There are multiple ways to
  243. interpret this:
  244. 1. `-x` takes a value: `{x: 'az'}`
  245. 2. `-x` and `-z` are both booleans: `{x:true,a:true,z:true}`
  246. Since dashdash does not know what `-x` and `-z` are, it can't know
  247. if you'd prefer to receive `{a:true,_args:['-x','-z']}` or
  248. `{x:'az'}`, or `{_args:['-xaz']}`. Leaving the positional arg unprocessed
  249. is the easiest mistake for the user to recover from.
  250. # Option specs
  251. Example using all fields (required fields are noted):
  252. ```javascript
  253. {
  254. names: ['file', 'f'], // Required (one of `names` or `name`).
  255. type: 'string', // Required.
  256. completionType: 'filename',
  257. env: 'MYTOOL_FILE',
  258. help: 'Config file to load before running "mytool"',
  259. helpArg: 'PATH',
  260. helpWrap: false,
  261. default: path.resolve(process.env.HOME, '.mytoolrc')
  262. }
  263. ```
  264. Each option spec in the `options` array must/can have the following fields:
  265. - `name` (String) or `names` (Array). Required. These give the option name
  266. and aliases. The first name (if more than one given) is the key for the
  267. parsed `opts` object.
  268. - `type` (String). Required. One of:
  269. - bool
  270. - string
  271. - number
  272. - integer
  273. - positiveInteger
  274. - date (epoch seconds, e.g. 1396031701, or ISO 8601 format
  275. `YYYY-MM-DD[THH:MM:SS[.sss][Z]]`, e.g. "2014-03-28T18:35:01.489Z")
  276. - arrayOfBool
  277. - arrayOfString
  278. - arrayOfNumber
  279. - arrayOfInteger
  280. - arrayOfPositiveInteger
  281. - arrayOfDate
  282. FWIW, these names attempt to match with asserts on
  283. [assert-plus](https://github.com/mcavage/node-assert-plus).
  284. You can add your own custom option types with `dashdash.addOptionType`.
  285. See below.
  286. - `completionType` (String). Optional. This is used for [Bash
  287. completion](#bash-completion) for an option argument. If not specified,
  288. then the value of `type` is used. Any string may be specified, but only the
  289. following values have meaning:
  290. - `none`: Provide no completions.
  291. - `file`: Bash's default completion (i.e. `complete -o default`), which
  292. includes filenames.
  293. - *Any string FOO for which a `function complete_FOO` Bash function is
  294. defined.* This is for custom completions for a given tool. Typically
  295. these custom functions are provided in the `specExtra` argument to
  296. `dashdash.bashCompletionFromOptions()`. See
  297. ["examples/ddcompletion.js"](examples/ddcompletion.js) for an example.
  298. - `env` (String or Array of String). Optional. An environment variable name
  299. (or names) that can be used as a fallback for this option. For example,
  300. given a "foo.js" like this:
  301. var options = [{names: ['dry-run', 'n'], env: 'FOO_DRY_RUN'}];
  302. var opts = dashdash.parse({options: options});
  303. Both `node foo.js --dry-run` and `FOO_DRY_RUN=1 node foo.js` would result
  304. in `opts.dry_run = true`.
  305. An environment variable is only used as a fallback, i.e. it is ignored if
  306. the associated option is given in `argv`.
  307. - `help` (String). Optional. Used for `parser.help()` output.
  308. - `helpArg` (String). Optional. Used in help output as the placeholder for
  309. the option argument, e.g. the "PATH" in:
  310. ...
  311. -f PATH, --file=PATH File to process
  312. ...
  313. - `helpWrap` (Boolean). Optional, default true. Set this to `false` to have
  314. that option's `help` *not* be text wrapped in `<parser>.help()` output.
  315. - `default`. Optional. A default value used for this option, if the
  316. option isn't specified in argv.
  317. - `hidden` (Boolean). Optional, default false. If true, help output will not
  318. include this option. See also the `includeHidden` option to
  319. `bashCompletionFromOptions()` for [Bash completion](#bash-completion).
  320. # Option group headings
  321. You can add headings between option specs in the `options` array. To do so,
  322. simply add an object with only a `group` property -- the string to print as
  323. the heading for the subsequent options in the array. For example:
  324. ```javascript
  325. var options = [
  326. {
  327. group: 'Armament Options'
  328. },
  329. {
  330. names: [ 'weapon', 'w' ],
  331. type: 'string'
  332. },
  333. {
  334. group: 'General Options'
  335. },
  336. {
  337. names: [ 'help', 'h' ],
  338. type: 'bool'
  339. }
  340. ];
  341. ...
  342. ```
  343. Note: You can use an empty string, `{group: ''}`, to get a blank line in help
  344. output between groups of options.
  345. # Help config
  346. The `parser.help(...)` function is configurable as follows:
  347. Options:
  348. Armament Options:
  349. ^^ -w WEAPON, --weapon=WEAPON Weapon with which to crush. One of: |
  350. / sword, spear, maul |
  351. / General Options: |
  352. / -h, --help Print this help and exit. |
  353. / ^^^^ ^ |
  354. \ `-- indent `-- helpCol maxCol ---'
  355. `-- headingIndent
  356. - `indent` (Number or String). Default 4. Set to a number (for that many
  357. spaces) or a string for the literal indent.
  358. - `headingIndent` (Number or String). Default half length of `indent`. Set to
  359. a number (for that many spaces) or a string for the literal indent. This
  360. indent applies to group heading lines, between normal option lines.
  361. - `nameSort` (String). Default is 'length'. By default the names are
  362. sorted to put the short opts first (i.e. '-h, --help' preferred
  363. to '--help, -h'). Set to 'none' to not do this sorting.
  364. - `maxCol` (Number). Default 80. Note that reflow is just done on whitespace
  365. so a long token in the option help can overflow maxCol.
  366. - `helpCol` (Number). If not set a reasonable value will be determined
  367. between `minHelpCol` and `maxHelpCol`.
  368. - `minHelpCol` (Number). Default 20.
  369. - `maxHelpCol` (Number). Default 40.
  370. - `helpWrap` (Boolean). Default true. Set to `false` to have option `help`
  371. strings *not* be textwrapped to the helpCol..maxCol range.
  372. - `includeEnv` (Boolean). Default false. If the option has associated
  373. environment variables (via the `env` option spec attribute), then
  374. append mentioned of those envvars to the help string.
  375. - `includeDefault` (Boolean). Default false. If the option has a default value
  376. (via the `default` option spec attribute, or a default on the option's type),
  377. then a "Default: VALUE" string will be appended to the help string.
  378. # Custom option types
  379. Dashdash includes a good starter set of option types that it will parse for
  380. you. However, you can add your own via:
  381. var dashdash = require('dashdash');
  382. dashdash.addOptionType({
  383. name: '...',
  384. takesArg: true,
  385. helpArg: '...',
  386. parseArg: function (option, optstr, arg) {
  387. ...
  388. },
  389. array: false, // optional
  390. arrayFlatten: false, // optional
  391. default: ..., // optional
  392. completionType: ... // optional
  393. });
  394. For example, a simple option type that accepts 'yes', 'y', 'no' or 'n' as
  395. a boolean argument would look like:
  396. var dashdash = require('dashdash');
  397. function parseYesNo(option, optstr, arg) {
  398. var argLower = arg.toLowerCase()
  399. if (~['yes', 'y'].indexOf(argLower)) {
  400. return true;
  401. } else if (~['no', 'n'].indexOf(argLower)) {
  402. return false;
  403. } else {
  404. throw new Error(format(
  405. 'arg for "%s" is not "yes" or "no": "%s"',
  406. optstr, arg));
  407. }
  408. }
  409. dashdash.addOptionType({
  410. name: 'yesno'
  411. takesArg: true,
  412. helpArg: '<yes|no>',
  413. parseArg: parseYesNo
  414. });
  415. var options = {
  416. {names: ['answer', 'a'], type: 'yesno'}
  417. };
  418. var opts = dashdash.parse({options: options});
  419. See "examples/custom-option-\*.js" for other examples.
  420. See the `addOptionType` block comment in "lib/dashdash.js" for more details.
  421. Please let me know [with an
  422. issue](https://github.com/trentm/node-dashdash/issues/new) if you write a
  423. generally useful one.
  424. # Why
  425. Why another node.js option parsing lib?
  426. - `nopt` really is just for "tools like npm". Implicit opts (e.g. '--no-foo'
  427. works for every '--foo'). Can't disable abbreviated opts. Can't do multiple
  428. usages of same opt, e.g. '-vvv' (I think). Can't do grouped short opts.
  429. - `optimist` has surprise interpretation of options (at least to me).
  430. Implicit opts mean ambiguities and poor error handling for fat-fingering.
  431. `process.exit` calls makes it hard to use as a libary.
  432. - `optparse` Incomplete docs. Is this an attempted clone of Python's `optparse`.
  433. Not clear. Some divergence. `parser.on("name", ...)` API is weird.
  434. - `argparse` Dep on underscore. No thanks just for option processing.
  435. `find lib | wc -l` -> `26`. Overkill.
  436. Argparse is a bit different anyway. Not sure I want that.
  437. - `posix-getopt` No type validation. Though that isn't a killer. AFAIK can't
  438. have a long opt without a short alias. I.e. no `getopt_long` semantics.
  439. Also, no whizbang features like generated help output.
  440. - ["commander.js"](https://github.com/visionmedia/commander.js): I wrote
  441. [a critique](http://trentm.com/2014/01/a-critique-of-commander-for-nodejs.html)
  442. a while back. It seems fine, but last I checked had
  443. [an outstanding bug](https://github.com/visionmedia/commander.js/pull/121)
  444. that would prevent me from using it.
  445. # License
  446. MIT. See LICENSE.txt.