3 const fs = require('fs')
4 const path = require('path')
5 const YError = require('./yerror')
7 let previouslyVisitedConfigs = []
9 function checkForCircularExtends (cfgPath) {
10 if (previouslyVisitedConfigs.indexOf(cfgPath) > -1) {
11 throw new YError(`Circular extended configurations: '${cfgPath}'.`)
15 function getPathToDefaultConfig (cwd, pathToExtend) {
16 return path.resolve(cwd, pathToExtend)
19 function applyExtends (config, cwd) {
20 let defaultConfig = {}
22 if (config.hasOwnProperty('extends')) {
23 if (typeof config.extends !== 'string') return defaultConfig
24 const isPath = /\.json$/.test(config.extends)
25 let pathToDefault = null
28 pathToDefault = require.resolve(config.extends)
30 // most likely this simply isn't a module.
33 pathToDefault = getPathToDefaultConfig(cwd, config.extends)
35 // maybe the module uses key for some other reason,
36 // err on side of caution.
37 if (!pathToDefault && !isPath) return config
39 checkForCircularExtends(pathToDefault)
41 previouslyVisitedConfigs.push(pathToDefault)
43 defaultConfig = isPath ? JSON.parse(fs.readFileSync(pathToDefault, 'utf8')) : require(config.extends)
45 defaultConfig = applyExtends(defaultConfig, path.dirname(pathToDefault))
48 previouslyVisitedConfigs = []
50 return Object.assign({}, defaultConfig, config)
53 module.exports = applyExtends