|
| 1 | +/** |
| 2 | + * @fileoverview prefer using replaceText instead of replaceTextRange. |
| 3 | + * @author 薛定谔的猫<[email protected]> |
| 4 | + */ |
| 5 | + |
| 6 | +'use strict'; |
| 7 | + |
| 8 | +const utils = require('../utils'); |
| 9 | + |
| 10 | +// ------------------------------------------------------------------------------ |
| 11 | +// Rule Definition |
| 12 | +// ------------------------------------------------------------------------------ |
| 13 | + |
| 14 | +module.exports = { |
| 15 | + meta: { |
| 16 | + docs: { |
| 17 | + description: 'prefer using replaceText instead of replaceTextRange.', |
| 18 | + category: 'Rules', |
| 19 | + recommended: false, |
| 20 | + }, |
| 21 | + fixable: 'code', |
| 22 | + schema: [], |
| 23 | + }, |
| 24 | + |
| 25 | + create (context) { |
| 26 | + const sourceCode = context.getSourceCode(); |
| 27 | + const message = 'prefer using replaceText instead of replaceTextRange.'; |
| 28 | + let funcInfo = { |
| 29 | + upper: null, |
| 30 | + codePath: null, |
| 31 | + shouldCheck: false, |
| 32 | + node: null, |
| 33 | + }; |
| 34 | + let contextIdentifiers; |
| 35 | + |
| 36 | + return { |
| 37 | + Program (node) { |
| 38 | + contextIdentifiers = utils.getContextIdentifiers(context, node); |
| 39 | + }, |
| 40 | + |
| 41 | + // Stacks this function's information. |
| 42 | + onCodePathStart (codePath, node) { |
| 43 | + const parent = node.parent; |
| 44 | + const shouldCheck = node.type === 'FunctionExpression' && |
| 45 | + parent.parent.type === 'ObjectExpression' && |
| 46 | + parent.parent.parent.type === 'CallExpression' && |
| 47 | + contextIdentifiers.has(parent.parent.parent.callee.object) && |
| 48 | + parent.parent.parent.callee.property.name === 'report' && |
| 49 | + utils.getReportInfo(parent.parent.parent.arguments).fix === node; |
| 50 | + |
| 51 | + funcInfo = { |
| 52 | + upper: funcInfo, |
| 53 | + codePath, |
| 54 | + shouldCheck, |
| 55 | + node, |
| 56 | + }; |
| 57 | + }, |
| 58 | + |
| 59 | + // Pops this function's information. |
| 60 | + onCodePathEnd () { |
| 61 | + funcInfo = funcInfo.upper; |
| 62 | + }, |
| 63 | + |
| 64 | + // Checks the return statement is valid. |
| 65 | + 'CallExpression[arguments.length>1]' (node) { |
| 66 | + if (funcInfo.shouldCheck && |
| 67 | + node.callee.property.name === 'replaceTextRange') { |
| 68 | + const arg = node.arguments[0]; |
| 69 | + if ((arg.type === 'MemberExpression' && arg.property.name === 'range') |
| 70 | + || ( |
| 71 | + arg.type === 'ArrayExpression' && arg.elements.length === 2 && |
| 72 | + arg.elements[0].type === 'MemberExpression' && arg.elements[0].type === 'MemberExpression' && sourceCode.getText(arg.elements[0].object) === sourceCode.getText(arg.elements[1].object)) |
| 73 | + ) { |
| 74 | + context.report({ |
| 75 | + node, |
| 76 | + message, |
| 77 | + }); |
| 78 | + } |
| 79 | + } |
| 80 | + }, |
| 81 | + }; |
| 82 | + }, |
| 83 | +}; |
0 commit comments