Last active
January 16, 2022 17:28
-
-
Save paulgalow/4e076577dd5f22cbdf7e16a71ad48255 to your computer and use it in GitHub Desktop.
Revisions
-
paulgalow revised this gist
Jan 16, 2022 . No changes.There are no files selected for viewing
-
paulgalow created this gist
Jan 15, 2022 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,51 @@ const dotenv = require("dotenv"); const fs = require("fs").promises; const path = require("path"); module.exports = async function processManifest(manifestData) { const stageName = Object.keys(manifestData)[0]; const { outputs } = manifestData[stageName]; const envArray = outputs .map((obj) => Object.values(obj)) .map((arr) => [camelToUpperSnakeCase(arr[0]), arr[1]]); const envObject = Object.fromEntries(envArray); const dotEnvFile = path.resolve(".env"); await updateDotEnv(dotEnvFile, envObject); }; /* Utils, typically this would be a package includes from NPM */ async function updateDotEnv(filePath, env) { // Merge with existing values try { const existing = dotenv.parse(await fs.readFile(filePath, "utf-8")); env = { ...existing, ...env }; } catch (err) { if (err.code !== "ENOENT") { throw err; } } const contents = Object.keys(env) .map((key) => format(key, env[key])) .join("\n"); await fs.writeFile(filePath, contents); return env; } function escapeNewlines(str) { return str.replace(/\n/g, "\\n"); } function format(key, value) { return `${key}=${escapeNewlines(value)}`; } function camelToUpperSnakeCase(str) { return [...str].reduce((previous, current) => current === current.toUpperCase() ? (previous += "_" + current) : (previous += current.toUpperCase()) ); }