-
Notifications
You must be signed in to change notification settings - Fork 175
/
Copy pathindex.ts
executable file
Β·374 lines (331 loc) Β· 9.11 KB
/
index.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
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
import {
getBooleanInput,
getInput,
getMultilineInput,
endGroup as originalEndGroup,
error as originalError,
info as originalInfo,
debug,
startGroup as originalStartGroup,
setFailed,
setOutput,
} from "@actions/core";
import { getExecOutput } from "@actions/exec";
import semverEq from "semver/functions/eq";
import { exec, execShell } from "./exec";
import { checkWorkingDirectory, semverCompare } from "./utils";
import { getPackageManager } from "./packageManagers";
const DEFAULT_WRANGLER_VERSION = "3.78.10";
/**
* A configuration object that contains all the inputs & immutable state for the action.
*/
const config = {
WRANGLER_VERSION: getInput("wranglerVersion") || DEFAULT_WRANGLER_VERSION,
didUserProvideWranglerVersion: Boolean(getInput("wranglerVersion")),
secrets: getMultilineInput("secrets"),
workingDirectory: checkWorkingDirectory(getInput("workingDirectory")),
CLOUDFLARE_API_TOKEN: getInput("apiToken"),
CLOUDFLARE_ACCOUNT_ID: getInput("accountId"),
ENVIRONMENT: getInput("environment"),
VARS: getMultilineInput("vars"),
COMMANDS: getMultilineInput("command"),
QUIET_MODE: getBooleanInput("quiet"),
PACKAGE_MANAGER: getInput("packageManager"),
} as const;
const packageManager = getPackageManager(config.PACKAGE_MANAGER, {
workingDirectory: config.workingDirectory,
});
function info(message: string, bypass?: boolean): void {
if (!config.QUIET_MODE || bypass) {
originalInfo(message);
}
}
function error(message: string, bypass?: boolean): void {
if (!config.QUIET_MODE || bypass) {
originalError(message);
}
}
function startGroup(name: string): void {
if (!config.QUIET_MODE) {
originalStartGroup(name);
}
}
function endGroup(): void {
if (!config.QUIET_MODE) {
originalEndGroup();
}
}
async function main() {
try {
authenticationSetup();
await installWrangler();
await execCommands(getMultilineInput("preCommands"), "pre");
await uploadSecrets();
await wranglerCommands();
await execCommands(getMultilineInput("postCommands"), "post");
info("π Wrangler Action completed", true);
} catch (err: unknown) {
err instanceof Error && error(err.message);
setFailed("π¨ Action failed");
}
}
async function installWrangler() {
if (config["WRANGLER_VERSION"].startsWith("1")) {
throw new Error(
`Wrangler v1 is no longer supported by this action. Please use major version 2 or greater`,
);
}
startGroup("π Checking for existing Wrangler installation");
let installedVersion = "";
let installedVersionSatisfiesRequirement = false;
try {
const { stdout } = await getExecOutput(
// We want to simply invoke wrangler to check if it's installed, but don't want to auto-install it at this stage
packageManager.execNoInstall,
["wrangler", "--version"],
{
cwd: config["workingDirectory"],
silent: config.QUIET_MODE,
},
);
// There are two possible outputs from `wrangler --version`:
// ` β
οΈ wrangler 3.48.0 (update available 3.53.1)`
// and
// `3.48.0`
const versionMatch =
stdout.match(/wrangler (\d+\.\d+\.\d+)/) ??
stdout.match(/^(\d+\.\d+\.\d+)/m);
if (versionMatch) {
installedVersion = versionMatch[1];
}
if (config.didUserProvideWranglerVersion) {
installedVersionSatisfiesRequirement = semverEq(
installedVersion,
config["WRANGLER_VERSION"],
);
}
if (!config.didUserProvideWranglerVersion && installedVersion) {
info(
`β
No wrangler version specified, using pre-installed wrangler version ${installedVersion}`,
true,
);
endGroup();
return;
}
if (
config.didUserProvideWranglerVersion &&
installedVersionSatisfiesRequirement
) {
info(`β
Using Wrangler ${installedVersion}`, true);
endGroup();
return;
}
info(
"β οΈ Wrangler not found or version is incompatible. Installing...",
true,
);
} catch (error) {
debug(`Error checking Wrangler version: ${error}`);
info(
"β οΈ Wrangler not found or version is incompatible. Installing...",
true,
);
} finally {
endGroup();
}
startGroup("π₯ Installing Wrangler");
try {
await exec(
packageManager.install,
[`wrangler@${config["WRANGLER_VERSION"]}`],
{
cwd: config["workingDirectory"],
silent: config["QUIET_MODE"],
},
);
info(`β
Wrangler installed`, true);
} finally {
endGroup();
}
}
function authenticationSetup() {
process.env.CLOUDFLARE_API_TOKEN = config["CLOUDFLARE_API_TOKEN"];
process.env.CLOUDFLARE_ACCOUNT_ID = config["CLOUDFLARE_ACCOUNT_ID"];
}
async function execCommands(commands: string[], cmdType: string) {
if (!commands.length) {
return;
}
startGroup(`π Running ${cmdType}Commands`);
try {
for (const command of commands) {
const cmd = command.startsWith("wrangler")
? `${packageManager.exec} ${command}`
: command;
await execShell(cmd, {
cwd: config["workingDirectory"],
silent: config["QUIET_MODE"],
});
}
} finally {
endGroup();
}
}
function getSecret(secret: string) {
if (!secret) {
throw new Error("Secret name cannot be blank.");
}
const value = process.env[secret];
if (!value) {
throw new Error(`Value for secret ${secret} not found in environment.`);
}
return value;
}
function getEnvVar(envVar: string) {
if (!envVar) {
throw new Error("Var name cannot be blank.");
}
const value = process.env[envVar];
if (!value) {
throw new Error(`Value for var ${envVar} not found in environment.`);
}
return value;
}
async function legacyUploadSecrets(
secrets: string[],
environment?: string,
workingDirectory?: string,
) {
for (const secret of secrets) {
const args = ["wrangler", "secret", "put", secret];
if (environment) {
args.push("--env", environment);
}
await exec(packageManager.exec, args, {
cwd: workingDirectory,
silent: config["QUIET_MODE"],
input: Buffer.from(getSecret(secret)),
});
}
}
async function uploadSecrets() {
const secrets: string[] = config["secrets"];
const environment = config["ENVIRONMENT"];
const workingDirectory = config["workingDirectory"];
if (!secrets.length) {
return;
}
startGroup("π Uploading secrets...");
try {
if (semverCompare(config["WRANGLER_VERSION"], "3.4.0")) {
return legacyUploadSecrets(secrets, environment, workingDirectory);
}
const args = ["wrangler", "secret:bulk"];
if (environment) {
args.push("--env", environment);
}
await exec(packageManager.exec, args, {
cwd: workingDirectory,
silent: config["QUIET_MODE"],
input: Buffer.from(
JSON.stringify(
Object.fromEntries(
secrets.map((secret) => [secret, getSecret(secret)]),
),
),
),
});
} catch (err: unknown) {
if (err instanceof Error) {
error(err.message);
err.stack && debug(err.stack);
}
throw new Error(`Failed to upload secrets.`);
} finally {
endGroup();
}
}
async function wranglerCommands() {
startGroup("π Running Wrangler Commands");
try {
const commands = config["COMMANDS"];
const environment = config["ENVIRONMENT"];
if (!commands.length) {
const wranglerVersion = config["WRANGLER_VERSION"];
const deployCommand = semverCompare("2.20.0", wranglerVersion)
? "deploy"
: "publish";
commands.push(deployCommand);
}
for (let command of commands) {
const args = [];
if (environment && !command.includes("--env")) {
args.push("--env", environment);
}
if (
config["VARS"].length &&
(command.startsWith("deploy") || command.startsWith("publish")) &&
!command.includes("--var")
) {
args.push("--var");
for (const v of config["VARS"]) {
args.push(`${v}:${getEnvVar(v)}`);
}
}
// Used for saving the wrangler output
let stdOut = "";
let stdErr = "";
// Construct the options for the exec command
const options = {
cwd: config["workingDirectory"],
silent: config["QUIET_MODE"],
listeners: {
stdout: (data: Buffer) => {
stdOut += data.toString();
},
stderr: (data: Buffer) => {
stdErr += data.toString();
},
},
};
// Execute the wrangler command
await exec(`${packageManager.exec} wrangler ${command}`, args, options);
// Set the outputs for the command
setOutput("command-output", stdOut);
setOutput("command-stderr", stdErr);
// Check if this command is a workers or pages deployment
if (
command.startsWith("deploy") ||
command.startsWith("publish") ||
command.startsWith("pages publish") ||
command.startsWith("pages deploy")
) {
// If this is a workers or pages deployment, try to extract the deployment URL
let deploymentUrl = "";
const deploymentUrlMatch = stdOut.match(/https?:\/\/[a-zA-Z0-9-./]+/);
if (deploymentUrlMatch && deploymentUrlMatch[0]) {
deploymentUrl = deploymentUrlMatch[0].trim();
setOutput("deployment-url", deploymentUrl);
}
// And also try to extract the alias URL (since wrangler@3.78.0)
const aliasUrlMatch = stdOut.match(
/alias URL: (https?:\/\/[a-zA-Z0-9-./]+)/,
);
if (aliasUrlMatch && aliasUrlMatch.length == 2 && aliasUrlMatch[1]) {
const aliasUrl = aliasUrlMatch[1].trim();
setOutput("deployment-alias-url", aliasUrl);
}
}
}
} finally {
endGroup();
}
}
main();
export {
authenticationSetup,
execCommands,
installWrangler,
uploadSecrets,
wranglerCommands,
};