Skip to content

Instantly share code, notes, and snippets.

@paulgalow
Last active January 16, 2022 17:28
Show Gist options
  • Save paulgalow/4e076577dd5f22cbdf7e16a71ad48255 to your computer and use it in GitHub Desktop.
Save paulgalow/4e076577dd5f22cbdf7e16a71ad48255 to your computer and use it in GitHub Desktop.

Revisions

  1. paulgalow revised this gist Jan 16, 2022. No changes.
  2. paulgalow created this gist Jan 15, 2022.
    51 changes: 51 additions & 0 deletions processManifest.js
    Original 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())
    );
    }