-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexpect-env.js
276 lines (248 loc) · 9.31 KB
/
expect-env.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
'use strict';
/* eslint-disable no-console */
const debug = require('debug')(`${require('./package.json').name}:expect-env`);
const DEFAULT_VALUE_REGEX = [/^.*$/, /.*/];
class IllegalEnvironmentError extends Error {}
module.exports = {
/**
* This function accepts a single object parameter with a list of `rules` used
* to verify `env`. If `env` is not defined, `process.env` is used instead. If
* `rules` is not defined, the "rules" defined under the "expect-env" key in
* ./package.json are used instead.
*
* Below, "name" is the name of an environment variable and "value" is its
* expected value.
*
* Each rule can be one of:
*
* (1) A simple STRING variable "name" interpreted as RegExp(`^${STRING}$`)
*
* (2) An OBJECT where "name" and "value" are both regex STRINGs; "required"
* is optional and defaults to `true`; and "errorMessage" is optional:
*
* {
* "name": "^(MY_)?VARIABLE_NAME$",
* "value": "^(true|false)$",
* "required": true, // ◄ optional
* "errorMessage": "some custom error message" // ◄ optional
* }
*
* (3) An OBJECT where "operation" is either "xor", "or", "and", or "not";
* "variables" is an array where each element is (1) or (2) (without
* "required" or "errorMessage"); "required" is optional and defaults to
* `true`; and "errorMessage" is optional:
*
* {
* "operation": "xor",
* "variables": ["^MY_V_1$", { name: "^MY_V_2$", value: "^.*$" }],
* "required": false, // ◄ optional
* "errorMessage": "some custom error message" // ◄ optional
* }
*
* When "operation" is "xor", exactly one of the elements in "variables" must
* match the environment. When it's "or", at least one of the elements must
* match (this is the default). When it's "and", all of the elements must
* match. When it's "not", exactly zero elements must match. When "required"
* is `false` and "operation" is something other than "not", rules matching
* non-existent variable names will be skipped (others will still be
* verified).
*
* With both (2) and (3), "errorMessage" is output to the console if the rule
* fails verification or was not found in `env` but "required" is `true`.
*
* When `isCli=false`, this function will return an array of objects each with
* the shape of (3) representing all the rules that failed to match against
* the current environment. An empty array is returned if all rules matched
* and verification succeeded. When `isCli=true` (the default), this function
* will output errors to the console and non-zero exit if verification fails.
*/
verifyEnvironment(options) {
let { rules } = options || {};
const { env: outsideEnv, isCli } = {
...options,
env: undefined,
isCli: true
};
let fromPkg = false;
let errorMessage = null;
const normalize = (rule) => {
let normalizedRule;
const makeErrorMessage = (reason) => `missing dep: ${reason}`;
debug('::normalize (not normalized): %O', rule);
if (typeof rule === 'string' || rule instanceof RegExp) {
if (typeof rule === 'string') {
rule = rule.startsWith('^') ? rule.slice(1) : rule;
rule = rule.startsWith('$') ? rule.slice(0, -1) : rule;
rule = new RegExp(`^${rule}$`);
}
normalizedRule = {
operation: 'or',
variables: [{ name: rule, value: DEFAULT_VALUE_REGEX[0] }],
required: true,
errorMessage: String(
makeErrorMessage(
`must define environment variable with name matching regex ${rule}`
)
)
};
} else if (typeof rule.name === 'string' || rule.name instanceof RegExp) {
rule.name = rule.name instanceof RegExp ? rule.name : new RegExp(rule.name);
rule.value =
typeof rule.value === 'string'
? new RegExp(rule.value)
: rule.value instanceof RegExp
? rule.value
: DEFAULT_VALUE_REGEX[0];
normalizedRule = {
operation: 'or',
variables: [{ name: rule.name, value: rule.value }],
required: rule.required === undefined || !!rule.required,
errorMessage: String(
rule.errorMessage ||
makeErrorMessage(
`must define environment variable with name matching regex ` +
`${rule.name}${
DEFAULT_VALUE_REGEX.map(String).includes(rule.value.toString())
? ''
: ' and value matching regex ' + rule.value
}`
)
)
};
} else if (
['and', 'or', 'xor', 'not'].includes(rule.operation) &&
Array.isArray(rule.variables)
) {
const variables = rule.variables.map((r) => normalize(r).variables[0]);
const not = rule.operation === 'not';
const opString = not ? ' ' : `${rule.operation} `;
const makeSubstr = (name, value) =>
`name ${not ? 'NOT ' : ''}matching regex ${name}` +
(DEFAULT_VALUE_REGEX.map(String).includes((value || '').toString())
? ''
: ` and value ${not ? 'NOT ' : ''}matching regex ${value}`);
normalizedRule = {
operation: rule.operation,
variables,
required: rule.required === undefined || !!rule.required,
errorMessage: String(
rule.errorMessage ||
makeErrorMessage(
`must define ${
not ? 'ALL environment variables' : 'environment variable'
} with` +
(variables.length > 1 ? ':\n' : ' ') +
variables
.slice(1)
// eslint-disable-next-line unicorn/no-array-reduce
.reduce(
(str, { name, value }) =>
`${str}\n${opString}${makeSubstr(name, value)}`,
`${' '.repeat(opString.length)}${makeSubstr(
variables[0].name,
variables[0].value
)}`
)
)
)
};
} else {
debug('::normalize BAD RULE ENCOUNTERED: %O', rule);
throw new IllegalEnvironmentError(
`bad rule encountered${
fromPkg ? ' in ./package.json "expect-env"' : ''
}: ${JSON.stringify(rule, undefined, 2)}`
);
}
debug('::normalize (normalized): %O', normalizedRule);
return normalizedRule;
};
if (!rules) {
try {
({
'expect-env': { rules, errorMessage }
} = require('./package.json'));
fromPkg = true;
} catch {
/* ignored */
}
}
debug('rules: %O', rules);
debug('errorMessage: %O', errorMessage);
if (rules === undefined) return [];
if (!Array.isArray(rules)) {
throw new IllegalEnvironmentError(
fromPkg
? '"expect-env" key must have an array value in package.json'
: '`rules` must be an array'
);
}
const env = outsideEnv || process.env;
const envVariables = Object.keys(env);
const violations = [];
let verificationSucceeded = true;
rules
.map((rule) => normalize(rule))
.forEach((rule) => {
let succeeded = null;
for (const { name, value } of rule.variables) {
let matchedAtLeastOneVariable = false;
// ? Attempt to match variable names and values vs name and value
const matched = envVariables.some((v) => {
const matchesName = name.test(v);
matchedAtLeastOneVariable = matchedAtLeastOneVariable || matchesName;
return matchesName && value.test(env[v]);
});
// ? If it's not required and not in env, skip evaluation
if (!rule.required && !matchedAtLeastOneVariable) {
succeeded = true;
continue;
}
if (rule.operation === 'or') {
if (matched) {
succeeded = true;
break;
}
} else if (rule.operation === 'and') {
if (matched) succeeded = true;
else {
succeeded = false;
break;
}
} else if (rule.operation === 'not') {
if (!matched) succeeded = true;
else {
succeeded = false;
break;
}
} else if (rule.operation === 'xor') {
if (succeeded === null) succeeded = !matched ? null : true;
else if (succeeded && matched) {
succeeded = false;
break;
}
} else {
throw new IllegalEnvironmentError(
`unrecognized operation "${rule.operation}"`
);
}
}
if (!succeeded)
isCli ? console.error(rule.errorMessage) : violations.push(rule);
verificationSucceeded = verificationSucceeded && succeeded;
});
if (!verificationSucceeded && isCli)
throw new IllegalEnvironmentError(
errorMessage || 'environment verification failed'
);
debug('violated rules: %O', violations);
return violations;
}
};
try {
!module.parent && module.exports.verifyEnvironment();
} catch (error) {
console.error(error);
// eslint-disable-next-line unicorn/no-process-exit
process.exit(1);
}