config-loader.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /* global process */
  2. 'use strict'
  3. var fs = require('fs')
  4. var path = require('path')
  5. var findup = require('findup')
  6. var stripJSONComments = require('strip-json-comments')
  7. var config = {}
  8. var configSources = ['package.json', '.rtlcssrc', '.rtlcss.json']
  9. module.exports.load = function (configFilePath, cwd, overrides) {
  10. if (configFilePath) {
  11. return override(
  12. JSON.parse(
  13. stripJSONComments(
  14. fs.readFileSync(configFilePath, 'utf-8').trim())), overrides)
  15. }
  16. var directory = cwd || process.cwd()
  17. config = loadConfig(directory)
  18. if (!config) {
  19. var evns = [process.env.USERPROFILE, process.env.HOMEPATH, process.env.HOME]
  20. for (var x = 0; x < evns.length; x++) {
  21. if (!evns[x]) {
  22. continue
  23. }
  24. config = loadConfig(evns[x])
  25. if (config) {
  26. break
  27. }
  28. }
  29. }
  30. if (config) {
  31. override(config, overrides)
  32. }
  33. return config
  34. }
  35. function loadConfig (dir) {
  36. for (var x = 0; x < configSources.length; x++) {
  37. var found
  38. var source = configSources[x]
  39. try {
  40. found = findup.sync(dir, source)
  41. } catch (e) {
  42. continue
  43. }
  44. if (found) {
  45. var configFilePath = path.normalize(path.join(found, source))
  46. try {
  47. config = JSON.parse(
  48. stripJSONComments(
  49. fs.readFileSync(configFilePath, 'utf-8').trim()))
  50. } catch (e) {
  51. throw new Error(e + ' ' + configFilePath)
  52. }
  53. if (source === 'package.json') {
  54. config = config.rtlcssConfig
  55. }
  56. if (config) {
  57. return config
  58. }
  59. }
  60. }
  61. }
  62. function override (to, from) {
  63. if (to && from) {
  64. for (var p in from) {
  65. if (typeof to[p] === 'object') {
  66. override(to[p], from[p])
  67. } else {
  68. to[p] = from[p]
  69. }
  70. }
  71. }
  72. return to
  73. }