UNPKG

17.9 kBJavaScriptView Raw
1import { EventEmitter } from 'events';
2
3function toArr(any) {
4 return any == null ? [] : Array.isArray(any) ? any : [any];
5}
6
7function toVal(out, key, val, opts) {
8 var x, old=out[key], nxt=(
9 !!~opts.string.indexOf(key) ? (val == null || val === true ? '' : String(val))
10 : typeof val === 'boolean' ? val
11 : !!~opts.boolean.indexOf(key) ? (val === 'false' ? false : val === 'true' || (out._.push((x = +val,x * 0 === 0) ? x : val),!!val))
12 : (x = +val,x * 0 === 0) ? x : val
13 );
14 out[key] = old == null ? nxt : (Array.isArray(old) ? old.concat(nxt) : [old, nxt]);
15}
16
17function mri2 (args, opts) {
18 args = args || [];
19 opts = opts || {};
20
21 var k, arr, arg, name, val, out={ _:[] };
22 var i=0, j=0, idx=0, len=args.length;
23
24 const alibi = opts.alias !== void 0;
25 const strict = opts.unknown !== void 0;
26 const defaults = opts.default !== void 0;
27
28 opts.alias = opts.alias || {};
29 opts.string = toArr(opts.string);
30 opts.boolean = toArr(opts.boolean);
31
32 if (alibi) {
33 for (k in opts.alias) {
34 arr = opts.alias[k] = toArr(opts.alias[k]);
35 for (i=0; i < arr.length; i++) {
36 (opts.alias[arr[i]] = arr.concat(k)).splice(i, 1);
37 }
38 }
39 }
40
41 for (i=opts.boolean.length; i-- > 0;) {
42 arr = opts.alias[opts.boolean[i]] || [];
43 for (j=arr.length; j-- > 0;) opts.boolean.push(arr[j]);
44 }
45
46 for (i=opts.string.length; i-- > 0;) {
47 arr = opts.alias[opts.string[i]] || [];
48 for (j=arr.length; j-- > 0;) opts.string.push(arr[j]);
49 }
50
51 if (defaults) {
52 for (k in opts.default) {
53 name = typeof opts.default[k];
54 arr = opts.alias[k] = opts.alias[k] || [];
55 if (opts[name] !== void 0) {
56 opts[name].push(k);
57 for (i=0; i < arr.length; i++) {
58 opts[name].push(arr[i]);
59 }
60 }
61 }
62 }
63
64 const keys = strict ? Object.keys(opts.alias) : [];
65
66 for (i=0; i < len; i++) {
67 arg = args[i];
68
69 if (arg === '--') {
70 out._ = out._.concat(args.slice(++i));
71 break;
72 }
73
74 for (j=0; j < arg.length; j++) {
75 if (arg.charCodeAt(j) !== 45) break; // "-"
76 }
77
78 if (j === 0) {
79 out._.push(arg);
80 } else if (arg.substring(j, j + 3) === 'no-') {
81 name = arg.substring(j + 3);
82 if (strict && !~keys.indexOf(name)) {
83 return opts.unknown(arg);
84 }
85 out[name] = false;
86 } else {
87 for (idx=j+1; idx < arg.length; idx++) {
88 if (arg.charCodeAt(idx) === 61) break; // "="
89 }
90
91 name = arg.substring(j, idx);
92 val = arg.substring(++idx) || (i+1 === len || (''+args[i+1]).charCodeAt(0) === 45 || args[++i]);
93 arr = (j === 2 ? [name] : name);
94
95 for (idx=0; idx < arr.length; idx++) {
96 name = arr[idx];
97 if (strict && !~keys.indexOf(name)) return opts.unknown('-'.repeat(j) + name);
98 toVal(out, name, (idx + 1 < arr.length) || val, opts);
99 }
100 }
101 }
102
103 if (defaults) {
104 for (k in opts.default) {
105 if (out[k] === void 0) {
106 out[k] = opts.default[k];
107 }
108 }
109 }
110
111 if (alibi) {
112 for (k in out) {
113 arr = opts.alias[k] || [];
114 while (arr.length > 0) {
115 out[arr.shift()] = out[k];
116 }
117 }
118 }
119
120 return out;
121}
122
123const removeBrackets = (v) => v.replace(/[<[].+/, "").trim();
124const findAllBrackets = (v) => {
125 const ANGLED_BRACKET_RE_GLOBAL = /<([^>]+)>/g;
126 const SQUARE_BRACKET_RE_GLOBAL = /\[([^\]]+)\]/g;
127 const res = [];
128 const parse = (match) => {
129 let variadic = false;
130 let value = match[1];
131 if (value.startsWith("...")) {
132 value = value.slice(3);
133 variadic = true;
134 }
135 return {
136 required: match[0].startsWith("<"),
137 value,
138 variadic
139 };
140 };
141 let angledMatch;
142 while (angledMatch = ANGLED_BRACKET_RE_GLOBAL.exec(v)) {
143 res.push(parse(angledMatch));
144 }
145 let squareMatch;
146 while (squareMatch = SQUARE_BRACKET_RE_GLOBAL.exec(v)) {
147 res.push(parse(squareMatch));
148 }
149 return res;
150};
151const getMriOptions = (options) => {
152 const result = {alias: {}, boolean: []};
153 for (const [index, option] of options.entries()) {
154 if (option.names.length > 1) {
155 result.alias[option.names[0]] = option.names.slice(1);
156 }
157 if (option.isBoolean) {
158 if (option.negated) {
159 const hasStringTypeOption = options.some((o, i) => {
160 return i !== index && o.names.some((name) => option.names.includes(name)) && typeof o.required === "boolean";
161 });
162 if (!hasStringTypeOption) {
163 result.boolean.push(option.names[0]);
164 }
165 } else {
166 result.boolean.push(option.names[0]);
167 }
168 }
169 }
170 return result;
171};
172const findLongest = (arr) => {
173 return arr.sort((a, b) => {
174 return a.length > b.length ? -1 : 1;
175 })[0];
176};
177const padRight = (str, length) => {
178 return str.length >= length ? str : `${str}${" ".repeat(length - str.length)}`;
179};
180const camelcase = (input) => {
181 return input.replace(/([a-z])-([a-z])/g, (_, p1, p2) => {
182 return p1 + p2.toUpperCase();
183 });
184};
185const setDotProp = (obj, keys, val) => {
186 let i = 0;
187 let length = keys.length;
188 let t = obj;
189 let x;
190 for (; i < length; ++i) {
191 x = t[keys[i]];
192 t = t[keys[i]] = i === length - 1 ? val : x != null ? x : !!~keys[i + 1].indexOf(".") || !(+keys[i + 1] > -1) ? {} : [];
193 }
194};
195const setByType = (obj, transforms) => {
196 for (const key of Object.keys(transforms)) {
197 const transform = transforms[key];
198 if (transform.shouldTransform) {
199 obj[key] = Array.prototype.concat.call([], obj[key]);
200 if (typeof transform.transformFunction === "function") {
201 obj[key] = obj[key].map(transform.transformFunction);
202 }
203 }
204 }
205};
206const getFileName = (input) => {
207 const m = /([^\\\/]+)$/.exec(input);
208 return m ? m[1] : "";
209};
210const camelcaseOptionName = (name) => {
211 return name.split(".").map((v, i) => {
212 return i === 0 ? camelcase(v) : v;
213 }).join(".");
214};
215class CACError extends Error {
216 constructor(message) {
217 super(message);
218 this.name = this.constructor.name;
219 if (typeof Error.captureStackTrace === "function") {
220 Error.captureStackTrace(this, this.constructor);
221 } else {
222 this.stack = new Error(message).stack;
223 }
224 }
225}
226
227class Option {
228 constructor(rawName, description, config) {
229 this.rawName = rawName;
230 this.description = description;
231 this.config = Object.assign({}, config);
232 rawName = rawName.replace(/\.\*/g, "");
233 this.negated = false;
234 this.names = removeBrackets(rawName).split(",").map((v) => {
235 let name = v.trim().replace(/^-{1,2}/, "");
236 if (name.startsWith("no-")) {
237 this.negated = true;
238 name = name.replace(/^no-/, "");
239 }
240 return camelcaseOptionName(name);
241 }).sort((a, b) => a.length > b.length ? 1 : -1);
242 this.name = this.names[this.names.length - 1];
243 if (this.negated) {
244 this.config.default = true;
245 }
246 if (rawName.includes("<")) {
247 this.required = true;
248 } else if (rawName.includes("[")) {
249 this.required = false;
250 } else {
251 this.isBoolean = true;
252 }
253 }
254}
255
256const processArgs = process.argv;
257const platformInfo = `${process.platform}-${process.arch} node-${process.version}`;
258
259class Command {
260 constructor(rawName, description, config = {}, cli) {
261 this.rawName = rawName;
262 this.description = description;
263 this.config = config;
264 this.cli = cli;
265 this.options = [];
266 this.aliasNames = [];
267 this.name = removeBrackets(rawName);
268 this.args = findAllBrackets(rawName);
269 this.examples = [];
270 }
271 usage(text) {
272 this.usageText = text;
273 return this;
274 }
275 allowUnknownOptions() {
276 this.config.allowUnknownOptions = true;
277 return this;
278 }
279 ignoreOptionDefaultValue() {
280 this.config.ignoreOptionDefaultValue = true;
281 return this;
282 }
283 version(version, customFlags = "-v, --version") {
284 this.versionNumber = version;
285 this.option(customFlags, "Display version number");
286 return this;
287 }
288 example(example) {
289 this.examples.push(example);
290 return this;
291 }
292 option(rawName, description, config) {
293 const option = new Option(rawName, description, config);
294 this.options.push(option);
295 return this;
296 }
297 alias(name) {
298 this.aliasNames.push(name);
299 return this;
300 }
301 action(callback) {
302 this.commandAction = callback;
303 return this;
304 }
305 isMatched(name) {
306 return this.name === name || this.aliasNames.includes(name);
307 }
308 get isDefaultCommand() {
309 return this.name === "" || this.aliasNames.includes("!");
310 }
311 get isGlobalCommand() {
312 return this instanceof GlobalCommand;
313 }
314 hasOption(name) {
315 name = name.split(".")[0];
316 return this.options.find((option) => {
317 return option.names.includes(name);
318 });
319 }
320 outputHelp() {
321 const {name, commands} = this.cli;
322 const {
323 versionNumber,
324 options: globalOptions,
325 helpCallback
326 } = this.cli.globalCommand;
327 let sections = [
328 {
329 body: `${name}${versionNumber ? `/${versionNumber}` : ""}`
330 }
331 ];
332 sections.push({
333 title: "Usage",
334 body: ` $ ${name} ${this.usageText || this.rawName}`
335 });
336 const showCommands = (this.isGlobalCommand || this.isDefaultCommand) && commands.length > 0;
337 if (showCommands) {
338 const longestCommandName = findLongest(commands.map((command) => command.rawName));
339 sections.push({
340 title: "Commands",
341 body: commands.map((command) => {
342 return ` ${padRight(command.rawName, longestCommandName.length)} ${command.description}`;
343 }).join("\n")
344 });
345 sections.push({
346 title: `For more info, run any command with the \`--help\` flag`,
347 body: commands.map((command) => ` $ ${name}${command.name === "" ? "" : ` ${command.name}`} --help`).join("\n")
348 });
349 }
350 const options = this.isGlobalCommand ? globalOptions : [...this.options, ...globalOptions || []];
351 if (options.length > 0) {
352 const longestOptionName = findLongest(options.map((option) => option.rawName));
353 sections.push({
354 title: "Options",
355 body: options.map((option) => {
356 return ` ${padRight(option.rawName, longestOptionName.length)} ${option.description} ${option.config.default === void 0 ? "" : `(default: ${option.config.default})`}`;
357 }).join("\n")
358 });
359 }
360 if (this.examples.length > 0) {
361 sections.push({
362 title: "Examples",
363 body: this.examples.map((example) => {
364 if (typeof example === "function") {
365 return example(name);
366 }
367 return example;
368 }).join("\n")
369 });
370 }
371 if (helpCallback) {
372 sections = helpCallback(sections) || sections;
373 }
374 console.log(sections.map((section) => {
375 return section.title ? `${section.title}:
376${section.body}` : section.body;
377 }).join("\n\n"));
378 }
379 outputVersion() {
380 const {name} = this.cli;
381 const {versionNumber} = this.cli.globalCommand;
382 if (versionNumber) {
383 console.log(`${name}/${versionNumber} ${platformInfo}`);
384 }
385 }
386 checkRequiredArgs() {
387 const minimalArgsCount = this.args.filter((arg) => arg.required).length;
388 if (this.cli.args.length < minimalArgsCount) {
389 throw new CACError(`missing required args for command \`${this.rawName}\``);
390 }
391 }
392 checkUnknownOptions() {
393 const {options, globalCommand} = this.cli;
394 if (!this.config.allowUnknownOptions) {
395 for (const name of Object.keys(options)) {
396 if (name !== "--" && !this.hasOption(name) && !globalCommand.hasOption(name)) {
397 throw new CACError(`Unknown option \`${name.length > 1 ? `--${name}` : `-${name}`}\``);
398 }
399 }
400 }
401 }
402 checkOptionValue() {
403 const {options: parsedOptions, globalCommand} = this.cli;
404 const options = [...globalCommand.options, ...this.options];
405 for (const option of options) {
406 const value = parsedOptions[option.name.split(".")[0]];
407 if (option.required) {
408 const hasNegated = options.some((o) => o.negated && o.names.includes(option.name));
409 if (value === true || value === false && !hasNegated) {
410 throw new CACError(`option \`${option.rawName}\` value is missing`);
411 }
412 }
413 }
414 }
415}
416class GlobalCommand extends Command {
417 constructor(cli) {
418 super("@@global@@", "", {}, cli);
419 }
420}
421
422var __assign = Object.assign;
423class CAC extends EventEmitter {
424 constructor(name = "") {
425 super();
426 this.name = name;
427 this.commands = [];
428 this.rawArgs = [];
429 this.args = [];
430 this.options = {};
431 this.globalCommand = new GlobalCommand(this);
432 this.globalCommand.usage("<command> [options]");
433 }
434 usage(text) {
435 this.globalCommand.usage(text);
436 return this;
437 }
438 command(rawName, description, config) {
439 const command = new Command(rawName, description || "", config, this);
440 command.globalCommand = this.globalCommand;
441 this.commands.push(command);
442 return command;
443 }
444 option(rawName, description, config) {
445 this.globalCommand.option(rawName, description, config);
446 return this;
447 }
448 help(callback) {
449 this.globalCommand.option("-h, --help", "Display this message");
450 this.globalCommand.helpCallback = callback;
451 this.showHelpOnExit = true;
452 return this;
453 }
454 version(version, customFlags = "-v, --version") {
455 this.globalCommand.version(version, customFlags);
456 this.showVersionOnExit = true;
457 return this;
458 }
459 example(example) {
460 this.globalCommand.example(example);
461 return this;
462 }
463 outputHelp() {
464 if (this.matchedCommand) {
465 this.matchedCommand.outputHelp();
466 } else {
467 this.globalCommand.outputHelp();
468 }
469 }
470 outputVersion() {
471 this.globalCommand.outputVersion();
472 }
473 setParsedInfo({args, options}, matchedCommand, matchedCommandName) {
474 this.args = args;
475 this.options = options;
476 if (matchedCommand) {
477 this.matchedCommand = matchedCommand;
478 }
479 if (matchedCommandName) {
480 this.matchedCommandName = matchedCommandName;
481 }
482 return this;
483 }
484 unsetMatchedCommand() {
485 this.matchedCommand = void 0;
486 this.matchedCommandName = void 0;
487 }
488 parse(argv = processArgs, {
489 run = true
490 } = {}) {
491 this.rawArgs = argv;
492 if (!this.name) {
493 this.name = argv[1] ? getFileName(argv[1]) : "cli";
494 }
495 let shouldParse = true;
496 for (const command of this.commands) {
497 const parsed = this.mri(argv.slice(2), command);
498 const commandName = parsed.args[0];
499 if (command.isMatched(commandName)) {
500 shouldParse = false;
501 const parsedInfo = __assign(__assign({}, parsed), {
502 args: parsed.args.slice(1)
503 });
504 this.setParsedInfo(parsedInfo, command, commandName);
505 this.emit(`command:${commandName}`, command);
506 }
507 }
508 if (shouldParse) {
509 for (const command of this.commands) {
510 if (command.name === "") {
511 shouldParse = false;
512 const parsed = this.mri(argv.slice(2), command);
513 this.setParsedInfo(parsed, command);
514 this.emit(`command:!`, command);
515 }
516 }
517 }
518 if (shouldParse) {
519 const parsed = this.mri(argv.slice(2));
520 this.setParsedInfo(parsed);
521 }
522 if (this.options.help && this.showHelpOnExit) {
523 this.outputHelp();
524 run = false;
525 this.unsetMatchedCommand();
526 }
527 if (this.options.version && this.showVersionOnExit) {
528 this.outputVersion();
529 run = false;
530 this.unsetMatchedCommand();
531 }
532 const parsedArgv = {args: this.args, options: this.options};
533 if (run) {
534 this.runMatchedCommand();
535 }
536 if (!this.matchedCommand && this.args[0]) {
537 this.emit("command:*");
538 }
539 return parsedArgv;
540 }
541 mri(argv, command) {
542 const cliOptions = [
543 ...this.globalCommand.options,
544 ...command ? command.options : []
545 ];
546 const mriOptions = getMriOptions(cliOptions);
547 let argsAfterDoubleDashes = [];
548 const doubleDashesIndex = argv.indexOf("--");
549 if (doubleDashesIndex > -1) {
550 argsAfterDoubleDashes = argv.slice(doubleDashesIndex + 1);
551 argv = argv.slice(0, doubleDashesIndex);
552 }
553 let parsed = mri2(argv, mriOptions);
554 parsed = Object.keys(parsed).reduce((res, name) => {
555 return __assign(__assign({}, res), {
556 [camelcaseOptionName(name)]: parsed[name]
557 });
558 }, {_: []});
559 const args = parsed._;
560 const options = {
561 "--": argsAfterDoubleDashes
562 };
563 const ignoreDefault = command && command.config.ignoreOptionDefaultValue ? command.config.ignoreOptionDefaultValue : this.globalCommand.config.ignoreOptionDefaultValue;
564 let transforms = Object.create(null);
565 for (const cliOption of cliOptions) {
566 if (!ignoreDefault && cliOption.config.default !== void 0) {
567 for (const name of cliOption.names) {
568 options[name] = cliOption.config.default;
569 }
570 }
571 if (Array.isArray(cliOption.config.type)) {
572 if (transforms[cliOption.name] === void 0) {
573 transforms[cliOption.name] = Object.create(null);
574 transforms[cliOption.name]["shouldTransform"] = true;
575 transforms[cliOption.name]["transformFunction"] = cliOption.config.type[0];
576 }
577 }
578 }
579 for (const key of Object.keys(parsed)) {
580 if (key !== "_") {
581 const keys = key.split(".");
582 setDotProp(options, keys, parsed[key]);
583 setByType(options, transforms);
584 }
585 }
586 return {
587 args,
588 options
589 };
590 }
591 runMatchedCommand() {
592 const {args, options, matchedCommand: command} = this;
593 if (!command || !command.commandAction)
594 return;
595 command.checkUnknownOptions();
596 command.checkOptionValue();
597 command.checkRequiredArgs();
598 const actionArgs = [];
599 command.args.forEach((arg, index) => {
600 if (arg.variadic) {
601 actionArgs.push(args.slice(index));
602 } else {
603 actionArgs.push(args[index]);
604 }
605 });
606 actionArgs.push(options);
607 return command.commandAction.apply(this, actionArgs);
608 }
609}
610
611const cac = (name = "") => new CAC(name);
612if (typeof module !== "undefined") {
613 module.exports = cac;
614 module.exports.default = cac;
615 module.exports.cac = cac;
616}
617
618export default cac;
619export { CAC, Command, cac };