UNPKG

2.19 kBJavaScriptView Raw
1'use strict';
2
3const { logger } = require('@carbon/cli-tools');
4
5function addCommandToProgram(program, command, CLI_ENV) {
6 const { name, description, options = [], action, ...rest } = command;
7 const cliCommand = program.command(name).description(description);
8
9 for (const option of options) {
10 const { flags, description, defaults, development } = option;
11
12 if (development) {
13 if (CLI_ENV === 'development') {
14 const args = [flags, `${description} [DEV ONLY]`, defaults].filter(
15 Boolean
16 );
17 cliCommand.option(...args);
18 }
19 } else {
20 const args = [flags, description, defaults].filter(Boolean);
21 cliCommand.option(...args);
22 }
23 }
24
25 for (const key of Object.keys(rest)) {
26 if (cliCommand[key]) {
27 cliCommand[key]();
28 }
29 }
30
31 cliCommand.action(async (...args) => {
32 const commandArgs = args.slice(0, args.length - 1);
33 const command = args[args.length - 1];
34 const options = cleanArgs(command);
35
36 logger.trace(
37 'Running command:',
38 name,
39 'with args:',
40 commandArgs,
41 'and options:',
42 options
43 );
44
45 try {
46 await action(...commandArgs, options);
47 } catch (error) {
48 // eslint-disable-next-line no-console
49 console.error(error);
50 process.exit(1);
51 }
52 });
53}
54
55// Inspired by Vue CLI:
56// https://github.com/vuejs/vue-cli/blob/31e1b4995edef3d2079da654deedffe002a1d689/packages/%40vue/cli/bin/vue.js#L172
57function cleanArgs(command) {
58 return command.options.reduce((acc, option) => {
59 // TODO: add case for reserved words from commander, like options
60
61 // Add case for mapping `--foo-bar` to `fooBar`
62 const key = option.long
63 .replace(/^--/, '')
64 .split('-')
65 .map((word, i) => {
66 if (i === 0) {
67 return word;
68 }
69 return word[0].toUpperCase() + word.slice(1);
70 })
71 .join('');
72
73 // If an option is not present and Command has a method with the same name
74 // it should not be copied
75 if (typeof command[key] !== 'function') {
76 return {
77 ...acc,
78 [key]: command[key],
79 };
80 }
81 return acc;
82 }, {});
83}
84
85module.exports = addCommandToProgram;