UNPKG

1.54 kBtext/coffeescriptView Raw
1cson = require './lib/cson'
2path = require 'path'
3fs = require 'fs'
4
5stack = []
6substitutes = []
7
8exports.use = (regexp, callback) ->
9 stack.push
10 regexp: regexp
11 handle: callback
12
13
14exports.load = (configPath, exportToProcess = true) ->
15 unless configPath
16 configDir = path.dirname module.parent.filename
17 configPath = "#{configDir}/config.cson"
18 else
19 configDir = path.dirname configPath
20
21 try
22 ef = "#{configDir}/.env"
23 items = fs.readFileSync(ef).toString().split "\n"
24 for item in items
25 # split by first '='
26 s = item.match /^([A-Z0-9_-]+)=(.+)/
27 continue unless s
28
29 # find and replace environment variables
30 env = s[2].match(/\$[A-Z0-9_-]+/g) || []
31 for key in env
32 if value = process.env[key.slice(1)]
33 s[2] = s[2].replace key, value
34
35 process.env[s[1]] ?= s[2]
36 catch err
37
38 c = cson.parseFileSync configPath, sandbox: global
39
40 if stack.length > 0
41 mapRecursive c, (val) ->
42 for filter in stack
43 if filter.regexp.test val
44 substitute = filter.handle val
45 unless substitute in substitutes
46 substitutes.push substitute
47 return substitute
48 return val
49
50 if c.stack?
51 console.log "Error in config file #{configPath}"
52 console.log c
53 process.exit 1
54
55 process.config[key] = val for key, val of c if exportToProcess
56
57 return c
58
59
60mapRecursive = (obj, callback) ->
61 return unless typeof obj is "object"
62 for key of obj
63 if obj[key] in substitutes
64 continue
65 if typeof obj[key] is "object"
66 mapRecursive obj[key], callback
67 else
68 val = callback obj[key]
69 obj[key] = val if val