2020-03-07 11:45:40 +08:00
|
|
|
/**
|
|
|
|
* @fileoverview Module for loading rules from files and directories.
|
|
|
|
* @author Michael Ficarra
|
|
|
|
*/
|
|
|
|
|
|
|
|
"use strict";
|
|
|
|
|
|
|
|
//------------------------------------------------------------------------------
|
|
|
|
// Requirements
|
|
|
|
//------------------------------------------------------------------------------
|
|
|
|
|
|
|
|
const fs = require("fs"),
|
|
|
|
path = require("path");
|
|
|
|
|
|
|
|
const rulesDirCache = {};
|
|
|
|
|
|
|
|
//------------------------------------------------------------------------------
|
|
|
|
// Public Interface
|
|
|
|
//------------------------------------------------------------------------------
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Load all rule modules from specified directory.
|
|
|
|
* @param {string} relativeRulesDir Path to rules directory, may be relative.
|
|
|
|
* @param {string} cwd Current working directory
|
2020-03-31 20:40:00 +08:00
|
|
|
* @returns {Object} Loaded rule modules.
|
2020-03-07 11:45:40 +08:00
|
|
|
*/
|
|
|
|
module.exports = function(relativeRulesDir, cwd) {
|
|
|
|
const rulesDir = path.resolve(cwd, relativeRulesDir);
|
|
|
|
|
|
|
|
// cache will help performance as IO operation are expensive
|
|
|
|
if (rulesDirCache[rulesDir]) {
|
|
|
|
return rulesDirCache[rulesDir];
|
|
|
|
}
|
|
|
|
|
|
|
|
const rules = Object.create(null);
|
|
|
|
|
|
|
|
fs.readdirSync(rulesDir).forEach(file => {
|
|
|
|
if (path.extname(file) !== ".js") {
|
|
|
|
return;
|
|
|
|
}
|
2020-03-31 20:40:00 +08:00
|
|
|
rules[file.slice(0, -3)] = require(path.join(rulesDir, file));
|
2020-03-07 11:45:40 +08:00
|
|
|
});
|
|
|
|
rulesDirCache[rulesDir] = rules;
|
|
|
|
|
|
|
|
return rules;
|
|
|
|
};
|