preprocessWarnings.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. 'use strict';
  2. /** @typedef {import('stylelint').LintResult} LintResult */
  3. /** @typedef {LintResult['parseErrors'][0]} ParseError */
  4. /** @typedef {LintResult['warnings'][0]} Warning */
  5. /** @typedef {Warning['severity']} Severity */
  6. /**
  7. * Preprocess warnings in a given lint result.
  8. * Note that this function has a side-effect.
  9. *
  10. * @param {LintResult} result
  11. * @returns {LintResult}
  12. */
  13. module.exports = function preprocessWarnings(result) {
  14. for (const error of result.parseErrors || []) {
  15. result.warnings.push(parseErrorToWarning(error));
  16. }
  17. for (const warning of result.warnings) {
  18. warning.severity = normalizeSeverity(warning);
  19. }
  20. result.warnings.sort(byLocationOrder);
  21. return result;
  22. };
  23. /**
  24. * @param {ParseError} error
  25. * @returns {Warning}
  26. */
  27. function parseErrorToWarning(error) {
  28. return {
  29. line: error.line,
  30. column: error.column,
  31. rule: error.stylelintType,
  32. severity: 'error',
  33. text: `${error.text} (${error.stylelintType})`,
  34. };
  35. }
  36. /**
  37. * @param {Warning} warning
  38. * @returns {Severity}
  39. */
  40. function normalizeSeverity(warning) {
  41. // NOTE: Plugins may add a warning without severity, for example,
  42. // by directly using the PostCSS `Result#warn()` API.
  43. return warning.severity || 'error';
  44. }
  45. /**
  46. * @param {Warning} a
  47. * @param {Warning} b
  48. * @returns {number}
  49. */
  50. function byLocationOrder(a, b) {
  51. // positionless first
  52. if (!a.line && b.line) return -1;
  53. // positionless first
  54. if (a.line && !b.line) return 1;
  55. if (a.line < b.line) return -1;
  56. if (a.line > b.line) return 1;
  57. if (a.column < b.column) return -1;
  58. if (a.column > b.column) return 1;
  59. return 0;
  60. }