wallet-core/node_modules/yargs/lib/apply-extends.js

54 lines
1.4 KiB
JavaScript
Raw Normal View History

2017-08-14 05:01:11 +02:00
2017-12-10 21:51:33 +01:00
'use strict'
const fs = require('fs')
const path = require('path')
const YError = require('./yerror')
let previouslyVisitedConfigs = []
2017-08-14 05:01:11 +02:00
function checkForCircularExtends (path) {
if (previouslyVisitedConfigs.indexOf(path) > -1) {
2017-12-10 21:51:33 +01:00
throw new YError(`Circular extended configurations: '${path}'.`)
2017-08-14 05:01:11 +02:00
}
}
function getPathToDefaultConfig (cwd, pathToExtend) {
return path.resolve(cwd, pathToExtend)
}
function applyExtends (config, cwd) {
2017-12-10 21:51:33 +01:00
let defaultConfig = {}
2017-08-14 05:01:11 +02:00
if (config.hasOwnProperty('extends')) {
if (typeof config.extends !== 'string') return defaultConfig
2017-12-10 21:51:33 +01:00
const isPath = /\.json$/.test(config.extends)
let pathToDefault = null
2017-08-14 05:01:11 +02:00
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
checkForCircularExtends(pathToDefault)
previouslyVisitedConfigs.push(pathToDefault)
defaultConfig = isPath ? JSON.parse(fs.readFileSync(pathToDefault, 'utf8')) : require(config.extends)
delete config.extends
defaultConfig = applyExtends(defaultConfig, path.dirname(pathToDefault))
}
previouslyVisitedConfigs = []
2017-12-10 21:51:33 +01:00
return Object.assign({}, defaultConfig, config)
2017-08-14 05:01:11 +02:00
}
module.exports = applyExtends