-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
99 lines (82 loc) · 2.61 KB
/
index.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
/*! Copyright 2023 Ayogo Health Inc. */
import { spawnSync } from "node:child_process";
const GITHUB_API_VERSION = "2022-11-28";
function getEnvironments(repoName) {
const [owner, repo] = repoName.split("/");
const result = spawnSync("gh", [
"api",
"-H", `"Accept: application/vnd.github+json"`,
"-H", `"X-GitHub-Api-Version: ${GITHUB_API_VERSION}"`,
`/repos/${owner}/${repo}/environments`
], { shell: true });
if (result.status === 0) {
return JSON.parse(result.stdout.toString()).environments.map((e) => e.name);
} else {
throw new Error(result.stderr.toString());
}
}
function createEnvironment(repoName, envName) {
const [owner, repo] = repoName.split("/");
const result = spawnSync("gh", [
"api",
"-H", `"Accept: application/vnd.github+json"`,
"-H", `"X-GitHub-Api-Version: ${GITHUB_API_VERSION}"`,
"-X", "PUT",
`/repos/${owner}/${repo}/environments/${envName}`
], { shell: true });
if (result.status === 0) {
console.log(`🟩 Created ${envName}...`);
} else {
throw new Error(result.stderr.toString());
}
}
function createVariable(repoName, envName, variableName, variableValue) {
const result = spawnSync("gh", [
"variable", "set",
"-e", envName,
"-R", repoName,
"-b", `"${variableValue}"`,
variableName
], { shell: true });
if (result.status === 0) {
console.log(` ▫️ Set variable ${variableName}`);
} else {
throw new Error(result.stderr.toString());
}
}
function createSecret(repoName, envName, variableName, variableValue) {
const result = spawnSync("gh", [
"secret", "set",
"-a", "actions",
"-e", envName,
"-R", repoName,
"-b", `"${variableValue}"`,
variableName
], { shell: true });
if (result.status === 0) {
console.log(` ▫️ Set secret ${variableName}`);
} else {
throw new Error(result.stderr.toString());
}
}
export async function provisionEnvironments(repoName, config) {
const existingEnvs = await getEnvironments(repoName);
Object.keys(config.environments).forEach((envName) => {
if (!existingEnvs.includes(envName)) {
createEnvironment(repoName, envName);
} else {
console.log(`🔹 Populating ${envName}...`);
}
const environment = config.environments[envName];
if (environment.variables?.length) {
environment.variables.forEach((variable) => {
createVariable(repoName, envName, variable.name, variable.value);
});
}
if (environment.secrets?.length) {
environment.secrets.forEach((secret) => {
createSecret(repoName, envName, secret.name, secret.value);
});
}
});
}