-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
230 lines (197 loc) · 6.59 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
'use strict';
const path = require('path');
const yargs = require('yargs-parser');
const indent = require('indent-string');
const readPkgUp = require('read-pkg-up');
// Prevent caching of this module so module.parent is always accurate
delete require.cache[__filename];
const parentDir = path.dirname(module.parent.filename);
/**
* Command line application helper for single commands
* parses given flags, fail on missing required option
* support customizable built-in help message generation
*/
const clito = function (options) {
options = {
pkg: readPkgUp.sync({
cwd: parentDir,
normalize: false
}).package || {},
argv: process.argv.slice(2),
indentation: 0,
showHelp: true,
showVersion: true,
...options
};
// Default option values expected from yargs-parser
const parserDefaults = {
alias: {},
array: [],
boolean: [],
default: {},
string: [],
number: [],
config: {
[options.config || 'config']: true
},
configuration: {
'short-option-groups': true,
'camel-case-expansion': true,
'boolean-negation': true,
'duplicate-arguments-array': false,
'flatten-duplicate-arrays': true
}
};
// Prepare flags for reducing into parser options
const inputFlags = options.flags || {};
const flagsArr = Object.keys(inputFlags).map(function (key) {
return [key, inputFlags[key]];
});
// Return the command banner with name, version and description
// separated by one blank line and optionally preceeded by custom text
const getBanner = function () {
return [
options.banner,
getVersion(),
options.description || options.pkg.description
].filter(v => v && v !== '').join('\n\n');
};
// Return the command usage string
const getUsage = function () {
const pkgName = options.name || options.pkg.name;
const usage = options.usage || `$ ${pkgName} [options] <input>`;
return ['Usage:', indent(usage, 2)].join('\n');
};
// Return the usage examples string
const getExamples = function () {
const { examples } = options;
if (!examples) {
return '';
}
const outStr = (
Array.isArray(examples)
? examples
: [examples]
).map(s => indent(s, 2)).join('\n');
return ['Examples:', outStr].join('\n');
};
// Return application name and version
const getVersion = function () {
const { pkg } = options;
const nameStr = (options.name || pkg.name) + ' ';
const versionStr = `v${(options.version || pkg.version)}`;
return nameStr + versionStr;
};
// Return the options usage string
const getOptionsHelp = function () {
const optNames = flagsArr.map(([name, opts]) => {
const { alias, description } = opts;
let outStr = [`--${name}`];
alias && outStr.push(`-${alias}`);
outStr = outStr.join(', ');
return [outStr, description];
});
// Pad output strings using max width plus two spaces
const maxWidth = optNames.reduce((max, [cur]) => cur.length > max ? cur.length : max, 0);
const outStr = optNames.map(([opt, desc]) => {
return opt.padEnd(maxWidth + 2) + (desc || '');
}).join('\n');
return ['Options:', indent(outStr, 2)].join('\n');
};
// Print application name and version
const showVersion = function () {
// eslint-disable-next-line
console.log(getVersion());
process.exit();
};
// Print command usage string and options help
const showHelp = function () {
const out = [
getBanner(),
getUsage(),
getOptionsHelp(),
getExamples()
].join('\n\n');
// eslint-disable-next-line
console.log(indent(out, options.indentation));
process.exit();
};
// Prepare parser options from user config
const parserOpts = flagsArr.reduce(function (obj, flag) {
const [flagName, flagOptions] = flag;
const {
type,
alias,
multiple,
default: defaultValue,
} = flagOptions;
/**
* To allow for configuration objects via the configuration file
* if the type is not set just return without adding the key
* to the parser configuration object, if the key is set via
* the configuration file it will be automatically populated later
*/
if (typeof type === 'undefined') {
return obj;
}
if (multiple) {
obj.array.push({
key: flagName,
[type]: true
});
} else {
obj[type].push(flagName);
}
if (alias) {
obj.alias[flagName] = [alias];
}
if (defaultValue || type === 'boolean') {
obj.default[flagName] = defaultValue || false;
}
return obj;
}, parserDefaults);
// Parse and extract args
const { _: input, ...args } = yargs(options.argv, parserOpts);
// Print application version
if (args.version && options.showVersion) {
showVersion();
}
// If --help has been passed as flag
if (args.help && options.showHelp) {
showHelp();
}
// Check for required options
const flags = flagsArr.reduce(function (obj, [flagName, flagOpts]) {
const flagValue = args[flagName];
const isDefined = typeof flagValue !== 'undefined';
// Verify if option is required
if (!isDefined && flagOpts.required) {
throw new Error(`Option "${flagName}" is required.`);
}
if (isDefined) {
// Optionally validate parsed option value
if (flagOpts.validation) {
const isValid = flagOpts.validation(flagValue);
if (isValid !== true) {
const err = typeof isValid === 'string' ?
isValid :
`Invalid value "${flagValue}" for option "${flagName}".`;
throw new Error(err);
}
}
// Finally assign flag to object
obj[flagOpts.alias || flagName] = flagValue;
obj[flagName] = flagValue;
}
return obj;
}, {});
return {
input,
flags
};
};
/**
* Export module
*/
module.exports = clito;
module.exports.default = clito;