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

82 lines
1.8 KiB
JavaScript
Raw Normal View History

2022-05-29 09:24:36 +00:00
/* global process */
2022-01-21 08:28:41 +00:00
'use strict'
2022-05-29 09:24:36 +00:00
var fs = require('fs')
var path = require('path')
var findup = require('@choojs/findup')
var stripJSONComments = require('strip-json-comments')
var config = {}
var configSources = ['package.json', '.rtlcssrc', '.rtlcss.json']
module.exports.load = function (configFilePath, cwd, overrides) {
2022-01-21 08:28:41 +00:00
if (configFilePath) {
2022-05-29 09:24:36 +00:00
return override(
JSON.parse(
stripJSONComments(
fs.readFileSync(configFilePath, 'utf-8').trim())), overrides)
2022-01-21 08:28:41 +00:00
}
2022-05-29 09:24:36 +00:00
var directory = cwd || process.cwd()
2022-01-21 08:28:41 +00:00
config = loadConfig(directory)
if (!config) {
2022-05-29 09:24:36 +00:00
var evns = [process.env.USERPROFILE, process.env.HOMEPATH, process.env.HOME]
for (var x = 0; x < evns.length; x++) {
if (!evns[x]) {
2022-01-21 08:28:41 +00:00
continue
}
2022-05-29 09:24:36 +00:00
config = loadConfig(evns[x])
2022-01-21 08:28:41 +00:00
if (config) {
break
}
}
}
if (config) {
override(config, overrides)
}
return config
}
2022-05-29 09:24:36 +00:00
function loadConfig (dir) {
for (var x = 0; x < configSources.length; x++) {
var found
var source = configSources[x]
2022-01-21 08:28:41 +00:00
try {
2022-05-29 09:24:36 +00:00
found = findup.sync(dir, source)
2022-01-21 08:28:41 +00:00
} catch (e) {
continue
}
2022-05-29 09:24:36 +00:00
if (found) {
var configFilePath = path.normalize(path.join(found, source))
2022-01-21 08:28:41 +00:00
try {
2022-05-29 09:24:36 +00:00
config = JSON.parse(
stripJSONComments(
fs.readFileSync(configFilePath, 'utf-8').trim()))
2022-01-21 08:28:41 +00:00
} catch (e) {
2022-05-29 09:24:36 +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-05-29 09:24:36 +00:00
for (var p in from) {
if (typeof to[p] === 'object') {
override(to[p], from[p])
} else {
to[p] = from[p]
2022-01-21 08:28:41 +00:00
}
}
}
return to
}