UNPKG

2.05 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.objectToShellExport = exports.json2env = void 0;
4const fs = require("fs-extra");
5const colors_1 = require("../colors");
6const JSON2ENV_OPT_DEF = {
7 saveEnvFile: true,
8 bashEnv: true,
9 fail: true,
10};
11function json2env(opt) {
12 const { jsonPath, prefix, saveEnvFile, bashEnv, fail, debug, silent } = {
13 ...JSON2ENV_OPT_DEF,
14 ...opt,
15 };
16 if (!fs.pathExistsSync(jsonPath)) {
17 if (fail) {
18 throw new Error(`Path doesn't exist: ${jsonPath}`);
19 }
20 if (!silent) {
21 console.log(`json2env input file doesn't exist, skipping without error (${jsonPath})`);
22 }
23 if (bashEnv) {
24 appendBashEnv('');
25 }
26 return;
27 }
28 // read file
29 const json = fs.readJsonSync(jsonPath);
30 const exportStr = objectToShellExport(json, prefix);
31 if (debug) {
32 console.log(json, exportStr);
33 }
34 if (saveEnvFile) {
35 const shPath = `${jsonPath}.sh`;
36 fs.writeFileSync(shPath, exportStr);
37 if (!silent) {
38 console.log(`json2env created ${colors_1.dimGrey(shPath)}:`);
39 console.log(exportStr);
40 }
41 }
42 if (bashEnv) {
43 appendBashEnv(exportStr);
44 }
45}
46exports.json2env = json2env;
47function appendBashEnv(exportStr) {
48 const { BASH_ENV } = process.env;
49 if (BASH_ENV) {
50 fs.appendFileSync(BASH_ENV, exportStr + '\n');
51 console.log(`BASH_ENV file appended (${colors_1.dimGrey(BASH_ENV)})`);
52 }
53}
54/**
55 * Turns Object with keys/values into a *.sh script that exports all keys as values.
56 *
57 * @example
58 * { a: 'b', b: 'c'}
59 *
60 * will turn into:
61 *
62 * export a="b"
63 * export b="c"
64 */
65function objectToShellExport(o, prefix = '') {
66 return Object.keys(o)
67 .map(k => {
68 const v = o[k];
69 if (v) {
70 return `export ${prefix}${k}="${v}"`;
71 }
72 })
73 .filter(Boolean)
74 .join('\n');
75}
76exports.objectToShellExport = objectToShellExport;