1 | "use strict";
|
2 | Object.defineProperty(exports, "__esModule", { value: true });
|
3 | exports.objectToShellExport = exports.json2env = void 0;
|
4 | const fs = require("fs-extra");
|
5 | const colors_1 = require("../colors");
|
6 | const JSON2ENV_OPT_DEF = {
|
7 | saveEnvFile: true,
|
8 | bashEnv: true,
|
9 | fail: true,
|
10 | };
|
11 | function 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 |
|
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 | }
|
46 | exports.json2env = json2env;
|
47 | function 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 |
|
56 |
|
57 |
|
58 |
|
59 |
|
60 |
|
61 |
|
62 |
|
63 |
|
64 |
|
65 | function 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 | }
|
76 | exports.objectToShellExport = objectToShellExport;
|