/
modes.ts
87 lines (68 loc) · 1.93 KB
/
modes.ts
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
import * as abbrev from 'abbrev';
import { UnsupportedOptionCombinationError, CustomError } from '../lib/errors';
interface ModeData {
allowedCommands: Array<string>;
config: (args) => [];
}
const modes: Record<string, ModeData> = {
container: {
allowedCommands: ['test', 'monitor'],
config: (args): [] => {
args['docker'] = true;
args['experimental'] = true;
return args;
},
},
iac: {
allowedCommands: ['test'],
config: (args): [] => {
args['iac'] = true;
return args;
},
},
};
export function parseMode(mode: string, args): string {
if (isValidMode(mode)) {
const command: string = args._[0];
if (isValidCommand(mode, command)) {
configArgs(mode, args);
mode = args._.shift();
}
}
return mode;
}
export function modeValidation(args: object) {
const mode = args['command'];
const commands: Array<string> = args['options']._;
if (isValidMode(mode) && commands.length <= 1) {
const allowed = modes[mode].allowedCommands
.join(', ')
.replace(/, ([^,]*)$/, ' or $1');
const message = `use snyk ${mode} with ${allowed}`;
throw new CustomError(message);
}
const command = commands[0];
if (isValidMode(mode) && !isValidCommand(mode, command)) {
const notSupported = [mode, command];
throw new UnsupportedOptionCombinationError(notSupported);
}
}
export function displayModeHelp(mode: string, args) {
if (isValidMode(mode)) {
const command: string = args._[0];
if (!isValidCommand(mode, command) || args['help']) {
args['help'] = mode;
}
}
return mode;
}
function isValidMode(mode: string): boolean {
return Object.keys(modes).includes(mode);
}
function isValidCommand(mode: string, command: string): boolean {
const aliases = abbrev(modes[mode].allowedCommands);
return Object.keys(aliases).includes(command);
}
function configArgs(mode: string, args): [] {
return modes[mode].config(args);
}