forked from sindresorhus/eslint-plugin-unicorn
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
prefer-disallow-over-forbid.js
92 lines (79 loc) · 1.96 KB
/
prefer-disallow-over-forbid.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
'use strict';
const path = require('node:path');
const {matches} = require('../../rules/selectors/index.js');
const toLocation = require('../../rules/utils/to-location.js');
const messageId = path.basename(__filename, '.js');
const messageSelector = [
matches([
// `const messages = {...}`;
[
'VariableDeclarator',
'[id.type="Identifier"]',
'[id.name="messages"]',
],
// `{meta: {messages = {...}}}`;
[
'Property',
'[key.type="Identifier"]',
'[key.name="messages"]',
],
]),
' > ',
'ObjectExpression.init',
' > ',
'Property.properties',
' > ',
'Literal.value',
].join('');
const descriptionSelector = [
'Property',
'[computed!=true]',
' > ',
'Literal.value',
].join('');
const selector = matches([messageSelector, descriptionSelector]);
const words = [
{word: 'forbid', replacement: 'disallow'},
{word: 'forbidden', replacement: 'disallowed'},
];
module.exports = {
create(context) {
return {
[selector](node) {
const {value} = node;
if (typeof value !== 'string') {
return;
}
const message = node.raw.slice(1, -1);
const lowerCased = message.toLowerCase();
for (let {word, replacement} of words) {
const index = lowerCased.indexOf(word);
if (index === -1) {
continue;
}
const original = message.slice(index, index + word.length);
if (/^[A-Z]/.test(original)) {
replacement = replacement[0].toUpperCase() + replacement.slice(1);
}
const start = node.range[0] + index + 1;
const range = [start, start + word.length];
context.report({
node,
loc: toLocation(range, context.getSourceCode()),
messageId,
data: {original, replacement},
fix: fixer => fixer.replaceTextRange(range, replacement),
});
// Only report one problem
return;
}
},
};
},
meta: {
fixable: 'code',
messages: {
[messageId]: 'Prefer use `{{replacement}}` over `{{original}}` in error message and rule description.',
},
},
};