reportDisables.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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 reportDisables(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. endLine: range.comment.source.end && range.comment.source.end.line,
  40. endColumn: range.comment.source.end && range.comment.source.end.column,
  41. severity: 'error',
  42. });
  43. }
  44. }
  45. }
  46. };
  47. /**
  48. * @param {StylelintConfigRuleSettings} options
  49. * @return {boolean}
  50. */
  51. function reportDisablesForRule(options) {
  52. if (!options || !options[1]) return false;
  53. return Boolean(options[1].reportDisables);
  54. }