UNPKG

2.59 kBJavaScriptView Raw
1'use strict';
2
3const _ = require('lodash');
4
5/** @typedef {{
6 ruleName: string,
7 result: import('stylelint').PostcssResult,
8 message: string,
9 node: import('postcss').Node & {
10 positionBy(opts: { index?: number, word?: string }): { line: number, column: number }
11 },
12 index?: number,
13 word?: string,
14 line?: number
15}} Violation */
16
17/**
18 * Report a violation.
19 *
20 * This function accounts for `disabledRanges` attached to the result.
21 * That is, if the reported violation is within a disabledRange,
22 * it is ignored. Otherwise, it is attached to the result as a
23 * postcss warning.
24 *
25 * It also accounts for the rule's severity.
26 *
27 * You *must* pass *either* a node or a line number.
28 * @param {Violation} violation
29 */
30module.exports = function (violation) {
31 const ruleName = violation.ruleName;
32 const result = violation.result;
33 const message = violation.message;
34 const line = violation.line;
35 const node = violation.node;
36 const index = violation.index;
37 const word = violation.word;
38
39 result.stylelint = result.stylelint || {
40 ruleSeverities: {},
41 customMessages: {},
42 };
43
44 // In quiet mode, mere warnings are ignored
45 if (result.stylelint.quiet && result.stylelint.ruleSeverities[ruleName] !== 'error') {
46 return;
47 }
48
49 // If a line is not passed, use the node.positionBy method to get the
50 // line number that the complaint pertains to
51 const startLine = line || node.positionBy({ index }).line;
52
53 if (result.stylelint.disabledRanges && !result.stylelint.ignoreDisables) {
54 const ranges = result.stylelint.disabledRanges[ruleName] || result.stylelint.disabledRanges.all;
55
56 for (const range of ranges) {
57 if (
58 // If the violation is within a disabledRange,
59 // and that disabledRange's rules include this one,
60 // do not register a warning
61 range.start <= startLine &&
62 (range.end === undefined || range.end >= startLine) &&
63 (!range.rules || range.rules.includes(ruleName))
64 ) {
65 return;
66 }
67 }
68 }
69
70 /** @type {string} */
71 const severity = _.get(result.stylelint, ['ruleSeverities', ruleName], 'ignore');
72
73 if (!result.stylelint.stylelintError && severity === 'error') {
74 result.stylelint.stylelintError = true;
75 }
76
77 /** @type {import('stylelint').StylelintWarningOptions} */
78 const warningProperties = {
79 severity,
80 rule: ruleName,
81 };
82
83 if (node) {
84 warningProperties.node = node;
85 }
86
87 if (index) {
88 warningProperties.index = index;
89 }
90
91 if (word) {
92 warningProperties.word = word;
93 }
94
95 const warningMessage = _.get(result.stylelint, ['customMessages', ruleName], message);
96
97 result.warn(warningMessage, warningProperties);
98};