-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
287 lines (245 loc) · 6.45 KB
/
index.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
"use strict";
var isNullOrUndefined = require('util').isNullOrUndefined;
var isBoolean = require('util').isBoolean;
var minimist = require('minimist');
/**
* group1: required
* group2: name
* group3: default value
* @type {RegExp}
*/
const OPTION_DEFINITION = /(!)?(\w+)(?:=(\w+))?/;
const _private = new Map();
/** @class */
class MiniCli {
/**
* Creates mini-cli app commands map.
*/
constructor() {
_private.set(this, {
commands: new Map(),
current: null
})
}
static get MATCH_ANY() {return /./}
static parse(argv, factory) {
let instance = new MiniCli();
factory.call(instance);
return instance.parse(argv);
}
/**
* @param name
* @returns {MiniCli}
*/
command(name) {
let p = _private.get(this);
p.current = name;
p.commands.set(name, {
name,
description: '',
action: null,
args: {},
options: {}
});
return this;
}
/**
* @param {string} str
*/
description(str) {
this._current.description = str;
return this;
}
/**
* @returns {object} command
* @private
*/
get _current() {
let p = _private.get(this);
if (p.current === null) {
throw new Error('Un-initialized command');
}
return p.commands.get(p.current);
}
/**
* @param name
* @returns {MiniCli}
*/
alias(name) {
_private.get(this).commands.set(name, this._current);
return this;
}
/**
* Define arguments list.
* [name][=default]
*
* Arguments can only be marked default only after all compulsory arguments.
* Last argument can be a callback function invoked when argument(s) is encountered.
*
* @param {...string}
* @return {MiniCli}
*/
args() {
let curr = this._current;
let args = toCallbackFunction.apply(this, arguments);
var withDefault = false;
for(let arg of args.list) {
let def = createDefinition(curr, 'args', arg, args.callback);
if (withDefault && !def.default) {
throw new Error('invalid_command: optional argument must be in the last positions');
}
withDefault = !isNullOrUndefined(def.default);
}
return this;
}
/**
* Defines options list.
* [!]<name>[=default value]
*
* ! - marks argument to be required
* name - can be a char or a string
* default value - sets default string value
*
* Last argument can be a callback function invoked when option(s) is encountered.
*
* @param {...string}
* @returns {MiniCli}
*/
option() {
let curr = this._current;
let args = toCallbackFunction.apply(this, arguments);
for(let option of args.list) {
createDefinition(curr, 'options', option, args.callback);
}
return this;
}
/**
* @param callback
* @returns {MiniCli}
*/
action(callback) {
this._current.action = callback;
return this;
}
/**
* @param {Array} argv - Array of string arguments to map into cli actions.
* @param {object} [ctx] - Context to use with this command action.
* @returns {*} - proxies action return value
*/
parse(argv, ctx) {
let input = minimist(argv);
let command = findMatchingCommand(input._[0], _private.get(this).commands);
let context = ctx || {};
if (!command) throw new Error('Unknown command');
else if (!command.action) throw new Error('invalid_command: no action callback');
let args = input._.splice(1);
let keys = Object.keys(command.args);
let parsedArgs = null;
let i = -1;
let length = !keys.length ? 0 : Math.max(keys.length, args.length);
while(++i < length) {
parsedArgs = parsedArgs || {_:[]};
let val = args[i];
let com = keys.length > i ? command.args[keys[i]] : null;
if (com === null) parsedArgs._.push(val);
else if (isNullOrUndefined(val) && isNullOrUndefined(com.default)) {
return new Error(`Missing command argument{${i}}: ${com.name}`);
}
else {
parsedArgs[com.name] = !isNullOrUndefined(val) ? val : com.default;
}
}
let parsedOptions = {};
for(let key of Object.keys(command.options)) {
let options = command.options[key];
let value = input[key];
if (value === undefined && options.required) {
return new Error(`Missing command flag: ${key}`);
}
if (value !== undefined) {
parsedOptions[key] = value;
}
else if (options.default !== undefined) {
parsedOptions[key] = options.default;
}
}
if (parsedArgs) {
for(let key of Object.keys(parsedArgs)) {
if (key === '_') continue;
let opt = command.args[key];
if (opt.action) {
let result = opt.action(context, parsedArgs[key]);
if (result && !isBoolean(result) || !!result) {
return result;
}
}
}
}
for(let key of Object.keys(parsedOptions)) {
let opt = command.options[key];
if (opt.action) {
let result = opt.action(context, parsedOptions[key]);
if (result && !isBoolean(result) || result) {
return result;
}
}
}
return command.action(context, parsedArgs || args, parsedOptions);
}
/**
* Returns commands Iterator.<name, description>
* @returns {*}
*/
commands() {
let entries = _private.get(this).commands.entries();
let iterable = {
[Symbol.iterator]() { return this; }
};
iterable.next = function () {
let next = entries.next();
return next.done ? next : {
value: {
id: next.value[0],
name: next.value[1].name,
description: next.value[1].description
}
}
};
return iterable;
}
}
module.exports = MiniCli;
function findMatchingCommand (name, commands) {
for(let key of commands.keys()) {
if (name && name.match(key)) {
return commands.get(key);
}
}
}
function toCallbackFunction () {
let args = arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments);
return {
list: args.filter(n => {return typeof n === 'string'}),
callback: typeof args[args.length - 1] === 'function' ? args[args.length -1] : null
}
}
function toArgumentDefinition (str) {
let parsed = str.match(OPTION_DEFINITION);
return {
name: parsed[2],
required: !!parsed[1],
defaultValue: parsed[3]
}
}
function createDefinition (root, ref, arg, callback) {
if (arg === undefined) {
throw new Error(`Undefined "${ref}" string`);
}
let opt = toArgumentDefinition(arg);
let dest = root[ref][opt.name] ? root[ref][opt.name] : root[ref][opt.name] = {};
dest.name = opt.name;
dest.required = opt.required;
dest.default = opt.defaultValue;
dest.action = callback;
return dest;
}