/
command.js
336 lines (295 loc) · 9.45 KB
/
command.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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
'use strict';
const debug = require('debug')('common-bin');
const co = require('co');
const yargs = require('yargs');
const helper = require('./helper');
const assert = require('assert');
const fs = require('fs');
const path = require('path');
const changeCase = require('change-case');
const chalk = require('chalk');
const DISPATCH = Symbol('Command#dispatch');
const PARSE = Symbol('Command#parse');
const COMMANDS = Symbol('Command#commands');
const VERSION = Symbol('Command#version');
class CommonBin {
constructor(rawArgv) {
/**
* original argument
* @type {Array}
*/
this.rawArgv = rawArgv || process.argv.slice(2);
debug('[%s] origin argument `%s`', this.constructor.name, this.rawArgv.join(' '));
/**
* yargs
* @type {Object}
*/
this.yargs = yargs(this.rawArgv);
/**
* parserOptions
* @type {Object}
* @property {Boolean} execArgv - whether extract `execArgv` to `context.execArgv`
* @property {Boolean} removeAlias - whether remove alias key from `argv`
* @property {Boolean} removeCamelCase - whether remove camel case key from `argv`
*/
this.parserOptions = {
execArgv: false,
removeAlias: false,
removeCamelCase: false,
};
// <commandName, Command>
this[COMMANDS] = new Map();
}
/**
* command handler, could be generator / async function / normal function which return promise
* @param {Object} context - context object
* @param {String} context.cwd - process.cwd()
* @param {Object} context.argv - argv parse result by yargs, `{ _: [ 'start' ], '$0': '/usr/local/bin/common-bin', baseDir: 'simple'}`
* @param {Array} context.rawArgv - the raw argv, `[ "--baseDir=simple" ]`
* @protected
*/
run() {
this.showHelp();
}
/**
* load sub commands
* @param {String} fullPath - the command directory
* @example `load(path.join(__dirname, 'command'))`
*/
load(fullPath) {
assert(fs.existsSync(fullPath) && fs.statSync(fullPath).isDirectory(),
`${fullPath} should exist and be a directory`);
// load entire directory
const files = fs.readdirSync(fullPath);
const names = [];
for (const file of files) {
if (path.extname(file) === '.js') {
const name = path.basename(file).replace(/\.js$/, '');
names.push(name);
this.add(name, path.join(fullPath, file));
}
}
debug('[%s] loaded command `%s` from directory `%s`',
this.constructor.name, names, fullPath);
}
/**
* add sub command
* @param {String} name - a command name
* @param {String|Class} target - special file path (must contains ext) or Command Class
* @example `add('test', path.join(__dirname, 'test_command.js'))`
*/
add(name, target) {
assert(name, `${name} is required`);
if (!(target.prototype instanceof CommonBin)) {
assert(fs.existsSync(target) && fs.statSync(target).isFile(), `${target} is not a file.`);
debug('[%s] add command `%s` from `%s`', this.constructor.name, name, target);
target = require(target);
assert(target.prototype instanceof CommonBin,
'command class should be sub class of common-bin');
}
this[COMMANDS].set(name, target);
}
/**
* alias an existing command
* @param {String} alias - alias command
* @param {String} name - exist command
*/
alias(alias, name) {
assert(alias, 'alias command name is required');
assert(this[COMMANDS].has(name), `${name} should be added first`);
debug('[%s] set `%s` as alias of `%s`', this.constructor.name, alias, name);
this[COMMANDS].set(alias, this[COMMANDS].get(name));
}
/**
* start point of bin process
*/
start() {
co(function* () {
// replace `--get-yargs-completions` to our KEY, so yargs will not block our DISPATCH
const index = this.rawArgv.indexOf('--get-yargs-completions');
if (index !== -1) {
// bash will request as `--get-yargs-completions my-git remote add`, so need to remove 2
this.rawArgv.splice(index, 2, `--AUTO_COMPLETIONS=${this.rawArgv.join(',')}`);
}
yield this[DISPATCH]();
}.bind(this)).catch(this.errorHandler.bind(this));
}
/**
* default error hander
* @param {Error} err - error object
* @protected
*/
errorHandler(err) {
console.error(chalk.red(`⚠️ ${err.name}: ${err.message}`));
console.error(chalk.red('⚠️ Command Error, enable `DEBUG=common-bin` for detail'));
debug('args %s', process.argv.slice(3));
debug(err.stack);
process.exit(1);
}
/**
* print help message to console
* @param {String} [level=log] - console level
*/
showHelp(level = 'log') {
this.yargs.showHelp(level);
}
/**
* shortcut for yargs.options
* @param {Object} opt - an object set to `yargs.options`
*/
set options(opt) {
this.yargs.options(opt);
}
/**
* shortcut for yargs.usage
* @param {String} usage - usage info
*/
set usage(usage) {
this.yargs.usage(usage);
}
/**
* helper function
* @type {Object}
*/
get helper() {
return helper;
}
set version(ver) {
this[VERSION] = ver;
}
get version() {
return this[VERSION];
}
/**
* dispatch command, either `subCommand.exec` or `this.run`
* @param {Object} context - context object
* @param {String} context.cwd - process.cwd()
* @param {Object} context.argv - argv parse result by yargs, `{ _: [ 'start' ], '$0': '/usr/local/bin/common-bin', baseDir: 'simple'}`
* @param {Array} context.rawArgv - the raw argv, `[ "--baseDir=simple" ]`
* @private
*/
* [DISPATCH]() {
// define --help and --version by default
this.yargs
// .reset()
.completion()
.help()
.version()
.wrap(120)
.alias('h', 'help')
.alias('v', 'version')
.group([ 'help', 'version' ], 'Global Options:');
// get parsed argument without handling helper and version
const parsed = yield this[PARSE](this.rawArgv);
const commandName = parsed._[0];
if (parsed.version && this.version) {
console.log(this.version);
return;
}
// if sub command exist
if (this[COMMANDS].has(commandName)) {
const Command = this[COMMANDS].get(commandName);
const rawArgv = this.rawArgv.slice();
rawArgv.splice(rawArgv.indexOf(commandName), 1);
debug('[%s] dispatch to subcommand `%s` -> `%s` with %j', this.constructor.name, commandName, Command.name, rawArgv);
const command = new Command(rawArgv);
yield command[DISPATCH]();
return;
}
// register command for printing
for (const [ name, Command ] of this[COMMANDS].entries()) {
this.yargs.command(name, Command.prototype.description || '');
}
debug('[%s] exec run command', this.constructor.name);
const context = this.context;
// print completion for bash
if (context.argv.AUTO_COMPLETIONS) {
// slice to remove `--AUTO_COMPLETIONS=` which we append
this.yargs.getCompletion(this.rawArgv.slice(1), completions => {
// console.log('%s', completions)
completions.forEach(x => console.log(x));
});
} else {
// handle by self
yield this.helper.callFn(this.run, [ context ], this);
}
}
/**
* getter of context, default behavior is remove `help` / `h` / `version`
* @return {Object} context - { cwd, env, argv, rawArgv }
* @protected
*/
get context() {
const argv = this.yargs.argv;
const context = {
argv,
cwd: process.cwd(),
env: Object.assign({}, process.env),
rawArgv: this.rawArgv,
};
argv.help = undefined;
argv.h = undefined;
argv.version = undefined;
// remove alias result
if (this.parserOptions.removeAlias) {
const aliases = this.yargs.getOptions().alias;
for (const key of Object.keys(aliases)) {
aliases[key].forEach(item => {
argv[item] = undefined;
});
}
}
// remove camel case result
if (this.parserOptions.removeCamelCase) {
for (const key of Object.keys(argv)) {
if (key.includes('-')) {
argv[changeCase.camel(key)] = undefined;
}
}
}
// extract execArgv
if (this.parserOptions.execArgv) {
const execArgvObj = {};
for (const key of Object.keys(argv)) {
const value = argv[key];
// skip undefined set uppon (camel etc.)
if (value === undefined) continue;
// debug / debug-brk / debug-port / inspect / inspect-brk / inspect-port
if (match(key, [ /^debug.*/, /^inspect.*/ ])) {
// extract debug port
if (typeof value === 'number') context.debugPort = value;
execArgvObj[key] = value;
argv[key] = undefined;
continue;
}
// others execArgv
if (match(key, [ 'es_staging', 'expose_debug_as', /^harmony.*/ ])) {
execArgvObj[key] = value;
argv[key] = undefined;
continue;
}
}
// only exports execArgv when any match
if (Object.keys(execArgvObj).length) {
context.execArgvObj = execArgvObj;
context.execArgv = this.helper.unparseArgv(execArgvObj);
}
}
return context;
}
[PARSE](rawArgv) {
return new Promise((resolve, reject) => {
this.yargs.parse(rawArgv, (err, argv) => {
/* istanbul ignore next */
if (err) return reject(err);
resolve(argv);
});
});
}
}
function match(key, arr) {
return arr.some(x => {
return x instanceof RegExp ? x.test(key) : x === key;
});
}
module.exports = CommonBin;