apply-extends.js 1.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. var fs = require('fs')
  2. var path = require('path')
  3. var assign = require('./assign')
  4. var YError = require('./yerror')
  5. var previouslyVisitedConfigs = []
  6. function checkForCircularExtends (path) {
  7. if (previouslyVisitedConfigs.indexOf(path) > -1) {
  8. throw new YError("Circular extended configurations: '" + path + "'.")
  9. }
  10. }
  11. function getPathToDefaultConfig (cwd, pathToExtend) {
  12. return path.resolve(cwd, pathToExtend)
  13. }
  14. function applyExtends (config, cwd, subKey) {
  15. var defaultConfig = {}
  16. if (config.hasOwnProperty('extends')) {
  17. var pathToDefault = getPathToDefaultConfig(cwd, config.extends)
  18. checkForCircularExtends(pathToDefault)
  19. previouslyVisitedConfigs.push(pathToDefault)
  20. delete config.extends
  21. defaultConfig = JSON.parse(fs.readFileSync(pathToDefault, 'utf8'))
  22. if (subKey) {
  23. defaultConfig = defaultConfig[subKey] || {}
  24. }
  25. defaultConfig = applyExtends(defaultConfig, path.dirname(pathToDefault), subKey)
  26. }
  27. previouslyVisitedConfigs = []
  28. return assign(defaultConfig, config)
  29. }
  30. module.exports = applyExtends