-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
prefer-ast-types-enum.ts
executable file
·74 lines (66 loc) · 1.99 KB
/
prefer-ast-types-enum.ts
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
import {
AST_NODE_TYPES,
AST_TOKEN_TYPES,
TSESTree,
} from '@typescript-eslint/experimental-utils';
import { DefinitionType } from '@typescript-eslint/scope-manager';
import { createRule } from '../util';
const isStringLiteral = (
node: TSESTree.Literal,
): node is TSESTree.StringLiteral => typeof node.value === 'string';
export default createRule({
name: __filename,
meta: {
type: 'problem',
docs: {
recommended: 'error',
description:
'Ensures consistent usage of `AST_NODE_TYPES`, `AST_TOKEN_TYPES` and `DefinitionType` enums.',
},
messages: {
preferEnum: 'Prefer {{ enumName }}.{{ literal }} over raw literal',
},
fixable: 'code',
schema: [],
},
defaultOptions: [],
create(context) {
const report = (
enumName: 'AST_NODE_TYPES' | 'AST_TOKEN_TYPES' | 'DefinitionType',
literal: TSESTree.StringLiteral,
): void =>
context.report({
data: { enumName, literal: literal.value },
messageId: 'preferEnum',
node: literal,
fix: fixer =>
fixer.replaceText(literal, `${enumName}.${literal.value}`),
});
return {
Literal(node: TSESTree.Literal): void {
if (
node.parent?.type === AST_NODE_TYPES.TSEnumMember &&
node.parent.parent?.type === AST_NODE_TYPES.TSEnumDeclaration &&
['AST_NODE_TYPES', 'AST_TOKEN_TYPES', 'DefinitionType'].includes(
node.parent.parent.id.name,
)
) {
return;
}
if (!isStringLiteral(node)) {
return;
}
const value = node.value;
if (Object.prototype.hasOwnProperty.call(AST_NODE_TYPES, value)) {
report('AST_NODE_TYPES', node);
}
if (Object.prototype.hasOwnProperty.call(AST_TOKEN_TYPES, value)) {
report('AST_TOKEN_TYPES', node);
}
if (Object.prototype.hasOwnProperty.call(DefinitionType, value)) {
report('DefinitionType', node);
}
},
};
},
});