reportDisables.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. 'use strict';
  2. /** @typedef {import('stylelint').RangeType} RangeType */
  3. /** @typedef {import('stylelint').DisableReportRange} DisabledRange */
  4. /** @typedef {import('stylelint').LintResult} StylelintResult */
  5. /** @typedef {import('stylelint').ConfigRuleSettings<any, Object>} StylelintConfigRuleSettings */
  6. /**
  7. * Returns a report describing which `results` (if any) contain disabled ranges
  8. * for rules that disallow disables via `reportDisables: true`.
  9. *
  10. * @param {StylelintResult[]} results
  11. */
  12. module.exports = function (results) {
  13. for (const result of results) {
  14. // File with `CssSyntaxError` don't have `_postcssResult`s.
  15. if (!result._postcssResult) {
  16. continue;
  17. }
  18. /** @type {{[ruleName: string]: Array<RangeType>}} */
  19. const rangeData = result._postcssResult.stylelint.disabledRanges;
  20. if (!rangeData) continue;
  21. const config = result._postcssResult.stylelint.config;
  22. if (!config || !config.rules) continue;
  23. // If no rules actually disallow disables, don't bother looking for ranges
  24. // that correspond to disabled rules.
  25. if (!Object.values(config.rules).some((rule) => reportDisablesForRule(rule))) {
  26. continue;
  27. }
  28. for (const [rule, ranges] of Object.entries(rangeData)) {
  29. for (const range of ranges) {
  30. if (!reportDisablesForRule(config.rules[rule] || [])) continue;
  31. // If the comment doesn't have a location, we can't report a useful error.
  32. // In practice we expect all comments to have locations, though.
  33. if (!range.comment.source || !range.comment.source.start) continue;
  34. result.warnings.push({
  35. text: `Rule "${rule}" may not be disabled`,
  36. rule: 'reportDisables',
  37. line: range.comment.source.start.line,
  38. column: range.comment.source.start.column,
  39. severity: 'error',
  40. });
  41. }
  42. }
  43. }
  44. };
  45. /**
  46. * @param {StylelintConfigRuleSettings} options
  47. * @return {boolean}
  48. */
  49. function reportDisablesForRule(options) {
  50. if (!options || !options[1]) return false;
  51. return Boolean(options[1].reportDisables);
  52. }