-
Notifications
You must be signed in to change notification settings - Fork 7
/
cli.js
92 lines (75 loc) · 2.31 KB
/
cli.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
/* global global, process */
const fs = require('fs-extra');
const glob = require('glob');
const path = require('path');
/**
* Parse arguments from command array
*
* @param {Array} keywords
* @returns {object}
*/
getArgs = function(keywords) {
var args = {};
keywords.forEach(function(arg) {
if (arg.slice(0, 2) == '--') {
var segs = arg.slice(2).split('=');
args[segs[0]] = segs.length > 1 ? segs[1] : '';
}
});
return args;
},
/**
* Register all available commands
*
* @param {string} rootPath
* @param {Array} paths
* @returns {object}
*/
registerCommands = function(rootPath, paths) {
var commands = {};
paths.forEach(function(commandPath) {
var files = glob.sync(commandPath + '*.js');
files.forEach(function(file) {
var name = path.basename(file, '.js');
file = path.join(rootPath, file);
commands[name] = require(file);
});
});
return commands;
};
global.chalk = require('chalk');
module.exports = function(rootPath, program) {
var keywords = process.argv.slice(2),
keyCount = keywords.length,
args = getArgs(
keyCount === 1 ?
keywords.slice(0) :
keywords.slice(1)
),
configPath = path.join(rootPath, args.config || 'wee.config.js'),
project = require(configPath),
commands = registerCommands(rootPath, [
'node_modules/wee-core/commands/',
path.join(project.paths.source, 'commands/')
]);
// Register commands
Object.keys(commands).forEach(name => {
let command = commands[name];
// TODO: Remove once all default commands are updated
if (! command.name) {
return;
}
let result = program.command(command.name)
.usage(command.usage || command.name)
.description(command.description || '');
if (command.arguments) {
result.arguments(command.arguments);
}
if (command.options && command.options.length) {
command.options.forEach(option => {
result.option(option[0], option[1], option[2] || {});
});
}
result.action(command.action.bind(null, {rootPath: rootPath, project: project}));
});
};