Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 14 additions & 35 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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`);
Expand Down