Refactor error handling to stop execution on errors. Fixes #160.

This commit is contained in:
Cina Saffary 2023-08-29 16:36:50 -05:00
parent b076e889fb
commit e5251df521
2 changed files with 88 additions and 85 deletions

View file

@ -0,0 +1,5 @@
---
"wrangler-action": patch
---
Refactored error handling to stop execution when action fails. Previously, the action would continue executing to completion if one of the steps encountered an error. Fixes #160.

View file

@ -80,13 +80,18 @@ function semverCompare(version1: string, version2: string) {
} }
async function main() { async function main() {
installWrangler(); try {
authenticationSetup(); installWrangler();
await execCommands(getMultilineInput("preCommands"), "pre"); authenticationSetup();
await uploadSecrets(); await execCommands(getMultilineInput("preCommands"), "pre");
await wranglerCommands(); await uploadSecrets();
await execCommands(getMultilineInput("postCommands"), "post"); await wranglerCommands();
info("🏁 Wrangler Action completed", true); await execCommands(getMultilineInput("postCommands"), "post");
info("🏁 Wrangler Action completed", true);
} catch (err) {
error(`${err}`);
setFailed("🚨 Action failed");
}
} }
async function runProcess( async function runProcess(
@ -103,7 +108,7 @@ async function runProcess(
} catch (err: any) { } catch (err: any) {
err.stdout && info(err.stdout.toString()); err.stdout && info(err.stdout.toString());
err.stderr && error(err.stderr.toString(), true); err.stderr && error(err.stderr.toString(), true);
throw err; throw new Error(`\`${command}\` returned non-zero exit code.`);
} }
} }
@ -113,19 +118,19 @@ function checkWorkingDirectory(workingDirectory = ".") {
if (existsSync(normalizedPath)) { if (existsSync(normalizedPath)) {
return normalizedPath; return normalizedPath;
} else { } else {
setFailed(`🚨 Directory ${workingDirectory} does not exist.`); throw new Error(`Directory ${workingDirectory} does not exist.`);
} }
} catch (error) { } catch (error) {
setFailed( throw new Error(
`🚨 While checking/creating directory ${workingDirectory} received ${error}`, `While checking/creating directory ${workingDirectory} received ${error}`,
); );
} }
} }
function installWrangler() { function installWrangler() {
if (config["WRANGLER_VERSION"].startsWith("1")) { if (config["WRANGLER_VERSION"].startsWith("1")) {
setFailed( throw new Error(
`🚨 Wrangler v1 is no longer supported by this action. Please use major version 2 or greater`, `Wrangler v1 is no longer supported by this action. Please use major version 2 or greater`,
); );
} }
startGroup("📥 Installing Wrangler"); startGroup("📥 Installing Wrangler");
@ -145,27 +150,26 @@ async function execCommands(commands: string[], cmdType: string) {
if (!commands.length) { if (!commands.length) {
return; return;
} }
startGroup(`🚀 Running ${cmdType}Commands`); startGroup(`🚀 Running ${cmdType}Commands`);
try {
const arrPromises = commands.map(async (command) => {
const cmd = command.startsWith("wrangler")
? `${getNpxCmd()} ${command}`
: command;
const arrPromises = commands.map(async (command) => { info(`🚀 Executing command: ${cmd}`);
const cmd = command.startsWith("wrangler")
? `${getNpxCmd()} ${command}`
: command;
info(`🚀 Executing command: ${cmd}`); return await runProcess(cmd, {
cwd: config["workingDirectory"],
return await runProcess(cmd, { env: process.env,
cwd: config["workingDirectory"], });
env: process.env,
}); });
});
await Promise.all(arrPromises).catch((result) => { await Promise.all(arrPromises);
result.stdout && info(result.stdout.toString()); } finally {
result.stderr && error(result.stderr.toString(), true); endGroup();
setFailed(`🚨 ${cmdType}Commands failed`); }
});
endGroup();
} }
/** /**
@ -173,12 +177,12 @@ async function execCommands(commands: string[], cmdType: string) {
*/ */
function getSecret(secret: string) { function getSecret(secret: string) {
if (!secret) { if (!secret) {
setFailed("No secret provided"); throw new Error("Secret name cannot be blank.");
} }
const value = process.env[secret]; const value = process.env[secret];
if (!value) { if (!value) {
setFailed(`Secret ${secret} not found`); throw new Error(`Value for secret ${secret} not found.`);
} }
return value; return value;
@ -189,26 +193,22 @@ async function legacyUploadSecrets(
environment?: string, environment?: string,
workingDirectory?: string, workingDirectory?: string,
) { ) {
try { const arrPromises = secrets
const arrPromises = secrets .map((secret) => {
.map((secret) => { const command = `echo ${getSecret(
const command = `echo ${getSecret( secret,
secret, )} | ${getNpxCmd()} wrangler secret put ${secret}`;
)} | ${getNpxCmd()} wrangler secret put ${secret}`; return environment ? command.concat(` --env ${environment}`) : command;
return environment ? command.concat(` --env ${environment}`) : command; })
}) .map(
.map( async (command) =>
async (command) => await execAsync(command, {
await execAsync(command, { cwd: workingDirectory,
cwd: workingDirectory, env: process.env,
env: process.env, }),
}), );
);
await Promise.all(arrPromises); await Promise.all(arrPromises);
} catch {
setFailed(`🚨 Error uploading secrets`);
}
} }
async function uploadSecrets() { async function uploadSecrets() {
@ -245,8 +245,8 @@ async function uploadSecrets() {
stdio: "ignore", stdio: "ignore",
}); });
info(`✅ Uploaded secrets`); info(`✅ Uploaded secrets`);
} catch { } catch (err) {
setFailed(`🚨 Error uploading secrets`); throw new Error(`Error uploading secrets: ${err}`);
} finally { } finally {
endGroup(); endGroup();
} }
@ -258,7 +258,7 @@ function getVarArgs() {
if (process.env[envVar] && process.env[envVar]?.length !== 0) { if (process.env[envVar] && process.env[envVar]?.length !== 0) {
return `${envVar}:${process.env[envVar]!}`; return `${envVar}:${process.env[envVar]!}`;
} else { } else {
setFailed(`🚨 ${envVar} not found in variables.`); throw new Error(`Value for var ${envVar} not found in environment.`);
} }
}); });
@ -267,47 +267,45 @@ function getVarArgs() {
async function wranglerCommands() { async function wranglerCommands() {
startGroup("🚀 Running Wrangler Commands"); startGroup("🚀 Running Wrangler Commands");
const commands = config["COMMANDS"]; try {
const environment = config["ENVIRONMENT"]; const commands = config["COMMANDS"];
const environment = config["ENVIRONMENT"];
if (!commands.length) { if (!commands.length) {
const wranglerVersion = config["WRANGLER_VERSION"]; const wranglerVersion = config["WRANGLER_VERSION"];
const deployCommand = semverCompare("2.20.0", wranglerVersion) const deployCommand = semverCompare("2.20.0", wranglerVersion)
? "deploy" ? "deploy"
: "publish"; : "publish";
commands.push(deployCommand); commands.push(deployCommand);
}
const arrPromises = commands.map(async (command) => {
if (environment.length > 0 && !command.includes(`--env`)) {
command = command.concat(` --env ${environment}`);
} }
const cmd = `${getNpxCmd()} wrangler ${command} ${ const arrPromises = commands.map(async (command) => {
(command.startsWith("deploy") || command.startsWith("publish")) && if (environment.length > 0 && !command.includes(`--env`)) {
!command.includes(`--var`) command = command.concat(` --env ${environment}`);
? getVarArgs() }
: ""
}`.trim();
info(`🚀 Executing command: ${cmd}`); const cmd = `${getNpxCmd()} wrangler ${command} ${
(command.startsWith("deploy") || command.startsWith("publish")) &&
!command.includes(`--var`)
? getVarArgs()
: ""
}`.trim();
return await runProcess(cmd, { info(`🚀 Executing command: ${cmd}`);
cwd: config["workingDirectory"],
env: process.env, return await runProcess(cmd, {
cwd: config["workingDirectory"],
env: process.env,
});
}); });
});
await Promise.all(arrPromises).catch((result) => { await Promise.all(arrPromises);
result.stdout && info(result.stdout.toString()); } finally {
result.stderr && error(result.stderr.toString()); endGroup();
setFailed(`🚨 Command failed`); }
});
endGroup();
} }
main().catch(() => setFailed("🚨 Action failed")); main();
export { export {
wranglerCommands, wranglerCommands,