1 | /**
|
2 | * @fileoverview Module for loading rules from files and directories.
|
3 | * @author Michael Ficarra
|
4 | */
|
5 |
|
6 | ;
|
7 |
|
8 | //------------------------------------------------------------------------------
|
9 | // Requirements
|
10 | //------------------------------------------------------------------------------
|
11 |
|
12 | const fs = require("fs"),
|
13 | path = require("path");
|
14 |
|
15 | const rulesDirCache = {};
|
16 |
|
17 | //------------------------------------------------------------------------------
|
18 | // Public Interface
|
19 | //------------------------------------------------------------------------------
|
20 |
|
21 | /**
|
22 | * Load all rule modules from specified directory.
|
23 | * @param {string} relativeRulesDir Path to rules directory, may be relative.
|
24 | * @param {string} cwd Current working directory
|
25 | * @returns {Object} Loaded rule modules.
|
26 | */
|
27 | module.exports = function(relativeRulesDir, cwd) {
|
28 | const rulesDir = path.resolve(cwd, relativeRulesDir);
|
29 |
|
30 | // cache will help performance as IO operation are expensive
|
31 | if (rulesDirCache[rulesDir]) {
|
32 | return rulesDirCache[rulesDir];
|
33 | }
|
34 |
|
35 | const rules = Object.create(null);
|
36 |
|
37 | fs.readdirSync(rulesDir).forEach(file => {
|
38 | if (path.extname(file) !== ".js") {
|
39 | return;
|
40 | }
|
41 | rules[file.slice(0, -3)] = require(path.join(rulesDir, file));
|
42 | });
|
43 | rulesDirCache[rulesDir] = rules;
|
44 |
|
45 | return rules;
|
46 | };
|