UNPKG

2.65 kBJavaScriptView Raw
1'use strict'
2
3/**
4 * @module command-line-args
5 */
6module.exports = commandLineArgs
7
8/**
9 * Returns an object containing all options set on the command line. By default it parses the global [`process.argv`](https://nodejs.org/api/process.html#process_process_argv) array.
10 *
11 * By default, an exception is thrown if the user sets an unknown option (one without a valid [definition](#exp_module_definition--OptionDefinition)). To enable __partial parsing__, invoke `commandLineArgs` with the `partial` option - all unknown arguments will be returned in the `_unknown` property.
12 *
13 *
14 * @param {module:definition[]} - An array of [OptionDefinition](#exp_module_definition--OptionDefinition) objects
15 * @param [options] {object} - Options.
16 * @param [options.argv] {string[]} - An array of strings, which if passed will be parsed instead of `process.argv`.
17 * @param [options.partial] {boolean} - If `true`, an array of unknown arguments is returned in the `_unknown` property of the output.
18 * @returns {object}
19 * @throws `UNKNOWN_OPTION` if `options.partial` is false and the user set an undefined option
20 * @throws `NAME_MISSING` if an option definition is missing the required `name` property
21 * @throws `INVALID_TYPE` if an option definition has a `type` value that's not a function
22 * @throws `INVALID_ALIAS` if an alias is numeric, a hyphen or a length other than 1
23 * @throws `DUPLICATE_NAME` if an option definition name was used more than once
24 * @throws `DUPLICATE_ALIAS` if an option definition alias was used more than once
25 * @throws `DUPLICATE_DEFAULT_OPTION` if more than one option definition has `defaultOption: true`
26 * @alias module:command-line-args
27 */
28function commandLineArgs (optionDefinitions, options) {
29 options = options || {}
30 const Definitions = require('./definitions')
31 const Argv = require('./argv')
32 const definitions = new Definitions()
33 definitions.load(optionDefinitions)
34 const argv = new Argv()
35 argv.load(options.argv)
36 argv.expandOptionEqualsNotation()
37 argv.expandGetoptNotation()
38 argv.validate(definitions, options)
39
40 const OutputClass = definitions.isGrouped() ? require('./grouped-output') : require('./output')
41 const output = new OutputClass(definitions, options)
42 let optionName
43
44 const option = require('./option')
45 for (const arg of argv) {
46 if (option.isOption(arg)) {
47 optionName = output.setFlag(arg) ? undefined : arg
48 } else {
49 if (optionName) {
50 optionName = output.setOptionValue(optionName, arg) ? undefined : optionName
51 } else {
52 optionName = output.setValue(arg) ? undefined : optionName
53 }
54 }
55 }
56
57 return output.toObject()
58}