UNPKG

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