forked from desktop/desktop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreact-readonly-props-and-state.js
85 lines (76 loc) · 2.25 KB
/
react-readonly-props-and-state.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
// @ts-check
/**
* react-readonly-props-and-state
*
* This custom eslint rule is highly specific to GitHub Desktop and attempts
* to prevent props and state interfaces from being declared with mutable
* members.
*
* While it's technically possible to modify this.props there's never a good
* reason to do so and marking our interfaces as read only ensures that we
* get compiler support for that fact.
*/
/**
* @typedef {import('@typescript-eslint/experimental-utils').TSESLint.RuleModule} RuleModule
* @typedef {import("@typescript-eslint/typescript-estree").TSESTree.TSInterfaceBody} TSInterfaceBody
*/
/** @type {RuleModule} */
module.exports = {
meta: {
type: 'problem',
messages: {
signaturesShouldBeReadonly: `Property and state signatures should be read-only`,
arraySignaturesShouldBeReadonly: `Prop and State arrays should be read only (ReadOnlyArray)`,
},
fixable: 'code',
schema: [],
},
create: function (context) {
const filename = context.getFilename()
if (filename.toLowerCase().endsWith('ts')) {
return {}
}
const sourceCode = context.getSourceCode()
/**
* Check each member of the interface body and ensure it is marked `readonly`.
*
* @param {TSInterfaceBody} body
*/
function ensureReadOnly(body) {
body.body.forEach(member => {
if (member.type !== 'TSPropertySignature') {
return
}
const isReadOnly = member.readonly || false
if (!isReadOnly) {
context.report({
node: member,
messageId: 'signaturesShouldBeReadonly',
})
}
if (member.typeAnnotation) {
const typeString = sourceCode.getText(member.typeAnnotation)
if (
/^\: \s*Array<.*>$/.test(typeString) ||
typeString.endsWith('[]')
) {
context.report({
node: member,
messageId: 'arraySignaturesShouldBeReadonly',
})
}
}
})
}
return {
TSInterfaceDeclaration(node) {
if (node.id.name.endsWith('Props')) {
ensureReadOnly(node.body)
}
if (node.id.name.endsWith('State')) {
ensureReadOnly(node.body)
}
},
}
},
}