codekingpro/portable-devtools
114k
1// replace any ${ENV} values with the appropriate environ.
2// optional "?" modifier can be used like this: ${ENV?} so in case of the variable being not defined, it evaluates into empty string.
3
4const envExpr = /(?<!\\)(\\*)\$\{([^${}?]+)(\?)?\}/g
5
6module.exports = (f, env) => f.replace(envExpr, (orig, esc, name, modifier) => {
7 const fallback = modifier === '?' ? '' : `$\{${name}}`
8 const val = env[name] !== undefined ? env[name] : fallback
9
10 // consume the escape chars that are relevant.
11 if (esc.length % 2) {
12 return orig.slice((esc.length + 1) / 2)
13 }
14
15 return (esc.slice(esc.length / 2)) + val
16})
17 