forked from eslint-community/eslint-plugin-eslint-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprefer-replace-text.js
79 lines (70 loc) · 2.31 KB
/
prefer-replace-text.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
/**
* @fileoverview prefer using `replaceText()` instead of `replaceTextRange()`
* @author 薛定谔的猫<[email protected]>
*/
'use strict';
const utils = require('../utils');
// ------------------------------------------------------------------------------
// Rule Definition
// ------------------------------------------------------------------------------
module.exports = {
meta: {
type: 'suggestion',
docs: {
description: 'require using `replaceText()` instead of `replaceTextRange()`',
category: 'Rules',
recommended: false,
url: 'https://github.com/not-an-aardvark/eslint-plugin-eslint-plugin/tree/HEAD/docs/rules/prefer-replace-text.md',
},
fixable: null,
schema: [],
messages: {
useReplaceText: 'Use replaceText instead of replaceTextRange.',
},
},
create (context) {
const sourceCode = context.getSourceCode();
let funcInfo = {
upper: null,
codePath: null,
shouldCheck: false,
node: null,
};
let contextIdentifiers;
return {
Program (node) {
contextIdentifiers = utils.getContextIdentifiers(context, node);
},
// Stacks this function's information.
onCodePathStart (codePath, node) {
funcInfo = {
upper: funcInfo,
codePath,
shouldCheck: utils.isAutoFixerFunction(node, contextIdentifiers) || utils.isSuggestionFixerFunction(node, contextIdentifiers),
node,
};
},
// Pops this function's information.
onCodePathEnd () {
funcInfo = funcInfo.upper;
},
// Checks the replaceTextRange arguments.
'CallExpression[arguments.length=2]' (node) {
if (funcInfo.shouldCheck &&
node.callee.type === 'MemberExpression' &&
node.callee.property.name === 'replaceTextRange') {
const arg = node.arguments[0];
const isIdenticalNodeRange = arg.type === 'ArrayExpression' &&
arg.elements[0].type === 'MemberExpression' && arg.elements[1].type === 'MemberExpression' &&
sourceCode.getText(arg.elements[0].object) === sourceCode.getText(arg.elements[1].object);
if (isIdenticalNodeRange) {
context.report({
node,
messageId: 'useReplaceText',
});
}
}
},
};
},
};