-
Notifications
You must be signed in to change notification settings - Fork 4
/
helmsman.js
356 lines (283 loc) · 8.97 KB
/
helmsman.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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
'use strict';
/*!
* Module dependencies.
*/
var util = require('util');
var events = require('events');
var path = require('path');
var glob = require('glob');
var spawn = require('child_process').spawn;
var _ = require('lodash');
var _s = require('underscore.string');
var domain = require('domain').create();
require('colors');
/**
* The default function used to get metadata from a command
*/
function defaultFillCommandData(defaults, file, extension) {
var data;
try {
data = require(file).command || {};
} catch (e) {
// If it's JavaScript then return the error
if (extension === '.js') {
data = {failedRequire: e};
}
}
return _.merge(defaults, data);
}
/**
* The Helmsman constructor
*
* Options:
*
* * prefix: The prefix of the script files. e.g.: 'git-''
*
* @param {object} options config
*/
function Helmsman(options) {
var self = this;
events.EventEmitter.call(self);
options = options || {};
// Add option defaults
options = _.merge({
usePath: false,
metadata: {},
fillCommandData: defaultFillCommandData,
fallbackCommandData: true,
ignoreRequireFail: true,
nodePath: 'node'
}, options);
this.fillCommandData = options.fillCommandData;
this.fallbackCommandData = options.fallbackCommandData;
this.ignoreRequireFail = options.ignoreRequireFail;
this.nodePath = options.nodePath;
if (!options.localDir) {
this.localDir = path.dirname(module.parent.filename);
} else {
this.localDir = path.resolve(options.localDir);
}
// Guess the prefix. Assume if one isn't given and that executable doesn't
// equal the root command filename, use the filename of the root command
if (!options.prefix &&
path.basename(process.argv[1]) !== path.basename(require.main.filename)) {
this.prefix = path.basename(require.main.filename,
path.extname(require.main.filename));
} else {
this.prefix = options.prefix || path.basename(process.argv[1],
path.extname(process.argv[1]));
}
this.availableCommands = {};
// Add a dash to the end if none was provided
if (this.prefix.substr(-1) !== '-') {
this.prefix += '-';
}
// Local files in files in the /bin folder for an application
this.localFiles = glob.sync(self.prefix + '*', {cwd: self.localDir})
.map(function (file) {
return path.join(self.localDir, file);
});
if (options.usePath) {
var pathTokens = process.env.PATH.split(':');
pathTokens.forEach(function (pathToken) {
self.localFiles = self.localFiles.concat(glob.sync(self.prefix + '*',
{cwd: pathToken}).map(function (file) {
return path.join(pathToken, file);
}));
});
}
this.localFiles.forEach(function (file) {
var extension = path.extname(file);
var name = path.basename(file, extension).substr(self.prefix.length);
var defaultCommandData = {
name: name,
description: '',
arguments: '',
path: file
};
// We get the defaults as a minimum if there's no strategy for the
// extension and no custom fillCommandData function specified
var commandData = _.clone(defaultCommandData);
// Load the command data from the metadata option if present
if (options.metadata[name]) {
commandData = _.merge(defaultCommandData, options.metadata[name]);
// Only try to get metadata from commands written in JavaScript
} else if ((extension === '' || extension === '.js') &&
self.fillCommandData === defaultFillCommandData) {
commandData = self.fillCommandData(defaultCommandData, file, extension);
if (!self.ignoreRequireFail && commandData.failedRequire) {
console.error(util.format('The file "%s" did not load correctly: %s',
file, commandData.failedRequire).red);
process.exit(1);
}
} else if (self.fillCommandData !== defaultFillCommandData) {
commandData = self.fillCommandData(defaultCommandData, file, extension);
if (!commandData && self.fallbackCommandData) {
commandData = defaultFillCommandData(defaultCommandData,
file, extension);
}
}
self.availableCommands[name] = commandData;
});
// help is always available!
self.availableCommands.help = {
name: 'help',
arguments: '<sub-command>',
description: 'Show the --help for a specific command'
};
}
util.inherits(Helmsman, events.EventEmitter);
/**
* Simplify creating a new Helmsman Object
*
* Example:
*
* var helmsman = require('helmsman');
*
* var cli = helmsman();
* cli.parse();
*
* @param {Object} options Contructor options
* @return {Helmsman} A new helmsman
*/
function helmsman(options) {
return new Helmsman(options);
}
/**
* Determine the subcommand to run
*
* Try:
* * Explicit match (status === status)
* * Shorthand (st === status)
* * Levenshtein of <=2 (sratus === status)
*
* @param {String} cmd The command given to the script
* @param {[String]} availableCommands An array of all the available commands
* @return {String} The actual command that will be run
*/
Helmsman.prototype.getCommand = function (cmd, availableCommands) {
var self = this;
if (!availableCommands) {
availableCommands = _.keys(self.availableCommands);
}
if (_.includes(availableCommands, cmd)) {
return cmd;
}
// Determine how many commands match the iterator. Return one if command,
function isOneOrMore(commands, iterator) {
var list = commands.filter(iterator);
if (list.length === 1) {
return list[0];
} else if (list.length > 1) {
return new Error(util.format('There are %d options for "%s": %s',
list.length, cmd, list.join(', ')));
}
return false;
}
// If there is a shorthand match, return it
var shortHandCmd = isOneOrMore(availableCommands, function (command) {
return (command.indexOf(cmd) === 0);
});
if (shortHandCmd) {
return shortHandCmd;
}
// If there is a close match, return it
var similarCmd = isOneOrMore(availableCommands, function (command) {
return (_s.levenshtein(cmd, command) <= 2);
});
if (similarCmd) {
console.log('You typed', cmd, 'which matched', similarCmd);
return similarCmd;
}
// If nothing, then get outta here
return new Error(util.format('There are no commands by the name of "%s"',
cmd));
};
/**
* GO!
*
* @param {[Object]} argv The arguments to parse. Defaults to process.argv
*/
Helmsman.prototype.parse = function (argv) {
var self = this;
// Default to process.argv
argv = argv || process.argv;
var args = argv.slice(2);
// Much of the following heavily inspired or simply taken from component/bin
// https://github.com/component/component/blob/master/bin/component
// Print the module's version number
if (args[0] === '--version') {
var pkg = require(path.join(path.dirname(require.main.filename), '..',
'package.json'));
return console.log(pkg.name + ': ' + pkg.version);
}
// Print the command list if --help is called
if (args[0] === '--help' ||
!args.length ||
args[0][0] === '-' ||
(args[0] === 'help' && args.length === 1) ||
(self.getCommand(args[0]) === 'help' && args.length === 1)) {
self.emit('--help');
return self.showHelp();
}
var cmd = self.getCommand(args.shift());
if (util.isError(cmd)) {
console.error(cmd.message.red);
self.showHelp();
process.exit(1);
}
// Implicit help
// If <command> help <sub-command> is entered, automatically run
// <command>-<sub-command> --help
if (cmd === 'help') {
cmd = args.shift();
args = ['--help'];
}
var fullPath = self.availableCommands[cmd] &&
self.availableCommands[cmd].path;
domain.on('error', function (err) {
if (err.code === 'EACCES') {
console.error();
console.error('Could not execute the subcommand: ' + self.prefix + cmd);
console.error();
console.error('Consider running:\n chmod +x', fullPath);
} else {
console.error(err.stack.red);
}
});
domain.run(function () {
// Windows doesn't know how to execute .js files, we help it out by
// launching it with node
if (process.platform === 'win32' &&
path.extname(fullPath) === '.js') {
args.unshift(fullPath);
fullPath = self.nodePath;
}
var subcommand = spawn(fullPath, args, {stdio: 'inherit'});
subcommand.on('close', function (code) {
process.exit(code);
});
});
};
/**
* Show the help
*/
Helmsman.prototype.showHelp = function () {
console.log();
console.log('Commands:');
console.log();
var strings = _.map(this.availableCommands, function (command) {
return command.name + ' ' + command.arguments;
});
var maxLength = _.max(_.map(strings, 'length'));
var descriptions = _.map(this.availableCommands, 'description');
_.zip(strings, descriptions).forEach(function (c) {
console.log(' %s %s', _s.rpad(c[0], maxLength), c[1]);
});
process.exit();
};
/**
* Exports
*/
module.exports = exports = helmsman;
exports.Helmsman = Helmsman;