1 | const commandLineArgs = require('command-line-args');
|
2 | const kebabCase = require('lodash/kebabCase');
|
3 | const concat = require('lodash/concat');
|
4 | const map = require('lodash/map');
|
5 | const pick = require('lodash/pick');
|
6 | const assign = require('lodash/assign');
|
7 |
|
8 | const basicOptions = [
|
9 | { name: 'version', alias: 'v', type: Boolean, defaultValue: false },
|
10 | { name: 'help', alias: 'h', type: Boolean, defaultValue: false }
|
11 | ];
|
12 |
|
13 | const convertOptions = (options, savedOptions) => {
|
14 | return map(options, (option) => {
|
15 | const sanitized = pick(option, [
|
16 | 'name',
|
17 | 'type',
|
18 | 'alias',
|
19 | 'multiple',
|
20 | 'lazyMultiple',
|
21 | 'defaultOption',
|
22 | 'defaultValue',
|
23 | 'group'
|
24 | ]);
|
25 | if (savedOptions[sanitized.name] !== undefined) {
|
26 | sanitized.defaultValue = savedOptions[sanitized.name];
|
27 | }
|
28 | sanitized.name = kebabCase(option.name);
|
29 | return sanitized;
|
30 | });
|
31 | };
|
32 |
|
33 | const parsingCommandLineArgs = (
|
34 | argv = process.argv, optionList, savedOptions
|
35 | ) => {
|
36 | const parsed = commandLineArgs(
|
37 | concat(basicOptions, convertOptions(optionList, savedOptions)),
|
38 | {
|
39 | camelCase: true,
|
40 | partial: true,
|
41 | argv
|
42 | }
|
43 | );
|
44 | const { _unknown: [ command, ...args ], ...options } =
|
45 | assign({ _unknown: [] }, parsed);
|
46 | return { command, args, options };
|
47 | };
|
48 |
|
49 | module.exports = parsingCommandLineArgs;
|