2023-12-18 13:12:25 +08:00
|
|
|
|
2023-12-28 23:41:32 +08:00
|
|
|
'use strict'
|
|
|
|
const fs = require('fs')
|
|
|
|
const path = require('path')
|
|
|
|
const YError = require('./yerror')
|
2023-12-18 13:12:25 +08:00
|
|
|
|
2023-12-28 23:41:32 +08:00
|
|
|
let previouslyVisitedConfigs = []
|
|
|
|
|
|
|
|
function checkForCircularExtends (cfgPath) {
|
|
|
|
if (previouslyVisitedConfigs.indexOf(cfgPath) > -1) {
|
|
|
|
throw new YError(`Circular extended configurations: '${cfgPath}'.`)
|
2023-12-18 13:12:25 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
function getPathToDefaultConfig (cwd, pathToExtend) {
|
|
|
|
return path.resolve(cwd, pathToExtend)
|
|
|
|
}
|
|
|
|
|
2023-12-28 23:41:32 +08:00
|
|
|
function applyExtends (config, cwd) {
|
|
|
|
let defaultConfig = {}
|
2023-12-18 13:12:25 +08:00
|
|
|
|
|
|
|
if (config.hasOwnProperty('extends')) {
|
2023-12-28 23:41:32 +08:00
|
|
|
if (typeof config.extends !== 'string') return defaultConfig
|
|
|
|
const isPath = /\.json|\..*rc$/.test(config.extends)
|
|
|
|
let pathToDefault = null
|
|
|
|
if (!isPath) {
|
|
|
|
try {
|
|
|
|
pathToDefault = require.resolve(config.extends)
|
|
|
|
} catch (err) {
|
|
|
|
// most likely this simply isn't a module.
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
pathToDefault = getPathToDefaultConfig(cwd, config.extends)
|
|
|
|
}
|
|
|
|
// maybe the module uses key for some other reason,
|
|
|
|
// err on side of caution.
|
|
|
|
if (!pathToDefault && !isPath) return config
|
2023-12-18 13:12:25 +08:00
|
|
|
|
|
|
|
checkForCircularExtends(pathToDefault)
|
|
|
|
|
|
|
|
previouslyVisitedConfigs.push(pathToDefault)
|
|
|
|
|
2023-12-28 23:41:32 +08:00
|
|
|
defaultConfig = isPath ? JSON.parse(fs.readFileSync(pathToDefault, 'utf8')) : require(config.extends)
|
|
|
|
delete config.extends
|
|
|
|
defaultConfig = applyExtends(defaultConfig, path.dirname(pathToDefault))
|
2023-12-18 13:12:25 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
previouslyVisitedConfigs = []
|
|
|
|
|
2023-12-28 23:41:32 +08:00
|
|
|
return Object.assign({}, defaultConfig, config)
|
2023-12-18 13:12:25 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = applyExtends
|