UNPKG

1.5 kBJavaScriptView Raw
1var cc = require('./lib/utils')
2var join = require('path').join
3var deepExtend = require('deep-extend')
4var etc = '/etc'
5var win = process.platform === "win32"
6var home = win
7 ? process.env.USERPROFILE
8 : process.env.HOME
9
10module.exports = function (name, defaults, argv, parse) {
11 if('string' !== typeof name)
12 throw new Error('rc(name): name *must* be string')
13 if(!argv)
14 argv = require('minimist')(process.argv.slice(2))
15 defaults = (
16 'string' === typeof defaults
17 ? cc.json(defaults) : defaults
18 ) || {}
19
20 parse = parse || cc.parse
21
22 var env = cc.env(name + '_')
23
24 var configs = [defaults]
25 var configFiles = []
26 function addConfigFile (file) {
27 if (configFiles.indexOf(file) >= 0) return
28 var fileConfig = cc.file(file)
29 if (fileConfig) {
30 configs.push(parse(fileConfig))
31 configFiles.push(file)
32 }
33 }
34
35 // which files do we look at?
36 if (!win)
37 [join(etc, name, 'config'),
38 join(etc, name + 'rc')].forEach(addConfigFile)
39 if (home)
40 [join(home, '.config', name, 'config'),
41 join(home, '.config', name),
42 join(home, '.' + name, 'config'),
43 join(home, '.' + name + 'rc')].forEach(addConfigFile)
44 addConfigFile(cc.find('.'+name+'rc'))
45 if (env.config) addConfigFile(env.config)
46 if (argv.config) addConfigFile(argv.config)
47
48 return deepExtend.apply(null, configs.concat([
49 env,
50 argv,
51 configFiles.length ? {configs: configFiles, config: configFiles[configFiles.length - 1]} : undefined,
52 ]))
53}