apply-extends.js 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  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