-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathvariable_handler.js
More file actions
55 lines (44 loc) · 1.45 KB
/
variable_handler.js
File metadata and controls
55 lines (44 loc) · 1.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
'use strict';
const { render } = require('micromustache');
function updateRuntimeVariables(config, output) {
const scope = { runtime: output };
const opts = { prefix: 'runtime', onMissing: 'skip' };
return replaceEntry(config, { scope, opts });
}
function updateUserVariables(config, vars) {
const scope = { var: vars };
const opts = { prefix: 'var', onMissing: 'fail' };
return replaceEntry(config, { scope, opts });
}
function replaceEntry(value, scope) {
const type = typeof(value);
if (type === 'string') {
return replaceVariable(value, scope);
} else if (type === 'object' && value !== null) {
if (Array.isArray(value)) {
return recurseArr(value, scope);
} else {
return recurseObj(value, scope);
}
}
return value;
}
function recurseObj(obj, scope) {
return Object.keys(obj).reduce((newObj, key) => {
return { ...newObj, [key]: replaceEntry(obj[key], scope) };
}, {});
}
function recurseArr(arr, scope) {
return arr.map(value => replaceEntry(value, scope));
}
function replaceVariable(string, { scope, opts }) {
if (string.indexOf('{{') === -1) return string;
if (string.indexOf(opts.prefix + '.') === -1) return string;
const newString = render(string, scope);
if (newString === '') {
if (opts.onMissing === 'fail') throw new Error(`Missing var: ${string}`);
if (opts.onMissing === 'skip') return string;
}
return newString;
}
module.exports = { updateRuntimeVariables, updateUserVariables };