diff --git a/src/index.js b/src/index.js index f6d1e99..c35391b 100644 --- a/src/index.js +++ b/src/index.js @@ -1,5 +1,7 @@ -const { exec } = require("child_process"); const fs = require("fs"); +const util = require("util") + +const pWriteFile = util.promisify(fs.writeFile) /** * Overrides an ENV var with a value if it exists @@ -8,52 +10,29 @@ const fs = require("fs"); * @param {*} mode the mode to use (prefix or suffix) */ function setEnvWithValue(key, contextOrBranch, mode) { - let foundOne = false; - let found; - - if (mode === "prefix") { - const prefixedEnvVar = `${contextOrBranch}_${key}`; - - if (process.env[prefixedEnvVar]) { - console.log(`Setting ${key} to the value from ${prefixedEnvVar}.`); - process.env[key] = process.env[prefixedEnvVar]; - found = `${key}=${process.env[prefixedEnvVar]}`; - } - } else { - const suffixedEnvVar = `${key}_${contextOrBranch}`; + const envVar = mode === 'prefix' ? `${contextOrBranch}_${key}` : `${key}_${contextOrBranch}`; - if (process.env[suffixedEnvVar]) { - console.log(`Setting ${key} to the value from ${suffixedEnvVar}.`); - process.env[key] = process.env[suffixedEnvVar]; - found = `${key}=${process.env[suffixedEnvVar]}`; - } + if (!process.env[envVar]) { + return; } - return found; + console.log(`Setting ${key} to the value from ${envVar}.`); + process.env[key] = process.env[envVar]; + return `${key}=${process.env[envVar]}\n`; } module.exports = { - onPreBuild: ({ inputs }) => { + onPreBuild: async ({ inputs }) => { const context = `${process.env.CONTEXT}`.toUpperCase().replace(/-/g, "_"); const branch = `${process.env.BRANCH}`.toUpperCase().replace(/-/g, "_"); - const replaced = []; - - Object.keys(process.env).forEach((key) => { - const foundContext = setEnvWithValue(key, context, inputs.mode); - const foundBranch = setEnvWithValue(key, branch, inputs.mode); - if (foundContext) replaced.push(foundContext); - if (foundBranch) replaced.push(foundBranch); - }); + const replaced = [].concat(...Object.keys(process.env) + .map((key) => [setEnvWithValue(key, context, inputs.mode), setEnvWithValue(key, branch, inputs.mode)]) + ).filter(Boolean) if (replaced.length) { // Write an env file so we can source it during build - const file = fs.createWriteStream(".env"); - replaced.forEach(function (v) { - file.write(`${v}\n`); - }); - file.end(); - + await pWriteFile(".env", replaced.join("")) console.log(`Replaced ${replaced.length} ENVs and wrote .env file`); } else { console.log(`Nothing found... keeping default ENVs`);