/
reportUnknownRuleNames.js
76 lines (62 loc) · 1.84 KB
/
reportUnknownRuleNames.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
'use strict';
const levenshtein = require('fastest-levenshtein');
const rules = require('./rules');
const MAX_LEVENSHTEIN_DISTANCE = 6;
const MAX_SUGGESTIONS_COUNT = 3;
/**
* @param {string} ruleName
* @return {string[]}
*/
function extractSuggestions(ruleName) {
const suggestions = Array.from({ length: MAX_LEVENSHTEIN_DISTANCE });
for (let i = 0; i < suggestions.length; i++) {
suggestions[i] = [];
}
Object.keys(rules).forEach((existRuleName) => {
const distance = levenshtein.distance(existRuleName, ruleName);
if (distance <= MAX_LEVENSHTEIN_DISTANCE) {
suggestions[distance - 1].push(existRuleName);
}
});
/** @type {string[]} */
let result = [];
for (let i = 0; i < suggestions.length; i++) {
if (suggestions[i].length > 0) {
if (i < 3) {
return suggestions[i].slice(0, MAX_SUGGESTIONS_COUNT);
}
result = result.concat(suggestions[i]);
}
}
return result.slice(0, MAX_SUGGESTIONS_COUNT);
}
/**
* @param {string} ruleName
* @param {string[]} [suggestions=[]]
* @return {string}
*/
function rejectMessage(ruleName, suggestions = []) {
return `Unknown rule ${ruleName}.${
suggestions.length > 0 ? ` Did you mean ${suggestions.join(', ')}?` : ''
}`;
}
/** @type {Map<string, string[]>} */
const cache = new Map();
/**
* @param {string} unknownRuleName
* @param {import('postcss').Root} postcssRoot
* @param {import('stylelint').PostcssResult} postcssResult
* @returns {void}
*/
module.exports = function reportUnknownRuleNames(unknownRuleName, postcssRoot, postcssResult) {
const suggestions = cache.has(unknownRuleName)
? /** @type {string[]} */ (cache.get(unknownRuleName))
: extractSuggestions(unknownRuleName);
cache.set(unknownRuleName, suggestions);
postcssResult.warn(rejectMessage(unknownRuleName, suggestions), {
severity: 'error',
rule: unknownRuleName,
node: postcssRoot,
index: 0,
});
};