Mathias Bynens | 79e2cf0 | 2020-05-29 16:46:17 +0200 | [diff] [blame^] | 1 | 'use strict'; |
| 2 | |
| 3 | const normalizeRuleSettings = require('../normalizeRuleSettings'); |
| 4 | const Result = require('postcss/lib/result'); |
| 5 | const rules = require('../rules'); |
| 6 | |
| 7 | /** |
| 8 | * Useful for third-party code (e.g. plugins) to run a PostCSS Root |
| 9 | * against a specific rule and do something with the warnings |
| 10 | * @param {{ |
| 11 | ruleName: string, |
| 12 | ruleSettings: import('stylelint').StylelintConfigRuleSettings, |
| 13 | root: Object, |
| 14 | }} options |
| 15 | * @param {Function} callback |
| 16 | * @returns {void} |
| 17 | */ |
| 18 | module.exports = function (options, callback) { |
| 19 | if (!options) |
| 20 | throw new Error( |
| 21 | "checkAgainstRule requires an options object with 'ruleName', 'ruleSettings', and 'root' properties", |
| 22 | ); |
| 23 | |
| 24 | if (!callback) throw new Error('checkAgainstRule requires a callback'); |
| 25 | |
| 26 | if (!options.ruleName) throw new Error("checkAgainstRule requires a 'ruleName' option"); |
| 27 | |
| 28 | if (!Object.keys(rules).includes(options.ruleName)) |
| 29 | throw new Error(`Rule '${options.ruleName}' does not exist`); |
| 30 | |
| 31 | if (!options.ruleSettings) throw new Error("checkAgainstRule requires a 'ruleSettings' option"); |
| 32 | |
| 33 | if (!options.root) throw new Error("checkAgainstRule requires a 'root' option"); |
| 34 | |
| 35 | const settings = normalizeRuleSettings(options.ruleSettings, options.ruleName); |
| 36 | |
| 37 | if (!settings) { |
| 38 | return; |
| 39 | } |
| 40 | |
| 41 | const tmpPostcssResult = new Result(); |
| 42 | |
| 43 | rules[options.ruleName](settings[0], settings[1], {})(options.root, tmpPostcssResult); |
| 44 | tmpPostcssResult.warnings().forEach(callback); |
| 45 | }; |