1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 | const path = require('path');
|
13 | const fse = require('fs-extra');
|
14 | const dotenv = require('dotenv');
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 | function decodeParamString(params, cwd = '') {
|
24 | let content = params.trim();
|
25 | if (cwd) {
|
26 | const filename = path.resolve(cwd, content);
|
27 | if (!fse.existsSync(filename)) {
|
28 | throw Error(`Specified param file does not exist: ${path.relative(process.cwd(), filename)}`);
|
29 | }
|
30 | content = fse.readFileSync(filename, 'utf-8').trim();
|
31 | }
|
32 | let data;
|
33 | if (content.startsWith('{')) {
|
34 | data = JSON.parse(content);
|
35 | } else {
|
36 | data = dotenv.parse(content);
|
37 | }
|
38 | return data;
|
39 | }
|
40 |
|
41 |
|
42 |
|
43 |
|
44 |
|
45 |
|
46 |
|
47 | function decodeFileParams(filenames, cwd = process.cwd()) {
|
48 | return filenames
|
49 | .reduce((prev, filename) => (Object.assign(prev, decodeParamString(filename, cwd))), {});
|
50 | }
|
51 |
|
52 |
|
53 |
|
54 |
|
55 |
|
56 |
|
57 |
|
58 | function decodeParams(values, name) {
|
59 | if (!values && values.length === 0) {
|
60 | return {};
|
61 | }
|
62 | if (values.length % 2 === 0) {
|
63 | return values.reduce((p, c, i) => {
|
64 | if (i % 2 === 0) {
|
65 |
|
66 | p[c] = values[i + 1];
|
67 | }
|
68 | return p;
|
69 | }, {});
|
70 | } else if (values.length === 1) {
|
71 | return decodeParamString(values[0]);
|
72 | } else {
|
73 | throw new Error(`${name} needs either a JSON string or key-value pairs`);
|
74 | }
|
75 | }
|
76 |
|
77 | module.exports = function commonArgs(yargs, options) {
|
78 | const fileOptions = {
|
79 | ...options,
|
80 | name: `${options.name}-file`,
|
81 | alias: options.alias ? `${options.alias}File` : `${options.name}File`,
|
82 | describe: `${options.describe} (JSON or env file)`,
|
83 | };
|
84 | return yargs
|
85 | .option(options.name, options)
|
86 | .coerce(options.name, (argv) => decodeParams(argv, options.name))
|
87 | .option(fileOptions.name, fileOptions)
|
88 | .coerce(fileOptions.name, (argv) => decodeFileParams.bind(decodeFileParams, argv));
|
89 | };
|
90 |
|
91 |
|
92 | module.exports.decodeFileParams = decodeFileParams;
|