index.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #! /usr/bin/env node
  2. var cc = require('./lib/utils')
  3. var join = require('path').join
  4. var deepExtend = require('deep-extend')
  5. var etc = '/etc'
  6. var win = process.platform === "win32"
  7. var home = win
  8. ? process.env.USERPROFILE
  9. : process.env.HOME
  10. module.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. parse = parse || cc.parse
  20. var env = cc.env(name + '_')
  21. var configs = [defaults]
  22. var configFiles = []
  23. function addConfigFile (file) {
  24. if (configFiles.indexOf(file) >= 0) return
  25. var fileConfig = cc.file(file)
  26. if (fileConfig) {
  27. configs.push(parse(fileConfig))
  28. configFiles.push(file)
  29. }
  30. }
  31. // which files do we look at?
  32. if (!win)
  33. [join(etc, name, 'config'),
  34. join(etc, name + 'rc')].forEach(addConfigFile)
  35. if (home)
  36. [join(home, '.config', name, 'config'),
  37. join(home, '.config', name),
  38. join(home, '.' + name, 'config'),
  39. join(home, '.' + name + 'rc')].forEach(addConfigFile)
  40. addConfigFile(cc.find('.'+name+'rc'))
  41. if (env.config) addConfigFile(env.config)
  42. if (argv.config) addConfigFile(argv.config)
  43. return deepExtend.apply(null, configs.concat([
  44. env,
  45. argv,
  46. configFiles.length ? {configs: configFiles, config: configFiles[configFiles.length - 1]} : undefined,
  47. ]))
  48. }
  49. if(!module.parent) {
  50. console.log(
  51. JSON.stringify(module.exports(process.argv[2]), false, 2)
  52. )
  53. }