apply-extends.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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) {
  15. var defaultConfig = {}
  16. if (config.hasOwnProperty('extends')) {
  17. if (typeof config.extends !== 'string') return defaultConfig
  18. var isPath = /\.json$/.test(config.extends)
  19. var pathToDefault = null
  20. if (!isPath) {
  21. try {
  22. pathToDefault = require.resolve(config.extends)
  23. } catch (err) {
  24. // most likely this simply isn't a module.
  25. }
  26. } else {
  27. pathToDefault = getPathToDefaultConfig(cwd, config.extends)
  28. }
  29. // maybe the module uses key for some other reason,
  30. // err on side of caution.
  31. if (!pathToDefault && !isPath) return config
  32. checkForCircularExtends(pathToDefault)
  33. previouslyVisitedConfigs.push(pathToDefault)
  34. defaultConfig = isPath ? JSON.parse(fs.readFileSync(pathToDefault, 'utf8')) : require(config.extends)
  35. delete config.extends
  36. defaultConfig = applyExtends(defaultConfig, path.dirname(pathToDefault))
  37. }
  38. previouslyVisitedConfigs = []
  39. return assign(defaultConfig, config)
  40. }
  41. module.exports = applyExtends