blob: bc2492e63cf493c2fe87eb814217963473dfabc1 [file] [log] [blame]
Tim van der Lippe835724b2020-03-10 16:48:02 +00001/**
2 * @fileoverview Allows a local ESLint rules directory to be used without a command-line flag
3 * @author Teddy Katz
4 */
5
6'use strict';
7
8//------------------------------------------------------------------------------
9// Requirements
10//------------------------------------------------------------------------------
11
12const fs = require('fs');
13const path = require('path');
14
15//------------------------------------------------------------------------------
16// Plugin Definition
17//------------------------------------------------------------------------------
18
19const cache = {};
20module.exports = {
21 get rules() {
22 const RULES_DIR = module.exports.RULES_DIR;
Jack Franklin32c8d822021-03-12 11:50:11 +000023 if (typeof module.exports.RULES_DIR !== 'string' && !Array.isArray(RULES_DIR)) {
24 throw new Error('To use eslint-plugin-rulesdir, you must load it beforehand and set the `RULES_DIR` property on the module to a string or an array of strings.');
Tim van der Lippe835724b2020-03-10 16:48:02 +000025 }
Jack Franklin32c8d822021-03-12 11:50:11 +000026 const cacheKey = JSON.stringify(RULES_DIR);
27 if (!cache[cacheKey]) {
28 const rules = Array.isArray(RULES_DIR) ? RULES_DIR : [RULES_DIR];
29 const rulesObject = {};
30 rules.forEach((rulesDir) => {
31 fs.readdirSync(rulesDir)
Tim van der Lippe0124c682021-11-23 15:12:10 +000032 .filter(filename => filename.endsWith('.js') || filename.endsWith('.cjs') || filename.endsWith('.mjs'))
Jack Franklin32c8d822021-03-12 11:50:11 +000033 .map(filename => path.resolve(rulesDir, filename))
34 .forEach((absolutePath) => {
Tim van der Lippe0124c682021-11-23 15:12:10 +000035 const ruleName = path.basename(absolutePath, path.extname(absolutePath));
Jack Franklin32c8d822021-03-12 11:50:11 +000036 if (rulesObject[ruleName]) {
37 throw new Error(`eslint-plugin-rulesdir found two rules with the same name: ${ruleName}`);
38 }
39 rulesObject[ruleName] = require(absolutePath);
40 });
41 });
42 cache[cacheKey] = rulesObject;
Tim van der Lippe835724b2020-03-10 16:48:02 +000043 }
Jack Franklin32c8d822021-03-12 11:50:11 +000044 return cache[cacheKey];
Tim van der Lippe835724b2020-03-10 16:48:02 +000045 },
46};