-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
program.js
39 lines (36 loc) · 936 Bytes
/
program.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
const parse = argv =>
argv.reduce((args, value) => {
if (value.startsWith('--')) {
const m = value.match(/^--(\w+)(=(.+))?$/);
const k = m[1];
const v = m[3] ? m[3] : true;
args[k] = v;
} else {
args._.push(value);
}
return args;
}, { _: [] });
const program = options => {
const interface = {
command(name, fn) {
this.commands = this.commands || {};
this.commands[name] = fn;
return this;
},
exec(name = 'help') {
const fn = this.commands[name];
if (typeof fn !== 'function') {
throw new TypeError(`command "${name}" not found`);
}
return fn.apply(this, [].slice.call(arguments, 1));
},
parse(argv = process.argv.slice(2)) {
const args = parse(argv);
const name = args._.shift();
return this.exec(name, args);
}
};
return interface;
};
program.parse = parse;
module.exports = program;