1 | 'use strict';
|
2 |
|
3 | const _ = require('lodash');
|
4 | const optionsMatches = require('./utils/optionsMatches');
|
5 | const putIfAbsent = require('./utils/putIfAbsent');
|
6 | const validateDisableSettings = require('./validateDisableSettings');
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 | module.exports = function (results) {
|
17 | results.forEach((result) => {
|
18 | const settings = validateDisableSettings(result._postcssResult, 'reportNeedlessDisables');
|
19 |
|
20 | if (!settings) return;
|
21 |
|
22 | const [enabled, options, stylelintResult] = settings;
|
23 |
|
24 |
|
25 | const rangeData = _.cloneDeep(stylelintResult.disabledRanges);
|
26 |
|
27 | if (!rangeData) return;
|
28 |
|
29 | const disabledWarnings = stylelintResult.disabledWarnings || [];
|
30 |
|
31 |
|
32 |
|
33 |
|
34 |
|
35 |
|
36 |
|
37 | const usefulDisables = new Map();
|
38 |
|
39 | for (const warning of disabledWarnings) {
|
40 | const rule = warning.rule;
|
41 | const ruleRanges = rangeData[rule];
|
42 |
|
43 | if (ruleRanges) {
|
44 | for (const range of ruleRanges) {
|
45 | if (isWarningInRange(warning, range)) {
|
46 | putIfAbsent(usefulDisables, range.comment, () => new Set()).add(rule);
|
47 | }
|
48 | }
|
49 | }
|
50 |
|
51 | for (const range of rangeData.all) {
|
52 | if (isWarningInRange(warning, range)) {
|
53 | putIfAbsent(usefulDisables, range.comment, () => new Set()).add(rule);
|
54 | }
|
55 | }
|
56 | }
|
57 |
|
58 | const rangeEntries = Object.entries(rangeData);
|
59 |
|
60 |
|
61 |
|
62 | for (const range of rangeData.all) {
|
63 | for (const [rule, ranges] of rangeEntries) {
|
64 | if (rule === 'all') continue;
|
65 |
|
66 | _.remove(ranges, (otherRange) => range.comment === otherRange.comment);
|
67 | }
|
68 | }
|
69 |
|
70 | for (const [rule, ranges] of rangeEntries) {
|
71 | for (const range of ranges) {
|
72 | if (enabled === optionsMatches(options, 'except', rule)) continue;
|
73 |
|
74 | const useful = usefulDisables.get(range.comment) || new Set();
|
75 |
|
76 |
|
77 |
|
78 |
|
79 | if (rule === 'all' ? useful.size !== 0 : useful.has(rule)) continue;
|
80 |
|
81 |
|
82 |
|
83 | if (!range.comment.source || !range.comment.source.start) continue;
|
84 |
|
85 | result.warnings.push({
|
86 | text: `Needless disable for "${rule}"`,
|
87 | rule: '--report-needless-disables',
|
88 | line: range.comment.source.start.line,
|
89 | column: range.comment.source.start.column,
|
90 | severity: options.severity,
|
91 | });
|
92 | }
|
93 | }
|
94 | });
|
95 | };
|
96 |
|
97 |
|
98 |
|
99 |
|
100 |
|
101 |
|
102 | function isWarningInRange(warning, range) {
|
103 | const line = warning.line;
|
104 |
|
105 |
|
106 | return (
|
107 | range.start <= line &&
|
108 | ((range.end !== undefined && range.end >= line) || range.end === undefined)
|
109 | );
|
110 | }
|