metal-soy-critic
Version:
A metal-soy code validation utility.
84 lines (83 loc) • 2.58 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const chalk = require("chalk");
const fs = require("fs");
const path = require("path");
const process = require("process");
const CONFIG_FILE_NAMES = [
'.soycriticrc',
'.soycriticrc.json',
];
exports.DEFAULT_CONFIG = {
callToImport: [{ regex: '(.*)', replace: '{$1}' }],
implicitParams: {}
};
function validateConfig(config) {
if (!Array.isArray(config.callToImport)) {
throw new Error('callToImport is not a valid config array.');
}
for (const item of config.callToImport) {
if (!isRegex(item.regex)) {
throw new Error(`callToImport.regex "${item.regex}" is not a valid RegExp.`);
}
if (!isRegex(item.replace)) {
throw new Error(`callToImport.replace "${item.replace}" is not a valid replace string.`);
}
}
for (const key in config.implicitParams) {
if (!isRegex(key)) {
throw new Error(`"${key}" is not a valid RegExp.`);
}
}
return config;
}
exports.validateConfig = validateConfig;
function convertConfig(config) {
if (config.callToImportRegex && config.callToImportReplace) {
config.callToImport = [
{
regex: config.callToImportRegex,
replace: config.callToImportReplace
}
];
console.log(chalk.yellow('CONFIG API HAS CHANGED, PLEASE UPDATE\n'));
console.log('\tYour callToImport configuration is outdated, update it to new API.\n');
}
return config;
}
exports.convertConfig = convertConfig;
function readConfig() {
const filePath = getConfigFilePath();
let config = {};
if (filePath) {
const buffer = fs.readFileSync(filePath);
config = JSON.parse(buffer.toString('utf8'));
}
config = convertConfig(config);
return validateConfig(Object.assign({}, exports.DEFAULT_CONFIG, config));
}
exports.readConfig = readConfig;
function getConfigFilePath() {
let currentPath = process.cwd();
while (currentPath !== '/') {
for (const fileName of CONFIG_FILE_NAMES) {
const nextPath = path.join(currentPath, '/', fileName);
if (fs.existsSync(nextPath)) {
return nextPath;
}
}
currentPath = path.dirname(currentPath);
}
return null;
}
exports.getConfigFilePath = getConfigFilePath;
function isRegex(regex) {
try {
new RegExp(regex);
}
catch (e) {
return false;
}
return true;
}
exports.isRegex = isRegex;