-
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
member-naming.ts
99 lines (90 loc) · 2.4 KB
/
member-naming.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import { TSESTree } from '@typescript-eslint/experimental-utils';
import * as util from '../util';
interface Config<T = string> {
private?: T;
protected?: T;
public?: T;
}
type Modifiers = keyof Config;
type Options = [Config];
type MessageIds = 'incorrectName';
export default util.createRule<Options, MessageIds>({
name: 'member-naming',
meta: {
type: 'suggestion',
docs: {
description:
'Enforces naming conventions for class members by visibility',
category: 'Stylistic Issues',
recommended: false,
},
messages: {
incorrectName:
'{{accessibility}} property {{name}} should match {{convention}}.',
},
schema: [
{
type: 'object',
properties: {
public: {
type: 'string',
minLength: 1,
format: 'regex',
},
protected: {
type: 'string',
minLength: 1,
format: 'regex',
},
private: {
type: 'string',
minLength: 1,
format: 'regex',
},
},
additionalProperties: false,
minProperties: 1,
},
],
},
defaultOptions: [{}],
create(context, [config]) {
const sourceCode = context.getSourceCode();
const conventions = (Object.keys(config) as Modifiers[]).reduce<
Config<RegExp>
>((acc, accessibility) => {
acc[accessibility] = new RegExp(config[accessibility]!);
return acc;
}, {});
/**
* Check that the property name matches the convention for its
* accessibility.
* @param {ASTNode} node the named node to evaluate.
* @returns {void}
* @private
*/
function validateName(
node: TSESTree.MethodDefinition | TSESTree.ClassProperty,
): void {
const name = util.getNameFromClassMember(node, sourceCode);
const accessibility: Modifiers = node.accessibility || 'public';
const convention = conventions[accessibility];
const method = node as TSESTree.MethodDefinition;
if (method.kind === 'constructor') {
return;
}
if (!convention || convention.test(name)) {
return;
}
context.report({
node: node.key,
messageId: 'incorrectName',
data: { accessibility, name, convention },
});
}
return {
MethodDefinition: validateName,
ClassProperty: validateName,
};
},
});