reportDisables.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. 'use strict';
  2. const _ = require('lodash');
  3. /** @typedef {import('stylelint').RangeType} RangeType */
  4. /** @typedef {import('stylelint').DisableReportRange} DisabledRange */
  5. /** @typedef {import('stylelint').StylelintDisableOptionsReport} StylelintDisableOptionsReport */
  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 {import('stylelint').StylelintResult[]} results
  11. * @returns {StylelintDisableOptionsReport}
  12. */
  13. module.exports = function (results) {
  14. /** @type {StylelintDisableOptionsReport} */
  15. const report = [];
  16. results.forEach((result) => {
  17. // File with `CssSyntaxError` don't have `_postcssResult`s.
  18. if (!result._postcssResult) {
  19. return;
  20. }
  21. /** @type {{ranges: DisabledRange[], source: string}} */
  22. const reported = { source: result.source || '', ranges: [] };
  23. /** @type {{[ruleName: string]: Array<RangeType>}} */
  24. const rangeData = result._postcssResult.stylelint.disabledRanges;
  25. if (!rangeData) return;
  26. const config = result._postcssResult.stylelint.config;
  27. // If no rules actually disallow disables, don't bother looking for ranges
  28. // that correspond to disabled rules.
  29. if (!Object.values(_.get(config, 'rules', {})).some(reportDisablesForRule)) {
  30. return [];
  31. }
  32. Object.keys(rangeData).forEach((rule) => {
  33. rangeData[rule].forEach((range) => {
  34. if (!reportDisablesForRule(_.get(config, ['rules', rule], []))) return;
  35. reported.ranges.push({
  36. rule,
  37. start: range.start,
  38. end: range.end,
  39. unusedRule: rule,
  40. });
  41. });
  42. });
  43. reported.ranges = _.sortBy(reported.ranges, ['start', 'end']);
  44. report.push(reported);
  45. });
  46. return report;
  47. };
  48. /**
  49. * @param {[any, object]|null} options
  50. * @return {boolean}
  51. */
  52. function reportDisablesForRule(options) {
  53. if (!options) return false;
  54. return _.get(options[1], 'reportDisables', false);
  55. }