UNPKG

2.31 kBJavaScriptView Raw
1/* @flow */
2'use strict'
3
4const chalk = require('chalk')
5const Table = require('cli-table2')
6
7const projectMeta = require('./utils/project-meta.js')
8
9function read (
10 cwd /* : string */,
11 env /* : string */
12) /* : Promise<{ [id:string]: string }> */ {
13 return projectMeta.read(cwd)
14 .then((config) => config && config.server && config.server.variables ? config.server.variables : {})
15 .then((variables) => {
16 const keys = Object.keys(variables)
17
18 if (!keys.length) {
19 return {}
20 }
21
22 return keys.reduce((memo, key) => {
23 const variable = variables[key]
24 switch (typeof variable) {
25 case 'string':
26 memo[key] = variable
27 return memo
28 case 'object': {
29 if (variable[env]) {
30 if (typeof variable[env] !== 'string') {
31 throw new Error(`Variable ${key} for Environment ${env} must be a string`)
32 }
33 memo[key] = variable[env]
34 }
35 return memo
36 }
37 default:
38 throw new Error(`Variable ${key} must be an object or a string`)
39 }
40 }, {})
41 })
42}
43
44function display (
45 logger /* : any */,
46 cwd /* : string */,
47 env /* : string */
48) /* : Promise<void> */ {
49 return read(cwd, env)
50 .then((envVars) => _display(logger, envVars, env))
51}
52
53function setToCurrentProcess (
54 logger /* : typeof console */,
55 cwd /* : string */,
56 env /* : string */
57) /* : Promise<void> */ {
58 return read(cwd, env)
59 .then((envVars) => {
60 const keys = Object.keys(envVars)
61 if (!keys.length) {
62 return
63 }
64
65 keys.forEach((key) => {
66 process.env[key] = envVars[key]
67 })
68
69 return _display(logger, envVars, env)
70 })
71}
72
73function _display (
74 logger /* : typeof console */,
75 envVars /* : { [id:string]: string } */,
76 env /* : string */
77) /* : void */ {
78 const keys = Object.keys(envVars)
79 if (!keys.length) {
80 return
81 }
82
83 const rows = keys.map((key) => [
84 chalk.grey(key),
85 envVars[key]
86 ])
87
88 rows.unshift([{
89 content: chalk.bold(`Environment Variables (${env})`),
90 hAlign: 'center',
91 colSpan: 2
92 }])
93
94 var table = new Table()
95 table.push.apply(table, rows)
96
97 logger.log(table.toString())
98}
99
100module.exports = {
101 read,
102 display,
103 setToCurrentProcess
104}