reportDisables.js 2.0 KB

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