generated from pabio/github-actions-starter
-
Notifications
You must be signed in to change notification settings - Fork 131
/
environment.ts
59 lines (49 loc) · 1.99 KB
/
environment.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
import {
RANDOM_MAX_DEFAULT,
RANDOM_MIN_DEFAULT,
DYNAMIC_RANDOM_NUMBER,
DYNAMIC_ALPHANUMERIC_STRING,
DYNAMIC_STRING_LENGTH_DEFAULT
} from "./constants";
export const replaceEnvironmentVariables = (str: string) => {
Object.keys(process.env).forEach((key) => {
str = str.replace(`$${key}`, process.env[key] || `$${key}`);
});
const SECRETS_CONTEXT = process.env.SECRETS_CONTEXT || "{}";
const allSecrets: Record<string, string> = JSON.parse(SECRETS_CONTEXT);
const secrets: Record<string, any> = { ...JSON.parse(JSON.stringify(process.env)), allSecrets };
Object.keys(secrets).forEach((key) => {
str = str.replace(`$${key}`, secrets[key] || `$${key}`);
});
str = substituteRandomNumbers(str);
str = substituteDynamicAlphanumericString(str);
return str;
};
const substituteRandomNumbers = (str: string) => {
if (str.includes(DYNAMIC_RANDOM_NUMBER)) {
const min = parseInt(process.env.RANDOM_MIN || RANDOM_MIN_DEFAULT);
const max = parseInt(process.env.RANDOM_MAX || RANDOM_MAX_DEFAULT);
str = str.replaceAll(DYNAMIC_RANDOM_NUMBER, () => getRandomNumber(min, max).toString());
}
return str;
}
const substituteDynamicAlphanumericString = (str: string) => {
if (str.includes(DYNAMIC_ALPHANUMERIC_STRING)) {
const length = parseInt(process.env.DYNAMIC_STRING_LENGTH || DYNAMIC_STRING_LENGTH_DEFAULT);
str = str.replaceAll(DYNAMIC_ALPHANUMERIC_STRING, () => getRandomAlphanumericString(length));
}
return str;
};
/** Return a random integer N such that min <= N <= max */
const getRandomNumber = (min: number, max: number) =>
Math.floor(Math.random() * (max - min + 1)) + min;
/** Return a random alphanumeric string of given length */
const getRandomAlphanumericString = (length: number) => {
const charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
let result = "";
for (let i = 0; i < length; i++) {
const randomIndex = Math.floor(Math.random() * charset.length);
result += charset[randomIndex];
}
return result;
};