1 | "use strict";
|
2 | Object.defineProperty(exports, "__esModule", { value: true });
|
3 | exports.objectToGithubActionsEnv = 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 | githubEnv: true,
|
10 | fail: true,
|
11 | };
|
12 | function json2env(opt) {
|
13 | const { jsonPath, prefix, saveEnvFile, bashEnv, githubEnv, fail, debug, silent } = {
|
14 | ...JSON2ENV_OPT_DEF,
|
15 | ...opt,
|
16 | };
|
17 | if (!fs.pathExistsSync(jsonPath)) {
|
18 | if (fail) {
|
19 | throw new Error(`Path doesn't exist: ${jsonPath}`);
|
20 | }
|
21 | if (!silent) {
|
22 | console.log(`json2env input file doesn't exist, skipping without error (${jsonPath})`);
|
23 | }
|
24 | if (bashEnv) {
|
25 | appendBashEnv('');
|
26 | }
|
27 | return;
|
28 | }
|
29 |
|
30 | const json = fs.readJsonSync(jsonPath);
|
31 | const exportStr = objectToShellExport(json, prefix);
|
32 | const githubStr = objectToGithubActionsEnv(json, prefix);
|
33 | if (debug) {
|
34 | console.log(json, exportStr, githubStr);
|
35 | }
|
36 | if (saveEnvFile) {
|
37 | const shPath = `${jsonPath}.sh`;
|
38 | fs.writeFileSync(shPath, exportStr);
|
39 | if (!silent) {
|
40 | console.log(`json2env created ${(0, colors_1.dimGrey)(shPath)}:`);
|
41 | console.log(exportStr);
|
42 | }
|
43 | }
|
44 | if (bashEnv) {
|
45 | appendBashEnv(exportStr);
|
46 | }
|
47 | if (githubEnv) {
|
48 | appendGithubEnv(githubStr);
|
49 | }
|
50 | }
|
51 | exports.json2env = json2env;
|
52 | function appendBashEnv(exportStr) {
|
53 | const { BASH_ENV } = process.env;
|
54 | if (BASH_ENV) {
|
55 | fs.appendFileSync(BASH_ENV, exportStr + '\n');
|
56 | console.log(`BASH_ENV file appended (${(0, colors_1.dimGrey)(BASH_ENV)})`);
|
57 | }
|
58 | }
|
59 | function appendGithubEnv(exportStr) {
|
60 | const { GITHUB_ENV } = process.env;
|
61 | if (GITHUB_ENV) {
|
62 | fs.appendFileSync(GITHUB_ENV, exportStr + '\n');
|
63 | console.log(`GITHUB_ENV file appended (${(0, colors_1.dimGrey)(GITHUB_ENV)})`);
|
64 | }
|
65 | }
|
66 |
|
67 |
|
68 |
|
69 |
|
70 |
|
71 |
|
72 |
|
73 |
|
74 |
|
75 |
|
76 |
|
77 | function objectToShellExport(o, prefix = '') {
|
78 | return Object.keys(o)
|
79 | .map(k => {
|
80 | const v = o[k];
|
81 | if (v) {
|
82 | return `export ${prefix}${k}="${v}"`;
|
83 | }
|
84 | })
|
85 | .filter(Boolean)
|
86 | .join('\n');
|
87 | }
|
88 | exports.objectToShellExport = objectToShellExport;
|
89 |
|
90 |
|
91 |
|
92 |
|
93 |
|
94 |
|
95 |
|
96 |
|
97 |
|
98 |
|
99 |
|
100 | function objectToGithubActionsEnv(o, prefix = '') {
|
101 | return Object.keys(o)
|
102 | .map(k => {
|
103 | const v = o[k];
|
104 | if (v) {
|
105 | return `${prefix}${k}=${v}`;
|
106 | }
|
107 | })
|
108 | .filter(Boolean)
|
109 | .join('\n');
|
110 | }
|
111 | exports.objectToGithubActionsEnv = objectToGithubActionsEnv;
|