forked from serverless/serverless
/
CLI.js
423 lines (353 loc) · 13.1 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
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
'use strict';
const version = require('../../package.json').version;
const enterpriseVersion = require('@serverless/enterprise-plugin/package.json').version;
const { sdkVersion } = require('@serverless/enterprise-plugin');
const _ = require('lodash');
const os = require('os');
const chalk = require('chalk');
const getCommandSuggestion = require('../utils/getCommandSuggestion');
const resolveCliInput = require('../utils/resolveCliInput');
const helpCommandNames = new Set(['help', 'version']);
class CLI {
constructor(serverless, inputArray) {
this.serverless = serverless;
this.inputArray = inputArray || null;
this.loadedPlugins = [];
this.loadedCommands = {};
}
setLoadedPlugins(plugins) {
this.loadedPlugins = plugins;
}
setLoadedCommands(commands) {
this.loadedCommands = commands;
}
processInput() {
let inputArray;
// check if commands are passed externally (e.g. used by tests)
// otherwise use process.argv to receive the commands
if (this.inputArray !== null) {
inputArray = this.inputArray;
} else {
inputArray = process.argv.slice(2);
}
return resolveCliInput(inputArray);
}
suppressLogIfPrintCommand(processedInput) {
const commands = processedInput.commands;
const options = processedInput.options;
// if "-help" or "-h" was entered
if (options.help || options.h) {
return;
}
// if "print" was NOT entered
if (commands.indexOf('print') === -1) {
return;
}
// if other command was combined with "print"
if (commands.length !== 1) {
return;
}
// Make "log" no-op to suppress warnings.
// But preserve "consoleLog" which "print" command use to print config.
this.log = function() {};
}
isHelpRequest(processedInput) {
const commands = processedInput.commands;
const options = processedInput.options;
if (options.help || options.h) return true;
switch (commands.length) {
case 0:
if (options.version || options.v) return true;
if (options['help-interactive']) return true;
return false;
case 1:
return helpCommandNames.has(commands[0]);
default:
return false;
}
}
displayHelp(processedInput) {
const commands = processedInput.commands;
const options = processedInput.options;
switch (commands.length) {
case 0:
if (options.version || options.v) {
this.getVersionNumber();
return true;
}
if (options['help-interactive']) {
this.generateInteractiveCliHelp();
return true;
}
if (options.verbose) this.generateVerboseHelp();
else this.generateMainHelp();
return true;
case 1:
if (commands[0] === 'version') {
this.getVersionNumber();
return true;
}
if (commands[0] === 'help') {
if (options.verbose) this.generateVerboseHelp();
else this.generateMainHelp();
return true;
}
// fallthrough
default:
if (options.help || options.h) {
this.generateCommandsHelp(commands);
return true;
}
return false;
}
}
displayCommandUsage(commandObject, command, indents) {
if (commandObject.isHidden) return;
const dotsLength = 30;
// check if command has lifecycleEvents (can be executed) and it's not a container command
if (commandObject.lifecycleEvents && commandObject.type !== 'container') {
const usage = commandObject.usage;
const dots = '.'.repeat(Math.max(dotsLength - command.length, 0));
const indent = ' '.repeat(indents || 0);
this.consoleLog(`${indent}${chalk.yellow(command)} ${chalk.dim(dots)} ${usage}`);
}
if (commandObject.commands) {
Object.entries(commandObject.commands).forEach(([subcommand, subcommandObject]) => {
this.displayCommandUsage(subcommandObject, `${command} ${subcommand}`, indents);
});
}
}
displayCommandOptions(commandObject) {
const dotsLength = 40;
const commandOptions = commandObject.configDependent
? Object.assign({}, commandObject.options, {
config: {
usage: 'Path to serverless config file',
shortcut: 'c',
},
})
: commandObject.options;
Object.entries(commandOptions).forEach(([option, optionsObject]) => {
let optionsDots = '.'.repeat(Math.max(dotsLength - option.length, 0));
const optionsUsage = optionsObject.usage;
if (optionsObject.required) {
optionsDots = optionsDots.slice(0, optionsDots.length - 18);
} else {
optionsDots = optionsDots.slice(0, optionsDots.length - 7);
}
if (optionsObject.shortcut) {
optionsDots = optionsDots.slice(0, optionsDots.length - 5);
}
const optionInfo = ` --${option}`;
let shortcutInfo = '';
let requiredInfo = '';
if (optionsObject.shortcut) {
shortcutInfo = ` / -${optionsObject.shortcut}`;
}
if (optionsObject.required) {
requiredInfo = ' (required)';
}
const thingsToLog = `${optionInfo}${shortcutInfo}${requiredInfo} ${chalk.dim(
optionsDots
)} ${optionsUsage}`;
this.consoleLog(chalk.yellow(thingsToLog));
});
}
generateMainHelp() {
this.consoleLog('');
this.consoleLog(chalk.yellow.underline('Commands'));
this.consoleLog(chalk.dim('* You can run commands with "serverless" or the shortcut "sls"'));
this.consoleLog(chalk.dim('* Pass "--verbose" to this command to get in-depth plugin info'));
this.consoleLog(chalk.dim('* Pass "--no-color" to disable CLI colors'));
this.consoleLog(chalk.dim('* Pass "--help" after any <command> for contextual help'));
this.consoleLog('');
this.consoleLog(chalk.yellow.underline('Interactive Quickstart'));
this.consoleLog(
chalk.dim(
`* Run serverless (or shortcut sls) without any arguments to initialize an interactive setup
of functionalities related to given service or current environment`
)
);
this.consoleLog(
chalk.dim('* Pass "--help-interactive" for contextual help on interactive CLI options')
);
this.consoleLog('');
this.consoleLog(chalk.yellow.underline('Serverless Components'));
this.consoleLog(
chalk.dim(
'* Run serverless (or shortcut sls) in context of a component service to initialize a components CLI'
)
);
this.consoleLog(
chalk.dim('* Pass "--help-components" for contextual help on Serverless Components')
);
this.consoleLog('');
this.consoleLog(chalk.yellow.underline('Framework'));
this.consoleLog(chalk.dim('* Documentation: http://slss.io/docs'));
this.consoleLog('');
this.consoleLog(chalk.yellow.underline('Environment Variables'));
this.consoleLog(chalk.dim('* Set SLS_DEBUG=* to see debugging logs'));
this.consoleLog(chalk.dim('* Set SLS_WARNING_DISABLE=* to hide warnings from the output'));
this.consoleLog(
chalk.dim(
"* Set SLS_MAX_CONCURRENT_ARTIFACTS_UPLOADS to control the maximum S3 upload SDK requests that are sent in parallel during the deployment of the service's artifacts. The default is 3. Note: increasing this too high might, actually, downgrade the overall upload speed"
)
);
this.consoleLog('');
if (Object.keys(this.loadedCommands).length) {
Object.entries(this.loadedCommands).forEach(([command, details]) => {
this.displayCommandUsage(details, command);
});
} else {
this.consoleLog('No commands found');
}
this.consoleLog('');
// print all the installed plugins
this.consoleLog(chalk.yellow.underline('Plugins'));
if (this.loadedPlugins.length) {
const sortedPlugins = this.loadedPlugins.sort((plugin1, plugin2) =>
plugin1.constructor.name.localeCompare(plugin2.constructor.name)
);
this.consoleLog(sortedPlugins.map(plugin => plugin.constructor.name).join(', '));
} else {
this.consoleLog('No plugins added yet');
}
}
generateInteractiveCliHelp() {
this.consoleLog(chalk.yellow.underline('Interactive CLI'));
this.consoleLog(
chalk.yellow(
`Run serverless (or shortcut sls) a subcommand to initialize an interactive setup of
functionalities related to given service or current environment.`
)
);
const command = this.loadedPlugins.find(plugin => plugin.constructor.name === 'InteractiveCli')
.commands.interactiveCli;
this.displayCommandOptions(command);
}
generateVerboseHelp() {
this.consoleLog('');
this.consoleLog(chalk.yellow.underline('Commands by plugin'));
this.consoleLog('');
let pluginCommands = {};
// add commands to pluginCommands based on command's plugin
const addToPluginCommands = cmd => {
const pcmd = _.clone(cmd);
// remove subcommand from clone
delete pcmd.commands;
// check if a plugin entry is already present in pluginCommands. Use the
// existing one or create a new plugin entry.
if (pluginCommands[pcmd.pluginName]) {
pluginCommands[pcmd.pluginName] = pluginCommands[pcmd.pluginName].concat(pcmd);
} else {
pluginCommands[pcmd.pluginName] = [pcmd];
}
// check for subcommands
if ('commands' in cmd) {
Object.values(cmd.commands).forEach(d => {
addToPluginCommands(d);
});
}
};
// fill up pluginCommands with commands in loadedCommands
Object.values(this.loadedCommands).forEach(details => {
addToPluginCommands(details);
});
// sort plugins alphabetically
pluginCommands = _(Object.entries(pluginCommands))
.sortBy(0)
.fromPairs()
.value();
Object.entries(pluginCommands).forEach(([plugin, details]) => {
this.consoleLog(plugin);
details.forEach(cmd => {
// display command usage with single(1) indent
this.displayCommandUsage(cmd, cmd.key.split(':').join(' '), 1);
});
this.consoleLog('');
});
}
generateCommandsHelp(commandsArray) {
const commandName = commandsArray.join(' ');
// Get all the commands using getCommands() with filtered entrypoint
// commands and reduce to the required command.
const allCommands = this.serverless.pluginManager.getCommands();
const command = commandsArray.reduce(
(currentCmd, cmd) => {
if (currentCmd.commands && cmd in currentCmd.commands) {
return currentCmd.commands[cmd];
}
return null;
},
{ commands: allCommands }
);
// Throw error if command not found.
if (!command) {
const suggestedCommand = getCommandSuggestion(commandName, allCommands);
const errorMessage = [
`Serverless command "${commandName}" not found. Did you mean "${suggestedCommand}"?`,
' Run "serverless help" for a list of all available commands.',
].join('');
throw new this.serverless.classes.Error(errorMessage);
}
// print the name of the plugin
this.consoleLog(chalk.yellow.underline(`Plugin: ${command.pluginName}`));
this.displayCommandUsage(command, commandName);
this.displayCommandOptions(command);
this.consoleLog('');
return null;
}
getVersionNumber() {
const installationModePostfix = (() => {
if (this.serverless.isStandaloneExecutable) return ' (standalone)';
if (this.serverless.isLocallyInstalled) return ' (local)';
return '';
})();
this.consoleLog(
`Framework Core: ${version}${installationModePostfix}\n` +
`Plugin: ${enterpriseVersion}\n` +
`SDK: ${sdkVersion}`
);
const userNodeVersion = Number(process.version.split('.')[0].slice(1));
// only show components version if user is running Node 8+
if (userNodeVersion >= 8) {
const componentsVersion = (() => {
try {
return require('@serverless/components/package').version;
} catch (error) {
return 'Unavailable';
}
})();
this.consoleLog(`Components: ${componentsVersion}`);
}
}
asciiGreeting() {
let art = '';
art = `${art} _______ __${os.EOL}`;
art = `${art}| _ .-----.----.--.--.-----.----| .-----.-----.-----.${os.EOL}`;
art = `${art}| |___| -__| _| | | -__| _| | -__|__ --|__ --|${os.EOL}`;
art = `${art}|____ |_____|__| \\___/|_____|__| |__|_____|_____|_____|${os.EOL}`;
art = `${art}| | | The Serverless Application Framework${os.EOL}`;
art = `${art}| | serverless.com, v${version}${os.EOL}`;
art = `${art} -------'`;
this.consoleLog(chalk.yellow(art));
this.consoleLog('');
}
printDot() {
process.stdout.write(chalk.yellow('.'));
}
log(message, entity, opts) {
const underline = opts ? opts.underline : false;
const bold = opts ? opts.bold : false;
const color = opts ? opts.color : null;
let print = chalk.yellow;
if (color) print = chalk.keyword(color);
if (underline) print = print.underline;
if (bold) print = print.bold;
this.consoleLog(`${entity || 'Serverless'}: ${print(message)}`);
}
consoleLog(message) {
console.log(message); // eslint-disable-line no-console
}
}
module.exports = CLI;