1 | 'use strict';
|
2 |
|
3 | const { logger } = require('@carbon/cli-tools');
|
4 |
|
5 | function 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 |
|
49 | console.error(error);
|
50 | process.exit(1);
|
51 | }
|
52 | });
|
53 | }
|
54 |
|
55 |
|
56 |
|
57 | function cleanArgs(command) {
|
58 | return command.options.reduce((acc, option) => {
|
59 |
|
60 |
|
61 |
|
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 |
|
74 |
|
75 | if (typeof command[key] !== 'function') {
|
76 | return {
|
77 | ...acc,
|
78 | [key]: command[key],
|
79 | };
|
80 | }
|
81 | return acc;
|
82 | }, {});
|
83 | }
|
84 |
|
85 | module.exports = addCommandToProgram;
|