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