UNPKG

2.01 kBPlain TextView Raw
1import * as fs from 'fs-extra'
2import { dimGrey } from '../colors'
3
4export interface Json2EnvOptions {
5 jsonPath: string
6 prefix?: string
7
8 /**
9 * @default true
10 */
11 saveEnvFile?: boolean
12
13 /**
14 * @default true
15 */
16 bashEnv?: boolean
17
18 /**
19 * @default true
20 */
21 fail?: boolean
22
23 debug?: boolean
24 silent?: boolean
25}
26
27const JSON2ENV_OPT_DEF: Partial<Json2EnvOptions> = {
28 saveEnvFile: true,
29 bashEnv: true,
30 fail: true,
31}
32
33export function json2env(opt: Json2EnvOptions): 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 // read file
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
78function 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 * Turns Object with keys/values into a *.sh script that exports all keys as values.
89 *
90 * @example
91 * { a: 'b', b: 'c'}
92 *
93 * will turn into:
94 *
95 * export a="b"
96 * export b="c"
97 */
98export 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}