UNPKG

2.97 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.objectToGithubActionsEnv = exports.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 githubEnv: true,
10 fail: true,
11};
12function 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 // read file
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}
51exports.json2env = json2env;
52function 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}
59function 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 * Turns Object with keys/values into a *.sh script that exports all keys as values.
68 *
69 * @example
70 * { a: 'b', b: 'c'}
71 *
72 * will turn into:
73 *
74 * export a="b"
75 * export b="c"
76 */
77function 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}
88exports.objectToShellExport = objectToShellExport;
89/**
90 * Turns Object with keys/values into a file of key-value pairs
91 *
92 * @example
93 * { a: 'b', b: 'c'}
94 *
95 * will turn into:
96 *
97 * a=b
98 * b=c
99 */
100function 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}
111exports.objectToGithubActionsEnv = objectToGithubActionsEnv;