-
Notifications
You must be signed in to change notification settings - Fork 0
/
incli.js
47 lines (43 loc) · 1.51 KB
/
incli.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
const { omit } = require('lodash');
const yargs = require('yargs');
let log = () => null;
if (process.env.DEBUG === 'incli') { log = console.log; }
const yargOptionInit = (yargOptions) => (y) => {
log('Yarg Option initialization', yargOptions)
const demandOptions = [];
for (const option of yargOptions) {
const optionName = option.option;
if (option.required) { demandOptions.push(optionName); }
const settings = omit(option, ['option', 'required']);
y.option(option.option, settings);
}
if (demandOptions.length) {
let demandList = demandOptions;
let plural = '';
if (demandList.length > 1) {
plural = 's';
demandList[demandList.length - 1] = `and ${demandList[demandList.length - 1]}`;
}
demandList = demandList.length > 2 ? demandList.join(', ') : demandList.join(' ');
const demandOptionMessage = `Please provide the ${demandList} argument${plural} to work with this command`;
y.demandOption(demandOptions, demandOptionMessage);
}
};
const yargCallback = (callback) => async (argv) => {
log('Yarg callback executing', argv)
try {
await callback(argv);
} catch (e) {
log('Yarg error thrown')
console.error(e);
process.exit(1);
}
}
module.exports = (commands) => {
log('Yarg command initialization', commands)
for (const commandName of Object.keys(commands)) {
const command = commands[commandName];
yargs.command(commandName, command.description, yargOptionInit(command.options), yargCallback(command.callback));
}
yargs.argv;
}