index.js 1.5 KB

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