forked from pnp/cli-microsoft365
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCli.ts
More file actions
832 lines (715 loc) · 26.7 KB
/
Cli.ts
File metadata and controls
832 lines (715 loc) · 26.7 KB
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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
import type * as Chalk from 'chalk';
import type * as Configstore from 'configstore';
import * as fs from 'fs';
import type { Inquirer } from 'inquirer';
import type * as JMESPath from 'jmespath';
import type * as Markshell from 'markshell';
import * as minimist from 'minimist';
import * as os from 'os';
import * as path from 'path';
import { Logger } from '.';
import appInsights from '../appInsights';
import Command, { CommandArgs, CommandError } from '../Command';
import config from '../config';
import { settingsNames } from '../settingsNames';
import Utils from '../Utils';
import { CommandInfo } from './CommandInfo';
import { CommandOptionInfo } from './CommandOptionInfo';
const packageJSON = require('../../package.json');
export interface CommandOutput {
stdout: string;
stderr: string;
}
export class Cli {
public commands: CommandInfo[] = [];
/**
* Command to execute
*/
private commandToExecute: CommandInfo | undefined;
/**
* Name of the command specified through args
*/
public currentCommandName: string | undefined;
private optionsFromArgs: { options: minimist.ParsedArgs } | undefined;
private commandsFolder: string = '';
private static instance: Cli;
private _config: Configstore | undefined;
public get config(): Configstore {
if (!this._config) {
const configStore: typeof Configstore = require('configstore');
this._config = new configStore(config.configstoreName);
}
return this._config;
}
public getSettingWithDefaultValue<TValue>(settingName: string, defaultValue: TValue): TValue {
const configuredValue: TValue | undefined = this.config.get(settingName);
if (typeof configuredValue === 'undefined') {
return defaultValue;
}
else {
return configuredValue;
}
}
// eslint-disable-next-line @typescript-eslint/no-empty-function
private constructor() {
}
public static getInstance(): Cli {
if (!Cli.instance) {
Cli.instance = new Cli();
}
return Cli.instance;
}
public async execute(commandsFolder: string, rawArgs: string[]): Promise<void> {
this.commandsFolder = commandsFolder;
// check if help for a specific command has been requested using the
// 'm365 help xyz' format. If so, remove 'help' from the array of words
// to use lazy loading commands but keep track of the fact that help should
// be displayed
let showHelp: boolean = false;
if (rawArgs.length > 0 && rawArgs[0] === 'help') {
showHelp = true;
rawArgs.shift();
}
// parse args to see if a command has been specified and can be loaded
// rather than loading all commands
const parsedArgs: minimist.ParsedArgs = minimist(rawArgs);
// load commands
this.loadCommandFromArgs(parsedArgs._);
if (this.currentCommandName) {
for (let i = 0; i < this.commands.length; i++) {
const command: CommandInfo = this.commands[i];
if (command.name === this.currentCommandName ||
(command.aliases &&
command.aliases.indexOf(this.currentCommandName) > -1)) {
this.commandToExecute = command;
break;
}
}
}
if (this.commandToExecute) {
// we have found a command to execute. Parse args again taking into
// account short and long options, option types and whether the command
// supports known and unknown options or not
this.optionsFromArgs = {
options: this.getCommandOptionsFromArgs(rawArgs, this.commandToExecute)
};
}
else {
this.optionsFromArgs = {
options: parsedArgs
};
}
// show help if no match found, help explicitly requested or
// no command specified
if (!this.commandToExecute ||
showHelp ||
parsedArgs.h ||
parsedArgs.help) {
this.printHelp();
return Promise.resolve();
}
// if the command doesn't allow unknown options, check if all specified
// options match command options
if (!this.commandToExecute.command.allowUnknownOptions()) {
for (const optionFromArgs in this.optionsFromArgs.options) {
if (optionFromArgs === '_') {
// ignore catch-all option
continue;
}
let matches: boolean = false;
for (let i = 0; i < this.commandToExecute.options.length; i++) {
const option: CommandOptionInfo = this.commandToExecute.options[i];
if (optionFromArgs === option.long ||
optionFromArgs === option.short) {
matches = true;
break;
}
}
if (!matches) {
return this.closeWithError(`Invalid option: '${optionFromArgs}'${os.EOL}`, this.optionsFromArgs, true);
}
}
}
// validate options
// validate required options
for (let i = 0; i < this.commandToExecute.options.length; i++) {
if (this.commandToExecute.options[i].required &&
typeof this.optionsFromArgs.options[this.commandToExecute.options[i].name] === 'undefined') {
return this.closeWithError(`Required option ${this.commandToExecute.options[i].name} not specified`, this.optionsFromArgs, true);
}
}
const optionsWithoutShorts = Cli.removeShortOptions(this.optionsFromArgs);
try {
// replace values staring with @ with file contents
Cli.loadOptionValuesFromFiles(optionsWithoutShorts);
}
catch (e) {
return this.closeWithError(e, optionsWithoutShorts);
}
try {
// process options before passing them on to validation stage
await this.commandToExecute.command.processOptions(optionsWithoutShorts.options);
}
catch (e) {
return this.closeWithError(e.message, optionsWithoutShorts, false);
}
// if output not specified, set the configured output value (if any)
if (optionsWithoutShorts.options.output === undefined) {
optionsWithoutShorts.options.output = this.getSettingWithDefaultValue<string | undefined>(settingsNames.output, undefined);
}
const validationResult: boolean | string = this.commandToExecute.command.validate(optionsWithoutShorts);
if (typeof validationResult === 'string') {
return this.closeWithError(validationResult, optionsWithoutShorts, true);
}
return Cli
.executeCommand(this.commandToExecute.command, optionsWithoutShorts)
.then(_ => process.exit(0), err => this.closeWithError(err, optionsWithoutShorts));
}
public static executeCommand(command: Command, args: { options: minimist.ParsedArgs }): Promise<void> {
return new Promise<void>((resolve: () => void, reject: (error: any) => void): void => {
const logger: Logger = {
log: (message: any): void => {
const output: any = Cli.formatOutput(message, args.options);
Cli.log(output);
},
logRaw: (message: any): void => Cli.log(message),
logToStderr: (message: any): void => Cli.error(message)
};
if (args.options.debug) {
logger.logToStderr(`Executing command ${command.name} with options ${JSON.stringify(args)}`);
}
// store the current command name, if any and set the name to the name of
// the command to execute
const cli = Cli.getInstance();
const parentCommandName: string | undefined = cli.currentCommandName;
cli.currentCommandName = command.getCommandName();
command.action(logger, args as any, (err: any): void => {
// restore the original command name
cli.currentCommandName = parentCommandName;
if (err) {
return reject(err);
}
if (args.options.debug || args.options.verbose) {
const chalk: typeof Chalk = require('chalk');
logger.logToStderr(chalk.green('DONE'));
}
resolve();
});
});
}
public static executeCommandWithOutput(command: Command, args: { options: minimist.ParsedArgs }): Promise<CommandOutput> {
return new Promise((resolve: (result: CommandOutput) => void, reject: (error: any) => void): void => {
const log: string[] = [];
const logErr: string[] = [];
const logger: Logger = {
log: (message: any): void => {
log.push(Cli.formatOutput(message, args.options));
},
logRaw: (message: any): void => {
log.push(Cli.formatOutput(message, args.options));
},
logToStderr: (message: any): void => {
logErr.push(message);
}
};
if (args.options.debug) {
Cli.log(`Executing command ${command.name} with options ${JSON.stringify(args)}`);
}
// store the current command name, if any and set the name to the name of
// the command to execute
const cli = Cli.getInstance();
const parentCommandName: string | undefined = cli.currentCommandName;
cli.currentCommandName = command.getCommandName();
command.action(logger, args as any, (err: any): void => {
// restore the original command name
cli.currentCommandName = parentCommandName;
if (err) {
return reject({
error: err,
stderr: logErr.join(os.EOL)
});
}
resolve({
stdout: log.join(os.EOL),
stderr: logErr.join(os.EOL)
});
});
});
}
public loadAllCommands(): void {
const files: string[] = Utils.readdirR(this.commandsFolder) as string[];
files.forEach(file => {
if (file.indexOf(`${path.sep}commands${path.sep}`) > -1 &&
file.indexOf(`${path.sep}assets${path.sep}`) < 0 &&
file.endsWith('.js') &&
!file.endsWith('.spec.js')) {
try {
const command: any = require(file);
if (command instanceof Command) {
this.loadCommand(command);
}
}
catch (e) {
this.closeWithError(e, { options: {} });
}
}
});
}
/**
* Loads command files into CLI based on the specified arguments.
*
* @param commandNameWords Array of words specified as args
*/
public loadCommandFromArgs(commandNameWords: string[]): void {
this.currentCommandName = commandNameWords.join(' ');
if (commandNameWords.length === 0) {
this.loadAllCommands();
return;
}
const isCompletionCommand: boolean = commandNameWords.indexOf('completion') > -1;
if (isCompletionCommand) {
this.loadAllCommands();
return;
}
let commandFilePath = '';
if (commandNameWords.length === 1) {
commandFilePath = path.join(this.commandsFolder, 'commands', `${commandNameWords[0]}.js`);
}
else {
if (commandNameWords.length === 2) {
commandFilePath = path.join(this.commandsFolder, commandNameWords[0], 'commands', `${commandNameWords.join('-')}.js`);
}
else {
commandFilePath = path.join(this.commandsFolder, commandNameWords[0], 'commands', commandNameWords[1], commandNameWords.slice(1).join('-') + '.js');
}
}
this.loadCommandFromFile(commandFilePath);
}
/**
* Loads command from the specified file into CLI. If can't find the file
* or the file doesn't contain a command, loads all available commands.
*
* @param commandFilePath File path of the file with command to load
*/
private loadCommandFromFile(commandFilePath: string): void {
if (!fs.existsSync(commandFilePath)) {
this.loadAllCommands();
return;
}
try {
const command: any = require(commandFilePath);
if (command instanceof Command) {
this.loadCommand(command);
}
else {
this.loadAllCommands();
}
}
catch {
this.loadAllCommands();
}
}
private loadCommand(command: Command): void {
this.commands.push({
aliases: command.alias(),
name: command.name,
command: command,
options: this.getCommandOptions(command),
defaultProperties: command.defaultProperties()
});
}
private getCommandOptions(command: Command): CommandOptionInfo[] {
const options: CommandOptionInfo[] = [];
command.options().forEach(option => {
const required: boolean = option.option.indexOf('<') > -1;
const optionArgs: string[] = option.option.split(/[ ,|]+/);
let short: string | undefined;
let long: string | undefined;
let name: string = '';
optionArgs.forEach(o => {
if (o.startsWith('--')) {
long = o.replace('--', '');
name = long;
}
else if (o.startsWith('-')) {
short = o.replace('-', '');
name = short;
}
});
options.push({
autocomplete: option.autocomplete,
long: long,
name: name,
required: required,
short: short
});
});
return options;
}
private getCommandOptionsFromArgs(args: string[], commandInfo: CommandInfo | undefined): minimist.ParsedArgs {
const minimistOptions: minimist.Opts = {
alias: {}
};
if (commandInfo) {
const commandTypes = commandInfo.command.types();
if (commandTypes) {
minimistOptions.string = commandTypes.string;
minimistOptions.boolean = commandTypes.boolean;
}
minimistOptions.alias = {};
commandInfo.options.forEach(option => {
if (option.short && option.long) {
(minimistOptions.alias as any)[option.short] = option.long;
}
});
}
return minimist(args, minimistOptions);
}
private static formatOutput(logStatement: any, options: any): any {
if (logStatement instanceof Date) {
return logStatement.toString();
}
let logStatementType: string = typeof logStatement;
if (logStatementType === 'undefined') {
return logStatement;
}
// we need to get the list of object's properties to see if the specified
// JMESPath query (if any) filters object's properties or not. We need to
// know this in order to decide if we should use default command's
// properties or custom ones from JMESPath
const originalObject: any = Array.isArray(logStatement) ? Cli.getFirstNonUndefinedArrayItem(logStatement) : logStatement;
const originalProperties: string[] = originalObject ? Object.getOwnPropertyNames(originalObject) : [];
if (options.query &&
!options.help) {
const jmespath: typeof JMESPath = require('jmespath');
try {
logStatement = jmespath.search(logStatement, options.query);
}
catch (e) {
const message = `JMESPath query error. ${e.message}. See https://jmespath.org/specification.html for more information`;
Cli.getInstance().closeWithError(message, { options }, false);
}
// we need to update the statement type in case the JMESPath query
// returns an object of different shape than the original message to log
// #2095
logStatementType = typeof logStatement;
}
if (options.output === 'json') {
return JSON.stringify(logStatement, null, 2);
}
if (logStatement instanceof CommandError) {
const chalk: typeof Chalk = require('chalk');
return chalk.red(`Error: ${logStatement.message}`);
}
let arrayType: string = '';
if (!Array.isArray(logStatement)) {
logStatement = [logStatement];
arrayType = logStatementType;
}
else {
for (let i: number = 0; i < logStatement.length; i++) {
if (Array.isArray(logStatement[i])) {
arrayType = 'array';
break;
}
const t: string = typeof logStatement[i];
if (t !== 'undefined') {
arrayType = t;
break;
}
}
}
if (arrayType !== 'object') {
return logStatement.join(os.EOL);
}
// if output type has not been set or set to 'text', process the retrieved
// data so that returned objects contain only default properties specified
// on the current command. If there is no current command or the
// command doesn't specify default properties, return original data
if (!options.output || options.output === 'text') {
const cli: Cli = Cli.getInstance();
const currentCommand: CommandInfo | undefined = cli.commandToExecute;
if (arrayType === 'object' &&
currentCommand && currentCommand.defaultProperties) {
// the log statement contains the same properties as the original object
// so it can be filtered following the default properties specified on
// the command
if (JSON.stringify(originalProperties) === JSON.stringify(Object.getOwnPropertyNames(logStatement[0]))) {
// in some cases we return properties wrapped in `value` array
// returned by the API. We'll remove it in the future, but for now
// we'll use a workaround to drop the `value` array here
if (logStatement[0].value &&
Array.isArray(logStatement[0].value)) {
logStatement = logStatement[0].value;
}
logStatement = logStatement.map((s: any) =>
Utils.filterObject(s, currentCommand.defaultProperties as string[]));
}
}
}
// display object as a list of key-value pairs
if (logStatement.length === 1) {
const obj: any = logStatement[0];
const propertyNames: string[] = [];
Object.getOwnPropertyNames(obj).forEach(p => {
propertyNames.push(p);
});
let longestPropertyLength: number = 0;
propertyNames.forEach(p => {
if (p.length > longestPropertyLength) {
longestPropertyLength = p.length;
}
});
const output: string[] = [];
propertyNames.sort().forEach(p => {
output.push(`${p.length < longestPropertyLength ? p + new Array(longestPropertyLength - p.length + 1).join(' ') : p}: ${Array.isArray(obj[p]) || typeof obj[p] === 'object' ? JSON.stringify(obj[p]) : obj[p]}`);
});
return output.join('\n') + '\n';
}
// display object as a table where each property is a column
else {
const Table = require('easy-table');
const t = new Table();
logStatement.forEach((r: any) => {
if (typeof r !== 'object') {
return;
}
Object.getOwnPropertyNames(r).forEach(p => {
t.cell(p, r[p]);
});
t.newRow();
});
return t.toString();
}
}
private static getFirstNonUndefinedArrayItem(arr: any[]): any {
for (let i: number = 0; i < arr.length; i++) {
const a: any = arr[i];
if (typeof a !== 'undefined') {
return a;
}
}
return undefined;
}
private printHelp(exitCode: number = 0): void {
const properties: any = {};
if (this.commandToExecute) {
properties.command = this.commandToExecute.name;
this.printCommandHelp();
}
else {
Cli.log();
Cli.log(`CLI for Microsoft 365 v${packageJSON.version}`);
Cli.log(`${packageJSON.description}`);
Cli.log();
properties.command = 'commandList';
this.printAvailableCommands();
}
appInsights.trackEvent({
name: 'help',
properties
});
appInsights.flush();
process.exit(exitCode);
}
private printCommandHelp(): void {
let helpFilePath = '';
let commandNameWords: string[] = [];
if (this.commandToExecute) {
commandNameWords = (this.commandToExecute.name).split(' ');
}
const pathChunks: string[] = [this.commandsFolder, '..', '..', 'docs', 'docs', 'cmd'];
if (commandNameWords.length === 1) {
pathChunks.push(`${commandNameWords[0]}.md`);
}
else {
if (commandNameWords.length === 2) {
pathChunks.push(commandNameWords[0], `${commandNameWords.join('-')}.md`);
}
else {
pathChunks.push(commandNameWords[0], commandNameWords[1], commandNameWords.slice(1).join('-') + '.md');
}
}
helpFilePath = path.join(...pathChunks);
if (fs.existsSync(helpFilePath)) {
Cli.log();
// because of prism, loading markshell slows down CLI a lot
// let's lazy-load it only when it's needed (help was requested)
const markshell: typeof Markshell = require('markshell');
const chalk: typeof Chalk = require('chalk');
const theme = markshell.getTheme();
const admonitionStyles = theme.admonitions.getStyles();
admonitionStyles.indent.beforeIndent = 0;
admonitionStyles.indent.titleIndent = 3;
admonitionStyles.indent.afterIndent = 0;
theme.admonitions.setStyles(admonitionStyles);
theme.indents.definitionList = 2;
theme.headline = chalk.white;
theme.inlineCode = chalk.cyan;
theme.sourceCodeTheme = 'solarizelight';
theme.includePath = path.join(this.commandsFolder, '..', '..', 'docs');
markshell.setTheme(theme);
Cli.log(markshell.toRawContent(helpFilePath));
}
}
private printAvailableCommands(): void {
// commands that match the current group
const commandsToPrint: { [commandName: string]: CommandInfo } = {};
// sub-commands in the current group
const commandGroupsToPrint: { [group: string]: number } = {};
// current command group, eg. 'spo', 'spo site'
let currentGroup: string = '';
const addToList = (commandName: string, command: CommandInfo): void => {
const pos: number = commandName.indexOf(' ', currentGroup.length + 1);
if (pos === -1) {
commandsToPrint[commandName] = command;
}
else {
const subCommandsGroup: string = commandName.substr(0, pos);
if (!commandGroupsToPrint[subCommandsGroup]) {
commandGroupsToPrint[subCommandsGroup] = 0;
}
commandGroupsToPrint[subCommandsGroup]++;
}
};
// get current command group
if (this.optionsFromArgs &&
this.optionsFromArgs.options &&
this.optionsFromArgs.options._ &&
this.optionsFromArgs.options._.length > 0) {
currentGroup = this.optionsFromArgs.options._.join(' ');
if (currentGroup) {
currentGroup += ' ';
}
}
const getCommandsForGroup = (): void => {
for (let i = 0; i < this.commands.length; i++) {
const command: CommandInfo = this.commands[i];
if (command.name.startsWith(currentGroup)) {
addToList(command.name, command);
}
if (command.aliases) {
for (let j = 0; j < command.aliases.length; j++) {
const alias: string = command.aliases[j];
if (alias.startsWith(currentGroup)) {
addToList(alias, command);
}
}
}
}
};
getCommandsForGroup();
if (Object.keys(commandsToPrint).length === 0 &&
Object.keys(commandGroupsToPrint).length === 0) {
// specified string didn't match any commands. Reset group and try again
currentGroup = '';
getCommandsForGroup();
}
const namesOfCommandsToPrint: string[] = Object.keys(commandsToPrint);
if (namesOfCommandsToPrint.length > 0) {
// determine the length of the longest command name to pad strings + ' [options]'
const maxLength: number = Math.max(...namesOfCommandsToPrint.map(s => s.length)) + 10;
Cli.log(`Commands:`);
Cli.log();
for (const commandName in commandsToPrint) {
Cli.log(` ${`${commandName} [options]`.padEnd(maxLength, ' ')} ${commandsToPrint[commandName].command.description}`);
}
}
const namesOfCommandGroupsToPrint: string[] = Object.keys(commandGroupsToPrint);
if (namesOfCommandGroupsToPrint.length > 0) {
if (namesOfCommandsToPrint.length > 0) {
Cli.log();
}
// determine the longest command group name to pad strings + ' *'
const maxLength: number = Math.max(...namesOfCommandGroupsToPrint.map(s => s.length)) + 2;
Cli.log(`Commands groups:`);
Cli.log();
// sort commands groups (because of aliased commands)
const sortedCommandGroupsToPrint = Object
.keys(commandGroupsToPrint)
.sort()
.reduce((object: { [group: string]: number }, key: string) => {
object[key] = commandGroupsToPrint[key];
return object;
}, {});
for (const commandGroup in sortedCommandGroupsToPrint) {
Cli.log(` ${`${commandGroup} *`.padEnd(maxLength, ' ')} ${commandGroupsToPrint[commandGroup]} command${commandGroupsToPrint[commandGroup] === 1 ? '' : 's'}`);
}
}
Cli.log();
}
private closeWithError(error: any, args: CommandArgs, showHelpIfEnabled: boolean = false): void {
const chalk: typeof Chalk = require('chalk');
let exitCode: number = 1;
let errorMessage: string = error instanceof CommandError ? error.message : error;
if (args.options.output === 'json' &&
!this.getSettingWithDefaultValue<boolean>(settingsNames.printErrorsAsPlainText, true)) {
errorMessage = JSON.stringify({ error: errorMessage });
}
else {
errorMessage = chalk.red(`Error: ${errorMessage}`);
}
if (error instanceof CommandError && error.code) {
exitCode = error.code;
}
Cli.error(errorMessage);
if (showHelpIfEnabled &&
this.getSettingWithDefaultValue<boolean>(settingsNames.showHelpOnFailure, showHelpIfEnabled)) {
this.printHelp(exitCode);
}
else {
process.exit(exitCode);
}
// will never be run. Required for testing where we're stubbing process.exit
/* c8 ignore next */
throw new Error();
/* c8 ignore next */
}
private static log(message?: any, ...optionalParams: any[]): void {
if (message) {
console.log(message, ...optionalParams);
}
else {
console.log();
}
}
private static error(message?: any, ...optionalParams: any[]): void {
const errorOutput: string = Cli.getInstance().getSettingWithDefaultValue(settingsNames.errorOutput, 'stderr');
if (errorOutput === 'stdout') {
console.log(message, ...optionalParams);
}
else {
console.error(message, ...optionalParams);
}
}
public static prompt(options: any, cb: (result: any) => void): void {
const inquirer: Inquirer = require('inquirer');
inquirer
.prompt(options)
.then(result => cb(result));
}
private static removeShortOptions(args: { options: minimist.ParsedArgs }): { options: minimist.ParsedArgs } {
const filteredArgs = JSON.parse(JSON.stringify(args));
const optionsToRemove: string[] = Object.getOwnPropertyNames(args.options)
.filter(option => option.length === 1 || option === '--');
optionsToRemove.forEach(option => delete filteredArgs.options[option]);
return filteredArgs;
}
private static loadOptionValuesFromFiles(args: { options: minimist.ParsedArgs }) {
const optionNames: string[] = Object.getOwnPropertyNames(args.options);
optionNames.forEach(option => {
const value = args.options[option];
if (!value ||
typeof value !== 'string' ||
!value.startsWith('@')) {
return;
}
const filePath: string = value.substr(1);
// if the file doesn't exist, leave as-is, if it exists replace with
// contents from the file
if (fs.existsSync(filePath)) {
args.options[option] = fs.readFileSync(filePath, 'utf-8');
}
});
}
}