-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
95 lines (87 loc) · 2.46 KB
/
index.js
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
var optimist = require('optimist')
, argv = optimist.argv;
// optimist provides these, we don't want them.
delete argv['_'];
delete argv['$0'];
// Load a js or json file
var getFile = function(filename) {
var file;
try {
file = require(filename);
} catch (e) {
if (e instanceof SyntaxError) {
throw new Error("Confrodo: Syntax error in file '" + filename + "': " + e.message);
} else if (e.message.match(/^Cannot find module/)) {
throw new Error("Confrodo: Can't find file '" + filename + "'");
} else {
throw e;
}
}
return file;
};
// Get the enviroment.
// env will be "local" unless `env` is passed as a command
// line argument, or the NODE_ENV environment variable is set.
var getEnvironment = function() {
var env;
if (argv.hasOwnProperty('env')) {
env = argv.env;
} else if (typeof process.env.NODE_ENV === 'string') {
env = process.env.NODE_ENV;
} else {
env = 'local';
}
return env;
};
// Merge two objects together.
// The second object wins if the both have
// the same property.
var mergeConfig = function(configA, configB, mergeStrategy) {
if (mergeStrategy) {
return mergeStrategy(configA, configB);
}
var merged = {}
, hop = Object.prototype.hasOwnProperty;
for (var i in configA) {
if (hop.call(configA, i)) {
merged[i] = configA[i];
}
}
for (var i in configB) {
if (hop.call(configB, i)) {
merged[i] = configB[i];
}
}
return merged;
};
// The magic we export.
// This funcion combines everything into one object.
// It is the essence of awesomeness.
var frodo = function() {
var args = Array.prototype.slice.call(arguments);
var mergeStrategy = null;
if (typeof args[args.length - 1] === "function") {
mergeStrategy = args.pop();
}
var config = {};
config.env = getEnvironment();
for (var i = 0; i < args.length; ++i) {
if (typeof args[i] === "string") {
if (args[i] === "ENV") {
config = mergeConfig(config, process.env, mergeStrategy);
} else if (args[i] === "ARGV") {
config = mergeConfig(config, argv, mergeStrategy);
} else {
config = mergeConfig(config, getFile(args[i]), mergeStrategy);
}
} else if (typeof args[i] === "object") {
config = mergeConfig(config, args[i], mergeStrategy);
}
}
return config;
};
// attach env to confrodo
frodo.env = getEnvironment();
// set NODE_ENV, in case we got it from somwhere else
process.env['NODE_ENV'] = frodo.env;
module.exports = frodo;