Tim van der Lippe | 835724b | 2020-03-10 16:48:02 +0000 | [diff] [blame] | 1 | /** |
| 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 | |
| 12 | const fs = require('fs'); |
| 13 | const path = require('path'); |
| 14 | |
| 15 | //------------------------------------------------------------------------------ |
| 16 | // Plugin Definition |
| 17 | //------------------------------------------------------------------------------ |
| 18 | |
| 19 | const cache = {}; |
| 20 | module.exports = { |
| 21 | get rules() { |
| 22 | const RULES_DIR = module.exports.RULES_DIR; |
Jack Franklin | 32c8d82 | 2021-03-12 11:50:11 +0000 | [diff] [blame^] | 23 | 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 Lippe | 835724b | 2020-03-10 16:48:02 +0000 | [diff] [blame] | 25 | } |
Jack Franklin | 32c8d82 | 2021-03-12 11:50:11 +0000 | [diff] [blame^] | 26 | 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) |
| 32 | .filter(filename => filename.endsWith('.js')) |
| 33 | .map(filename => path.resolve(rulesDir, filename)) |
| 34 | .forEach((absolutePath) => { |
| 35 | const ruleName = path.basename(absolutePath, '.js'); |
| 36 | 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 Lippe | 835724b | 2020-03-10 16:48:02 +0000 | [diff] [blame] | 43 | } |
Jack Franklin | 32c8d82 | 2021-03-12 11:50:11 +0000 | [diff] [blame^] | 44 | return cache[cacheKey]; |
Tim van der Lippe | 835724b | 2020-03-10 16:48:02 +0000 | [diff] [blame] | 45 | }, |
| 46 | }; |