aboutsummaryrefslogtreecommitdiff
path: root/node_modules/hullabaloo-config-manager/lib/codegen.js
diff options
context:
space:
mode:
authorFlorian Dold <florian.dold@gmail.com>2017-05-28 00:38:50 +0200
committerFlorian Dold <florian.dold@gmail.com>2017-05-28 00:40:43 +0200
commit7fff4499fd915bcea3fa93b1aa8b35f4fe7a6027 (patch)
tree6de9a1aebd150a23b7f8c273ec657a5d0a18fe3e /node_modules/hullabaloo-config-manager/lib/codegen.js
parent963b7a41feb29cc4be090a2446bdfe0c1f1bcd81 (diff)
add linting (and some initial fixes)
Diffstat (limited to 'node_modules/hullabaloo-config-manager/lib/codegen.js')
-rw-r--r--node_modules/hullabaloo-config-manager/lib/codegen.js64
1 files changed, 64 insertions, 0 deletions
diff --git a/node_modules/hullabaloo-config-manager/lib/codegen.js b/node_modules/hullabaloo-config-manager/lib/codegen.js
new file mode 100644
index 000000000..0f95284d2
--- /dev/null
+++ b/node_modules/hullabaloo-config-manager/lib/codegen.js
@@ -0,0 +1,64 @@
+'use strict'
+
+const indentString = require('indent-string')
+const stringifyJson5 = require('json5').stringify
+
+function stringify (json5, value) {
+ return json5
+ ? stringifyJson5(value, null, 2)
+ : JSON.stringify(value, null, 2)
+}
+
+function generateFactory (unflattened, envName) {
+ const code = [`${envName ? '()' : 'envName'} => {`]
+
+ if (envName) {
+ const flattenedOptions = unflattened.reduceRight((prev, options) => {
+ options.env = {
+ [envName]: prev
+ }
+ return options
+ })
+ code.push(indentString(`return ${stringify(unflattened.json5, flattenedOptions)}`, 2))
+ } else {
+ const optionsCode = unflattened.reduceRight((prev, options, index) => {
+ const str = stringify(unflattened.json5, options)
+ if (!prev) return str
+
+ // reduceOptions ensures no options object is ever empty.
+ const lines = str.split('\n')
+ lines[lines.length - 2] += ','
+ lines[lines.length - 1] = indentString(`env: {\n [envName]: ${indentString(prev, 2).trimLeft()}\n}`, 2)
+ return lines.join('\n') + '\n}'
+ }, null)
+
+ code.push(indentString(`return ${optionsCode.trimLeft()}`, 2))
+ }
+
+ code.push('}')
+ return code.join('\n')
+}
+
+function codegen (resolvedConfig) {
+ const code = [`"use strict"
+
+const process = require("process")\n`]
+ code.push(`const defaultOptions = ${generateFactory(resolvedConfig.unflattenedDefaultOptions)}\n`)
+
+ code.push(`const envOptions = Object.create(null)\n`)
+ for (const envName of resolvedConfig.envNames) {
+ const unflattened = resolvedConfig.unflattenedEnvOptions.get(envName)
+ code.push(`envOptions[${JSON.stringify(envName)}] = ${generateFactory(unflattened, envName)}\n`)
+ }
+
+ code.push(`exports.getOptions = () => {
+ const envName = process.env.BABEL_ENV || process.env.NODE_ENV || "development"
+ return envName in envOptions
+ ? envOptions[envName]()
+ : defaultOptions(envName)
+}\n`)
+
+ return code.join('\n')
+}
+
+module.exports = codegen