wishthis/node_modules/rtlcss/lib/config-loader.js

93 lines
1.8 KiB
JavaScript
Raw Normal View History

2022-01-21 08:28:41 +00:00
'use strict'
2022-06-08 10:36:39 +00:00
const fs = require('fs')
const path = require('path')
const findUp = require('find-up')
const stripJSONComments = require('strip-json-comments')
let config = {}
const configSources = ['package.json', '.rtlcssrc', '.rtlcss.json']
const environments = [
process.env.USERPROFILE,
process.env.HOMEPATH,
process.env.HOME
]
const readConfig = (configFilePath) => {
return JSON.parse(stripJSONComments(fs.readFileSync(configFilePath, 'utf-8').trim()))
}
module.exports.load = (configFilePath, cwd, overrides) => {
2022-01-21 08:28:41 +00:00
if (configFilePath) {
2022-06-08 10:36:39 +00:00
return override(readConfig(configFilePath), overrides)
2022-01-21 08:28:41 +00:00
}
2022-06-08 10:36:39 +00:00
const directory = cwd || process.cwd()
2022-01-21 08:28:41 +00:00
config = loadConfig(directory)
2022-06-08 10:36:39 +00:00
2022-01-21 08:28:41 +00:00
if (!config) {
2022-06-08 10:36:39 +00:00
for (const environment of environments) {
if (!environment) {
2022-01-21 08:28:41 +00:00
continue
}
2022-06-08 10:36:39 +00:00
config = loadConfig(environment)
2022-01-21 08:28:41 +00:00
if (config) {
break
}
}
}
if (config) {
override(config, overrides)
}
2022-06-08 10:36:39 +00:00
2022-01-21 08:28:41 +00:00
return config
}
2022-06-08 10:36:39 +00:00
function loadConfig (cwd) {
for (const source of configSources) {
let foundPath
2022-01-21 08:28:41 +00:00
try {
2022-06-08 10:36:39 +00:00
foundPath = findUp.sync(source, { cwd })
2022-01-21 08:28:41 +00:00
} catch (e) {
continue
}
2022-06-08 10:36:39 +00:00
if (foundPath) {
const configFilePath = path.normalize(foundPath)
2022-01-21 08:28:41 +00:00
try {
2022-06-08 10:36:39 +00:00
config = readConfig(configFilePath)
2022-01-21 08:28:41 +00:00
} catch (e) {
2022-06-08 10:36:39 +00:00
throw new Error(`${e} ${configFilePath}`)
2022-01-21 08:28:41 +00:00
}
if (source === 'package.json') {
config = config.rtlcssConfig
}
if (config) {
return config
}
}
}
}
function override (to, from) {
if (to && from) {
2022-06-08 10:36:39 +00:00
for (const p in from) {
if (Object.prototype.hasOwnProperty.call(from, p)) {
if (Object.prototype.hasOwnProperty.call(to, p) && typeof to[p] === 'object') {
override(to[p], from[p])
} else {
to[p] = from[p]
}
2022-01-21 08:28:41 +00:00
}
}
}
2022-06-08 10:36:39 +00:00
2022-01-21 08:28:41 +00:00
return to
}