1 | var fs = require('fs')
|
2 | var cons = require('./console').Console
|
3 |
|
4 | function method(name) {
|
5 | return function(o) {
|
6 | return o[name].apply(o)
|
7 | }
|
8 | }
|
9 |
|
10 |
|
11 | function KeyValue(data) {
|
12 | var env = {};
|
13 |
|
14 | data.toString().replace(/^\s*\#.*$/gm,'')
|
15 | .replace(/^\s*$/gm,'')
|
16 | .split(/\n/)
|
17 | .map(method('trim'))
|
18 | .filter(notBlank)
|
19 | .forEach(capturePair)
|
20 | return env
|
21 |
|
22 | function notBlank(str) {
|
23 | return str.length > 2
|
24 | }
|
25 |
|
26 | function capturePair(line) {
|
27 | var pair = line.split('=');
|
28 | var key = pair[0].trim();
|
29 | var rawVal = pair.slice(1).join('=').trim();
|
30 | env[key] = parseValue(rawVal);
|
31 | }
|
32 |
|
33 | function parseValue(val) {
|
34 | switch (val[0]) {
|
35 | case '"': return /^"([^"]*)"/.exec(val)[1];
|
36 | case "'": return /^'([^']*)'/.exec(val)[1];
|
37 | default : return val.replace(/\s*\#.*$/, '');
|
38 | }
|
39 | }
|
40 | }
|
41 |
|
42 |
|
43 |
|
44 |
|
45 |
|
46 |
|
47 |
|
48 |
|
49 |
|
50 |
|
51 |
|
52 |
|
53 |
|
54 |
|
55 |
|
56 |
|
57 |
|
58 |
|
59 |
|
60 |
|
61 |
|
62 |
|
63 |
|
64 |
|
65 | function flattenJSON(json) {
|
66 | var flattened = {}
|
67 |
|
68 | walk(json, function(path, item) {
|
69 | flattened[path.join('_').toUpperCase()] = item
|
70 | })
|
71 |
|
72 | return flattened
|
73 |
|
74 | function walk(obj, visitor, path) {
|
75 | var item
|
76 | path = path || []
|
77 | for (key in obj) {
|
78 | item = obj[key]
|
79 | if (typeof item == 'object') {
|
80 | walk(item, visitor, path.concat(key))
|
81 | } else {
|
82 | visitor(path.concat(key), item)
|
83 | }
|
84 | }
|
85 | }
|
86 | }
|
87 |
|
88 |
|
89 |
|
90 |
|
91 |
|
92 |
|
93 |
|
94 |
|
95 |
|
96 |
|
97 |
|
98 |
|
99 |
|
100 |
|
101 |
|
102 |
|
103 |
|
104 |
|
105 |
|
106 |
|
107 | function dumpEnv(conf) {
|
108 | var output = []
|
109 | for (key in conf) {
|
110 | output.push(key + '=' + conf[key])
|
111 | }
|
112 | return output.join('\n') + '\n'
|
113 | }
|
114 |
|
115 |
|
116 |
|
117 | function loadEnvs(path){
|
118 | var env, data
|
119 |
|
120 | if (!fs.existsSync(path)) {
|
121 | cons.Warn("No ENV file found")
|
122 | env = {}
|
123 | } else {
|
124 | data = fs.readFileSync(path);
|
125 | try {
|
126 | var envs_json = JSON.parse(data)
|
127 | env = flattenJSON(envs_json,"",{});
|
128 | cons.Alert("Loaded ENV %s File as JSON Format",path);
|
129 | } catch (e) {
|
130 | env = KeyValue(data);
|
131 | cons.Alert("Loaded ENV %s File as KEY=VALUE Format",path);
|
132 | }
|
133 | }
|
134 | env.PATH = env.PATH || process.env.PATH;
|
135 | return env;
|
136 | }
|
137 |
|
138 | module.exports.loadEnvs = loadEnvs
|
139 | module.exports.flattenJSON = flattenJSON
|
140 | module.exports.KeyValue = KeyValue
|
141 | module.exports.dumpEnv = dumpEnv
|