From d6e9059b01a5220321ddfca8506b7c19cbcbe1a7 Mon Sep 17 00:00:00 2001 From: Jordan Harband Date: Sat, 18 May 2024 20:14:55 -0700 Subject: [PATCH] [Refactor] `context.getSource` -> `sourceCode.getText` --- lib/rules/boolean-prop-naming.js | 9 ++++++--- lib/rules/destructuring-assignment.js | 4 ++-- lib/rules/forbid-elements.js | 6 +++--- lib/rules/forbid-prop-types.js | 4 ++-- lib/rules/function-component-definition.js | 5 ++--- lib/rules/hook-use-state.js | 4 ++-- lib/rules/jsx-curly-brace-presence.js | 14 +++++++------- lib/rules/jsx-curly-newline.js | 11 ++++++----- lib/rules/jsx-fragments.js | 18 ++++++++---------- lib/rules/jsx-handler-names.js | 10 +++++----- lib/rules/jsx-indent-props.js | 4 ++-- lib/rules/jsx-indent.js | 9 ++++++--- lib/rules/jsx-key.js | 4 ++-- lib/rules/jsx-max-props-per-line.js | 9 ++++----- lib/rules/jsx-newline.js | 11 ++++------- lib/rules/jsx-no-comment-textnodes.js | 4 ++-- lib/rules/jsx-no-leaked-render.js | 9 ++++----- lib/rules/jsx-no-literals.js | 4 ++-- lib/rules/jsx-no-useless-fragment.js | 4 ++-- lib/rules/jsx-one-expression-per-line.js | 9 ++++++--- lib/rules/jsx-props-no-multi-spaces.js | 9 ++++++--- lib/rules/jsx-sort-default-props.js | 4 ++-- lib/rules/jsx-sort-props.js | 8 +++++--- lib/rules/jsx-wrap-multilines.js | 15 +++++++++------ lib/rules/no-arrow-function-lifecycle.js | 15 +++++++++------ lib/rules/no-deprecated.js | 4 ++-- lib/rules/no-unknown-property.js | 4 ++-- lib/rules/prefer-exact-props.js | 5 ++--- lib/rules/prefer-stateless-function.js | 4 ++-- lib/rules/sort-default-props.js | 4 ++-- lib/rules/sort-prop-types.js | 7 +++++-- lib/util/Components.js | 5 ++--- lib/util/componentUtil.js | 4 ++-- lib/util/defaultProps.js | 6 ++---- lib/util/eslint.js | 7 +++++++ lib/util/propTypes.js | 5 +++-- lib/util/propTypesSort.js | 9 ++++++--- 37 files changed, 145 insertions(+), 122 deletions(-) diff --git a/lib/rules/boolean-prop-naming.js b/lib/rules/boolean-prop-naming.js index 78ed249805..f64da93242 100644 --- a/lib/rules/boolean-prop-naming.js +++ b/lib/rules/boolean-prop-naming.js @@ -13,7 +13,10 @@ const propsUtil = require('../util/props'); const docsUrl = require('../util/docsUrl'); const propWrapperUtil = require('../util/propWrapper'); const report = require('../util/report'); -const getSourceCode = require('../util/eslint').getSourceCode; +const eslintUtil = require('../util/eslint'); + +const getSourceCode = eslintUtil.getSourceCode; +const getText = eslintUtil.getText; // ------------------------------------------------------------------------------ // Rule Definition @@ -309,7 +312,7 @@ module.exports = { && node.value.type === 'CallExpression' && propWrapperUtil.isPropWrapperFunction( context, - getSourceCode(context).getText(node.value.callee) + getText(context, node.value.callee) ) ) { checkPropWrapperArguments(node, node.value.arguments); @@ -335,7 +338,7 @@ module.exports = { right.type === 'CallExpression' && propWrapperUtil.isPropWrapperFunction( context, - getSourceCode(context).getText(right.callee) + getText(context, right.callee) ) ) { checkPropWrapperArguments(component.node, right.arguments); diff --git a/lib/rules/destructuring-assignment.js b/lib/rules/destructuring-assignment.js index 40f3a0ac1f..9cac8d5889 100644 --- a/lib/rules/destructuring-assignment.js +++ b/lib/rules/destructuring-assignment.js @@ -10,7 +10,7 @@ const eslintUtil = require('../util/eslint'); const isAssignmentLHS = require('../util/ast').isAssignmentLHS; const report = require('../util/report'); -const getSourceCode = eslintUtil.getSourceCode; +const getText = eslintUtil.getText; const DEFAULT_OPTION = 'always'; @@ -272,7 +272,7 @@ module.exports = { param.typeAnnotation ? param.typeAnnotation.range[0] : param.range[1], ]; return [ - fixer.replaceTextRange(replaceRange, getSourceCode(context).getText(node.id)), + fixer.replaceTextRange(replaceRange, getText(context, node.id)), fixer.remove(node.parent), ]; }, diff --git a/lib/rules/forbid-elements.js b/lib/rules/forbid-elements.js index 8170aaf380..dd3ffa8f5d 100644 --- a/lib/rules/forbid-elements.js +++ b/lib/rules/forbid-elements.js @@ -7,7 +7,7 @@ const has = require('object.hasown/polyfill')(); const docsUrl = require('../util/docsUrl'); -const getSourceCode = require('../util/eslint').getSourceCode; +const getText = require('../util/eslint').getText; const isCreateElement = require('../util/isCreateElement'); const report = require('../util/report'); @@ -91,7 +91,7 @@ module.exports = { return { JSXOpeningElement(node) { - reportIfForbidden(getSourceCode(context).getText(node.name), node.name); + reportIfForbidden(getText(context, node.name), node.name); }, CallExpression(node) { @@ -111,7 +111,7 @@ module.exports = { } else if (argType === 'Literal' && /^[a-z][^.]*$/.test(argument.value)) { reportIfForbidden(argument.value, argument); } else if (argType === 'MemberExpression') { - reportIfForbidden(getSourceCode(context).getText(argument), argument); + reportIfForbidden(getText(context, argument), argument); } }, }; diff --git a/lib/rules/forbid-prop-types.js b/lib/rules/forbid-prop-types.js index 8161d6b45d..89f5c4b2d8 100644 --- a/lib/rules/forbid-prop-types.js +++ b/lib/rules/forbid-prop-types.js @@ -10,7 +10,7 @@ const astUtil = require('../util/ast'); const docsUrl = require('../util/docsUrl'); const propWrapperUtil = require('../util/propWrapper'); const report = require('../util/report'); -const getSourceCode = require('../util/eslint').getSourceCode; +const getText = require('../util/eslint').getText; // ------------------------------------------------------------------------------ // Constants @@ -172,7 +172,7 @@ module.exports = { case 'CallExpression': { const innerNode = node.arguments && node.arguments[0]; if ( - propWrapperUtil.isPropWrapperFunction(context, getSourceCode(context).getText(node.callee)) + propWrapperUtil.isPropWrapperFunction(context, getText(context, node.callee)) && innerNode ) { checkNode(innerNode); diff --git a/lib/rules/function-component-definition.js b/lib/rules/function-component-definition.js index 9f2c3b6fb2..24ad3f48d7 100644 --- a/lib/rules/function-component-definition.js +++ b/lib/rules/function-component-definition.js @@ -9,7 +9,7 @@ const arrayIncludes = require('array-includes'); const Components = require('../util/Components'); const docsUrl = require('../util/docsUrl'); const reportC = require('../util/report'); -const getSourceCode = require('../util/eslint').getSourceCode; +const getText = require('../util/eslint').getText; // ------------------------------------------------------------------------------ // Rule Definition @@ -182,8 +182,7 @@ module.exports = { ); function getFixer(node, options) { - const sourceCode = getSourceCode(context); - const source = sourceCode.getText(); + const source = getText(context); const typeAnnotation = getTypeAnnotation(node, source); diff --git a/lib/rules/hook-use-state.js b/lib/rules/hook-use-state.js index a0c46e338e..938802d82b 100644 --- a/lib/rules/hook-use-state.js +++ b/lib/rules/hook-use-state.js @@ -9,7 +9,7 @@ const Components = require('../util/Components'); const docsUrl = require('../util/docsUrl'); const report = require('../util/report'); const getMessageData = require('../util/message'); -const getSourceCode = require('../util/eslint').getSourceCode; +const getText = require('../util/eslint').getText; // ------------------------------------------------------------------------------ // Rule Definition @@ -168,7 +168,7 @@ module.exports = { // Convert useState call to useMemo + arrow function + dependency array fixer.replaceTextRange( node.range, - `${useMemoCode}(() => ${getSourceCode(context).getText(node.arguments[0])}, [])` + `${useMemoCode}(() => ${getText(context, node.arguments[0])}, [])` ), ].filter(Boolean), } diff --git a/lib/rules/jsx-curly-brace-presence.js b/lib/rules/jsx-curly-brace-presence.js index 64be524499..083a60a0e3 100755 --- a/lib/rules/jsx-curly-brace-presence.js +++ b/lib/rules/jsx-curly-brace-presence.js @@ -11,7 +11,10 @@ const arrayIncludes = require('array-includes'); const docsUrl = require('../util/docsUrl'); const jsxUtil = require('../util/jsx'); const report = require('../util/report'); -const getSourceCode = require('../util/eslint').getSourceCode; +const eslintUtil = require('../util/eslint'); + +const getSourceCode = eslintUtil.getSourceCode; +const getText = eslintUtil.getText; // ------------------------------------------------------------------------------ // Constants @@ -177,8 +180,7 @@ module.exports = { let textToReplace; if (jsxUtil.isJSX(expression)) { - const sourceCode = getSourceCode(context); - textToReplace = sourceCode.getText(expression); + textToReplace = getText(context, expression); } else { const expressionType = expression && expression.type; const parentType = JSXExpressionNode.parent.type; @@ -189,9 +191,7 @@ module.exports = { : expression.raw.slice(1, -1) }"`; } else if (jsxUtil.isJSX(expression)) { - const sourceCode = getSourceCode(context); - - textToReplace = sourceCode.getText(expression); + textToReplace = getText(context, expression); } else { textToReplace = expressionType === 'TemplateLiteral' ? expression.quasis[0].value.cooked : expression.value; @@ -208,7 +208,7 @@ module.exports = { node: literalNode, fix(fixer) { if (jsxUtil.isJSX(literalNode)) { - return fixer.replaceText(literalNode, `{${getSourceCode(context).getText(literalNode)}}`); + return fixer.replaceText(literalNode, `{${getText(context, literalNode)}}`); } // If a HTML entity name is found, bail out because it can be fixed diff --git a/lib/rules/jsx-curly-newline.js b/lib/rules/jsx-curly-newline.js index f2a4550f71..046ff79582 100644 --- a/lib/rules/jsx-curly-newline.js +++ b/lib/rules/jsx-curly-newline.js @@ -5,9 +5,12 @@ 'use strict'; const docsUrl = require('../util/docsUrl'); -const getSourceCode = require('../util/eslint').getSourceCode; +const eslintUtil = require('../util/eslint'); const report = require('../util/report'); +const getSourceCode = eslintUtil.getSourceCode; +const getText = eslintUtil.getText; + // ------------------------------------------------------------------------------ // Rule Definition // ------------------------------------------------------------------------------ @@ -131,8 +134,7 @@ module.exports = { report(context, messages.unexpectedAfter, 'unexpectedAfter', { node: leftCurly, fix(fixer) { - return sourceCode - .getText() + return getText(context) .slice(leftCurly.range[1], tokenAfterLeftCurly.range[0]) .trim() ? null // If there is a comment between the { and the first element, don't do a fix. @@ -150,8 +152,7 @@ module.exports = { report(context, messages.unexpectedBefore, 'unexpectedBefore', { node: rightCurly, fix(fixer) { - return sourceCode - .getText() + return getText(context) .slice(tokenBeforeRightCurly.range[1], rightCurly.range[0]) .trim() ? null // If there is a comment between the last element and the }, don't do a fix. diff --git a/lib/rules/jsx-fragments.js b/lib/rules/jsx-fragments.js index c075c47002..770cbd087f 100644 --- a/lib/rules/jsx-fragments.js +++ b/lib/rules/jsx-fragments.js @@ -11,7 +11,7 @@ const variableUtil = require('../util/variable'); const testReactVersion = require('../util/version').testReactVersion; const docsUrl = require('../util/docsUrl'); const report = require('../util/report'); -const getSourceCode = require('../util/eslint').getSourceCode; +const getText = require('../util/eslint').getText; // ------------------------------------------------------------------------------ // Rule Definition @@ -66,36 +66,34 @@ module.exports = { } function getFixerToLong(jsxFragment) { - const sourceCode = getSourceCode(context); if (!jsxFragment.closingFragment || !jsxFragment.openingFragment) { // the old TS parser crashes here // TODO: FIXME: can we fake these two descriptors? return null; } return function fix(fixer) { - let source = sourceCode.getText(); + let source = getText(context); source = replaceNode(source, jsxFragment.closingFragment, closeFragLong); source = replaceNode(source, jsxFragment.openingFragment, openFragLong); - const lengthDiff = openFragLong.length - sourceCode.getText(jsxFragment.openingFragment).length - + closeFragLong.length - sourceCode.getText(jsxFragment.closingFragment).length; + const lengthDiff = openFragLong.length - getText(context, jsxFragment.openingFragment).length + + closeFragLong.length - getText(context, jsxFragment.closingFragment).length; const range = jsxFragment.range; return fixer.replaceTextRange(range, source.slice(range[0], range[1] + lengthDiff)); }; } function getFixerToShort(jsxElement) { - const sourceCode = getSourceCode(context); return function fix(fixer) { - let source = sourceCode.getText(); + let source = getText(context); let lengthDiff; if (jsxElement.closingElement) { source = replaceNode(source, jsxElement.closingElement, closeFragShort); source = replaceNode(source, jsxElement.openingElement, openFragShort); - lengthDiff = sourceCode.getText(jsxElement.openingElement).length - openFragShort.length - + sourceCode.getText(jsxElement.closingElement).length - closeFragShort.length; + lengthDiff = getText(context, jsxElement.openingElement).length - openFragShort.length + + getText(context, jsxElement.closingElement).length - closeFragShort.length; } else { source = replaceNode(source, jsxElement.openingElement, `${openFragShort}${closeFragShort}`); - lengthDiff = sourceCode.getText(jsxElement.openingElement).length - openFragShort.length + lengthDiff = getText(context, jsxElement.openingElement).length - openFragShort.length - closeFragShort.length; } diff --git a/lib/rules/jsx-handler-names.js b/lib/rules/jsx-handler-names.js index 8e2227e89f..d839073a52 100644 --- a/lib/rules/jsx-handler-names.js +++ b/lib/rules/jsx-handler-names.js @@ -6,7 +6,7 @@ 'use strict'; const docsUrl = require('../util/docsUrl'); -const getSourceCode = require('../util/eslint').getSourceCode; +const getText = require('../util/eslint').getText; const report = require('../util/report'); // ------------------------------------------------------------------------------ @@ -130,10 +130,10 @@ module.exports = { const propKey = typeof node.name === 'object' ? node.name.name : node.name; const expression = node.value.expression; - const propValue = getSourceCode(context) - .getText(checkInlineFunction && isInlineHandler(node) ? expression.body.callee : expression) - .replace(/\s*/g, '') - .replace(/^this\.|.*::/, ''); + const propValue = getText( + context, + checkInlineFunction && isInlineHandler(node) ? expression.body.callee : expression + ).replace(/\s*/g, '').replace(/^this\.|.*::/, ''); if (propKey === 'ref') { return; diff --git a/lib/rules/jsx-indent-props.js b/lib/rules/jsx-indent-props.js index 7ba02450dd..050e721df3 100644 --- a/lib/rules/jsx-indent-props.js +++ b/lib/rules/jsx-indent-props.js @@ -32,7 +32,7 @@ const astUtil = require('../util/ast'); const docsUrl = require('../util/docsUrl'); -const getSourceCode = require('../util/eslint').getSourceCode; +const getText = require('../util/eslint').getText; const reportC = require('../util/report'); // ------------------------------------------------------------------------------ @@ -141,7 +141,7 @@ module.exports = { * @return {Number} Indent */ function getNodeIndent(node) { - let src = getSourceCode(context).getText(node, node.loc.start.column + extraColumnStart); + let src = getText(context, node, node.loc.start.column + extraColumnStart); const lines = src.split('\n'); src = lines[0]; diff --git a/lib/rules/jsx-indent.js b/lib/rules/jsx-indent.js index aeb5c38aa4..27397172c8 100644 --- a/lib/rules/jsx-indent.js +++ b/lib/rules/jsx-indent.js @@ -36,7 +36,10 @@ const astUtil = require('../util/ast'); const docsUrl = require('../util/docsUrl'); const reportC = require('../util/report'); const jsxUtil = require('../util/jsx'); -const getSourceCode = require('../util/eslint').getSourceCode; +const eslintUtil = require('../util/eslint'); + +const getSourceCode = eslintUtil.getSourceCode; +const getText = eslintUtil.getText; // ------------------------------------------------------------------------------ // Rule Definition @@ -117,7 +120,7 @@ module.exports = { } if (node.type === 'ReturnStatement') { - const raw = getSourceCode(context).getText(node); + const raw = getText(context, node); const lines = raw.split('\n'); if (lines.length > 1) { return function fix(fixer) { @@ -169,7 +172,7 @@ module.exports = { * @return {Number} Indent */ function getNodeIndent(node, byLastLine, excludeCommas) { - let src = getSourceCode(context).getText(node, node.loc.start.column + extraColumnStart); + let src = getText(context, node, node.loc.start.column + extraColumnStart); const lines = src.split('\n'); if (byLastLine) { src = lines[lines.length - 1]; diff --git a/lib/rules/jsx-key.js b/lib/rules/jsx-key.js index 70c745daf1..feee7ad5a0 100644 --- a/lib/rules/jsx-key.js +++ b/lib/rules/jsx-key.js @@ -12,7 +12,7 @@ const docsUrl = require('../util/docsUrl'); const pragmaUtil = require('../util/pragma'); const report = require('../util/report'); const astUtil = require('../util/ast'); -const getSourceCode = require('../util/eslint').getSourceCode; +const getText = require('../util/eslint').getText; // ------------------------------------------------------------------------------ // Rule Definition @@ -214,7 +214,7 @@ module.exports = { } } else { keys.forEach((attr) => { - const value = getSourceCode(context).getText(attr.value); + const value = getText(context, attr.value); if (!map[value]) { map[value] = []; } map[value].push(attr); diff --git a/lib/rules/jsx-max-props-per-line.js b/lib/rules/jsx-max-props-per-line.js index 3f609ca1cf..eebf7f0f33 100644 --- a/lib/rules/jsx-max-props-per-line.js +++ b/lib/rules/jsx-max-props-per-line.js @@ -6,12 +6,12 @@ 'use strict'; const docsUrl = require('../util/docsUrl'); -const getSourceCode = require('../util/eslint').getSourceCode; +const getText = require('../util/eslint').getText; const report = require('../util/report'); function getPropName(context, propNode) { if (propNode.type === 'JSXSpreadAttribute') { - return getSourceCode(context).getText(propNode.argument); + return getText(context, propNode.argument); } return propNode.name.name; } @@ -88,7 +88,6 @@ module.exports = { }; function generateFixFunction(line, max) { - const sourceCode = getSourceCode(context); const output = []; const front = line[0].range[0]; const back = line[line.length - 1].range[1]; @@ -97,9 +96,9 @@ module.exports = { const nodes = line.slice(i, i + max); output.push(nodes.reduce((prev, curr) => { if (prev === '') { - return sourceCode.getText(curr); + return getText(context, curr); } - return `${prev} ${sourceCode.getText(curr)}`; + return `${prev} ${getText(context, curr)}`; }, '')); } diff --git a/lib/rules/jsx-newline.js b/lib/rules/jsx-newline.js index 1b87383bd6..7fd395c72f 100644 --- a/lib/rules/jsx-newline.js +++ b/lib/rules/jsx-newline.js @@ -7,7 +7,7 @@ 'use strict'; const docsUrl = require('../util/docsUrl'); -const getSourceCode = require('../util/eslint').getSourceCode; +const getText = require('../util/eslint').getText; const report = require('../util/report'); // ------------------------------------------------------------------------------ @@ -72,10 +72,9 @@ module.exports = { }, create(context) { const jsxElementParents = new Set(); - const sourceCode = getSourceCode(context); function isBlockCommentInCurlyBraces(element) { - const elementRawValue = sourceCode.getText(element); + const elementRawValue = getText(context, element); return /^\s*{\/\*/.test(elementRawValue); } @@ -123,8 +122,7 @@ module.exports = { fix(fixer) { return fixer.replaceText( firstAdjacentSibling, - sourceCode.getText(firstAdjacentSibling) - .replace(regex, replacement) + getText(context, firstAdjacentSibling).replace(regex, replacement) ); }, }); @@ -152,8 +150,7 @@ module.exports = { return fixer.replaceText( firstAdjacentSibling, // double or remove the last newline - sourceCode.getText(firstAdjacentSibling) - .replace(regex, replacement) + getText(context, firstAdjacentSibling).replace(regex, replacement) ); }, }); diff --git a/lib/rules/jsx-no-comment-textnodes.js b/lib/rules/jsx-no-comment-textnodes.js index 5d7139c211..de4d288c37 100644 --- a/lib/rules/jsx-no-comment-textnodes.js +++ b/lib/rules/jsx-no-comment-textnodes.js @@ -6,7 +6,7 @@ 'use strict'; const docsUrl = require('../util/docsUrl'); -const getSourceCode = require('../util/eslint').getSourceCode; +const getText = require('../util/eslint').getText; const report = require('../util/report'); // ------------------------------------------------------------------------------ @@ -24,7 +24,7 @@ const messages = { */ function checkText(context, node) { // since babel-eslint has the wrong node.raw, we'll get the source text - const rawValue = getSourceCode(context).getText(node); + const rawValue = getText(context, node); if (/^\s*\/(\/|\*)/m.test(rawValue)) { // inside component, e.g.
literal
if ( diff --git a/lib/rules/jsx-no-leaked-render.js b/lib/rules/jsx-no-leaked-render.js index 9833996c14..2cbe705561 100644 --- a/lib/rules/jsx-no-leaked-render.js +++ b/lib/rules/jsx-no-leaked-render.js @@ -8,7 +8,7 @@ const find = require('es-iterator-helpers/Iterator.prototype.find'); const from = require('es-iterator-helpers/Iterator.from'); -const getSourceCode = require('../util/eslint').getSourceCode; +const getText = require('../util/eslint').getText; const docsUrl = require('../util/docsUrl'); const report = require('../util/report'); const variableUtil = require('../util/variable'); @@ -56,13 +56,12 @@ function extractExpressionBetweenLogicalAnds(node) { } function ruleFixer(context, fixStrategy, fixer, reportedNode, leftNode, rightNode) { - const sourceCode = getSourceCode(context); - const rightSideText = sourceCode.getText(rightNode); + const rightSideText = getText(context, rightNode); if (fixStrategy === COERCE_STRATEGY) { const expressions = extractExpressionBetweenLogicalAnds(leftNode); const newText = expressions.map((node) => { - let nodeText = sourceCode.getText(node); + let nodeText = getText(context, node); if (isParenthesized(context, node)) { nodeText = `(${nodeText})`; } @@ -100,7 +99,7 @@ function ruleFixer(context, fixStrategy, fixer, reportedNode, leftNode, rightNod } if (fixStrategy === TERNARY_STRATEGY) { - let leftSideText = sourceCode.getText(trimLeftNode(leftNode)); + let leftSideText = getText(context, trimLeftNode(leftNode)); if (isParenthesized(context, leftNode)) { leftSideText = `(${leftSideText})`; } diff --git a/lib/rules/jsx-no-literals.js b/lib/rules/jsx-no-literals.js index 3fa8ab03d5..d7f43ab05c 100644 --- a/lib/rules/jsx-no-literals.js +++ b/lib/rules/jsx-no-literals.js @@ -11,7 +11,7 @@ const map = require('es-iterator-helpers/Iterator.prototype.map'); const docsUrl = require('../util/docsUrl'); const report = require('../util/report'); -const getSourceCode = require('../util/eslint').getSourceCode; +const getText = require('../util/eslint').getText; // ------------------------------------------------------------------------------ // Rule Definition @@ -150,7 +150,7 @@ module.exports = { report(context, messages[messageId], messageId, { node, data: { - text: getSourceCode(context).getText(node).trim(), + text: getText(context, node).trim(), }, }); } diff --git a/lib/rules/jsx-no-useless-fragment.js b/lib/rules/jsx-no-useless-fragment.js index 11516c5a22..4c2886469f 100644 --- a/lib/rules/jsx-no-useless-fragment.js +++ b/lib/rules/jsx-no-useless-fragment.js @@ -10,7 +10,7 @@ const pragmaUtil = require('../util/pragma'); const jsxUtil = require('../util/jsx'); const docsUrl = require('../util/docsUrl'); const report = require('../util/report'); -const getSourceCode = require('../util/eslint').getSourceCode; +const getText = require('../util/eslint').getText; function isJSXText(node) { return !!node && (node.type === 'JSXText' || node.type === 'Literal'); @@ -217,7 +217,7 @@ module.exports = { const opener = node.type === 'JSXFragment' ? node.openingFragment : node.openingElement; const closer = node.type === 'JSXFragment' ? node.closingFragment : node.closingElement; - const childrenText = opener.selfClosing ? '' : getSourceCode(context).getText().slice(opener.range[1], closer.range[0]); + const childrenText = opener.selfClosing ? '' : getText(context).slice(opener.range[1], closer.range[0]); return fixer.replaceText(node, trimLikeReact(childrenText)); }; diff --git a/lib/rules/jsx-one-expression-per-line.js b/lib/rules/jsx-one-expression-per-line.js index 3e2fe4c0da..3ae61e3d96 100644 --- a/lib/rules/jsx-one-expression-per-line.js +++ b/lib/rules/jsx-one-expression-per-line.js @@ -6,10 +6,13 @@ 'use strict'; const docsUrl = require('../util/docsUrl'); -const getSourceCode = require('../util/eslint').getSourceCode; +const eslintUtil = require('../util/eslint'); const jsxUtil = require('../util/jsx'); const report = require('../util/report'); +const getSourceCode = eslintUtil.getSourceCode; +const getText = eslintUtil.getText; + // ------------------------------------------------------------------------------ // Rule Definition // ------------------------------------------------------------------------------ @@ -61,7 +64,7 @@ module.exports = { * @returns {string} */ function nodeDescriptor(n) { - return n.openingElement ? n.openingElement.name.name : getSourceCode(context).getText(n).replace(/\n/g, ''); + return n.openingElement ? n.openingElement.name.name : getText(context, n).replace(/\n/g, ''); } function handleJSX(node) { @@ -181,7 +184,7 @@ module.exports = { return; } - const source = getSourceCode(context).getText(child); + const source = getText(context, child); const leadingSpace = !!(prevChild && spaceBetweenPrev()); const trailingSpace = !!(nextChild && spaceBetweenNext()); const leadingNewLine = !!prevChild; diff --git a/lib/rules/jsx-props-no-multi-spaces.js b/lib/rules/jsx-props-no-multi-spaces.js index a3a8acaa59..ce80338cd8 100644 --- a/lib/rules/jsx-props-no-multi-spaces.js +++ b/lib/rules/jsx-props-no-multi-spaces.js @@ -6,9 +6,12 @@ 'use strict'; const docsUrl = require('../util/docsUrl'); -const getSourceCode = require('../util/eslint').getSourceCode; +const eslintUtil = require('../util/eslint'); const report = require('../util/report'); +const getSourceCode = eslintUtil.getSourceCode; +const getText = eslintUtil.getText; + // ------------------------------------------------------------------------------ // Rule Definition // ------------------------------------------------------------------------------ @@ -40,7 +43,7 @@ module.exports = { function getPropName(propNode) { switch (propNode.type) { case 'JSXSpreadAttribute': - return sourceCode.getText(propNode.argument); + return getText(context, propNode.argument); case 'JSXIdentifier': return propNode.name; case 'JSXMemberExpression': @@ -48,7 +51,7 @@ module.exports = { default: return propNode.name ? propNode.name.name - : `${sourceCode.getText(propNode.object)}.${propNode.property.name}`; // needed for typescript-eslint parser + : `${getText(context, propNode.object)}.${propNode.property.name}`; // needed for typescript-eslint parser } } diff --git a/lib/rules/jsx-sort-default-props.js b/lib/rules/jsx-sort-default-props.js index 3fd4c70b41..f65981ec64 100644 --- a/lib/rules/jsx-sort-default-props.js +++ b/lib/rules/jsx-sort-default-props.js @@ -13,7 +13,7 @@ const log = require('../util/log'); const eslintUtil = require('../util/eslint'); const getFirstTokens = eslintUtil.getFirstTokens; -const getSourceCode = eslintUtil.getSourceCode; +const getText = eslintUtil.getText; let isWarnedForDeprecation = false; @@ -86,7 +86,7 @@ module.exports = { } function getKey(node) { - return getSourceCode(context).getText(node.key || node.argument); + return getText(context, node.key || node.argument); } /** diff --git a/lib/rules/jsx-sort-props.js b/lib/rules/jsx-sort-props.js index fc8565191f..f811e16cf7 100644 --- a/lib/rules/jsx-sort-props.js +++ b/lib/rules/jsx-sort-props.js @@ -12,7 +12,10 @@ const toSorted = require('array.prototype.tosorted'); const docsUrl = require('../util/docsUrl'); const jsxUtil = require('../util/jsx'); const report = require('../util/report'); -const getSourceCode = require('../util/eslint').getSourceCode; +const eslintUtil = require('../util/eslint'); + +const getText = eslintUtil.getText; +const getSourceCode = eslintUtil.getSourceCode; // ------------------------------------------------------------------------------ // Rule Definition @@ -213,7 +216,6 @@ function getGroupsOfSortableAttributes(attributes, context) { } function generateFixerFunction(node, context, reservedList) { - const sourceCode = getSourceCode(context); const attributes = node.attributes.slice(0); const configuration = context.options[0] || {}; const ignoreCase = configuration.ignoreCase || false; @@ -246,7 +248,7 @@ function generateFixerFunction(node, context, reservedList) { return function fixFunction(fixer) { const fixers = []; - let source = sourceCode.getText(); + let source = getText(context); sortableAttributeGroups.forEach((sortableGroup, ii) => { sortableGroup.forEach((attr, jj) => { diff --git a/lib/rules/jsx-wrap-multilines.js b/lib/rules/jsx-wrap-multilines.js index c2da2a7882..17a9812465 100644 --- a/lib/rules/jsx-wrap-multilines.js +++ b/lib/rules/jsx-wrap-multilines.js @@ -7,11 +7,14 @@ const has = require('object.hasown/polyfill')(); const docsUrl = require('../util/docsUrl'); -const getSourceCode = require('../util/eslint').getSourceCode; +const eslintUtil = require('../util/eslint'); const jsxUtil = require('../util/jsx'); const reportC = require('../util/report'); const isParenthesized = require('../util/ast').isParenthesized; +const getSourceCode = eslintUtil.getSourceCode; +const getText = eslintUtil.getText; + // ------------------------------------------------------------------------------ // Constants // ------------------------------------------------------------------------------ @@ -148,7 +151,7 @@ module.exports = { const option = getOption(type); if ((option === true || option === 'parens') && !isParenthesized(context, node) && isMultilines(node)) { - report(node, 'missingParens', (fixer) => fixer.replaceText(node, `(${sourceCode.getText(node)})`)); + report(node, 'missingParens', (fixer) => fixer.replaceText(node, `(${getText(context, node)})`)); } if (option === 'parens-new-line' && isMultilines(node)) { @@ -163,18 +166,18 @@ module.exports = { 'missingParens', (fixer) => fixer.replaceTextRange( [tokenBefore.range[0], tokenAfter && (tokenAfter.value === ';' || tokenAfter.value === '}') ? tokenAfter.range[0] : node.range[1]], - `${trimTokenBeforeNewline(node, tokenBefore)}(\n${start.column > 0 ? ' '.repeat(start.column) : ''}${sourceCode.getText(node)}\n${start.column > 0 ? ' '.repeat(start.column - 2) : ''})` + `${trimTokenBeforeNewline(node, tokenBefore)}(\n${start.column > 0 ? ' '.repeat(start.column) : ''}${getText(context, node)}\n${start.column > 0 ? ' '.repeat(start.column - 2) : ''})` ) ); } else { - report(node, 'missingParens', (fixer) => fixer.replaceText(node, `(\n${sourceCode.getText(node)}\n)`)); + report(node, 'missingParens', (fixer) => fixer.replaceText(node, `(\n${getText(context, node)}\n)`)); } } else { const needsOpening = needsOpeningNewLine(node); const needsClosing = needsClosingNewLine(node); if (needsOpening || needsClosing) { report(node, 'parensOnNewLines', (fixer) => { - const text = sourceCode.getText(node); + const text = getText(context, node); let fixed = text; if (needsOpening) { fixed = `\n${fixed}`; @@ -193,7 +196,7 @@ module.exports = { const tokenAfter = sourceCode.getTokenAfter(node); report(node, 'extraParens', (fixer) => fixer.replaceTextRange( [tokenBefore.range[0], tokenAfter.range[1]], - sourceCode.getText(node) + getText(context, node) )); } } diff --git a/lib/rules/no-arrow-function-lifecycle.js b/lib/rules/no-arrow-function-lifecycle.js index 71c8389522..e56cb78601 100644 --- a/lib/rules/no-arrow-function-lifecycle.js +++ b/lib/rules/no-arrow-function-lifecycle.js @@ -13,9 +13,12 @@ const componentUtil = require('../util/componentUtil'); const docsUrl = require('../util/docsUrl'); const lifecycleMethods = require('../util/lifecycleMethods'); const report = require('../util/report'); -const getSourceCode = require('../util/eslint').getSourceCode; +const eslintUtil = require('../util/eslint'); -function getText(node) { +const getSourceCode = eslintUtil.getSourceCode; +const getText = eslintUtil.getText; + +function getRuleText(node) { const params = node.value.params.map((p) => p.name); if (node.type === 'Property') { @@ -104,7 +107,7 @@ module.exports = { node.key.range[1], (previousComment.length > 0 ? previousComment[0] : body).range[0], ]; - const hasSemi = node.value.expression && sourceCode.getText(node).slice(node.value.range[1] - node.range[0]) === ';'; + const hasSemi = node.value.expression && getText(context, node).slice(node.value.range[1] - node.range[0]) === ';'; report( context, @@ -118,13 +121,13 @@ module.exports = { fix(fixer) { if (!sourceCode.getCommentsAfter) { // eslint 3.x - return isBlockBody && fixer.replaceTextRange(headRange, getText(node)); + return isBlockBody && fixer.replaceTextRange(headRange, getRuleText(node)); } return [].concat( - fixer.replaceTextRange(headRange, getText(node)), + fixer.replaceTextRange(headRange, getRuleText(node)), isBlockBody ? [] : fixer.replaceTextRange( [bodyRange[0], bodyRange[1] + (hasSemi ? 1 : 0)], - `{ return ${previousComment.map((x) => sourceCode.getText(x)).join('')}${sourceCode.getText(body)}${nextComment.map((x) => sourceCode.getText(x)).join('')}; }` + `{ return ${previousComment.map((x) => getText(context, x)).join('')}${getText(context, body)}${nextComment.map((x) => getText(context, x)).join('')}; }` ) ); }, diff --git a/lib/rules/no-deprecated.js b/lib/rules/no-deprecated.js index 1541942b86..462bd4c756 100644 --- a/lib/rules/no-deprecated.js +++ b/lib/rules/no-deprecated.js @@ -14,7 +14,7 @@ const docsUrl = require('../util/docsUrl'); const pragmaUtil = require('../util/pragma'); const testReactVersion = require('../util/version').testReactVersion; const report = require('../util/report'); -const getSourceCode = require('../util/eslint').getSourceCode; +const getText = require('../util/eslint').getText; // ------------------------------------------------------------------------------ // Constants @@ -218,7 +218,7 @@ module.exports = { return { MemberExpression(node) { - checkDeprecation(node, getSourceCode(context).getText(node)); + checkDeprecation(node, getText(context, node)); }, ImportDeclaration(node) { diff --git a/lib/rules/no-unknown-property.js b/lib/rules/no-unknown-property.js index c8071c4a43..3e8c6de111 100644 --- a/lib/rules/no-unknown-property.js +++ b/lib/rules/no-unknown-property.js @@ -7,7 +7,7 @@ const has = require('object.hasown/polyfill')(); const docsUrl = require('../util/docsUrl'); -const getSourceCode = require('../util/eslint').getSourceCode; +const getText = require('../util/eslint').getText; const testReactVersion = require('../util/version').testReactVersion; const report = require('../util/report'); @@ -556,7 +556,7 @@ module.exports = { return { JSXAttribute(node) { const ignoreNames = getIgnoreConfig(); - const actualName = getSourceCode(context).getText(node.name); + const actualName = getText(context, node.name); if (ignoreNames.indexOf(actualName) >= 0) { return; } diff --git a/lib/rules/prefer-exact-props.js b/lib/rules/prefer-exact-props.js index d9970115f6..0bd4dd8b06 100644 --- a/lib/rules/prefer-exact-props.js +++ b/lib/rules/prefer-exact-props.js @@ -10,7 +10,7 @@ const propsUtil = require('../util/props'); const propWrapperUtil = require('../util/propWrapper'); const variableUtil = require('../util/variable'); const report = require('../util/report'); -const getSourceCode = require('../util/eslint').getSourceCode; +const getText = require('../util/eslint').getText; // ----------------------------------------------------------------------------- // Rule Definition @@ -37,7 +37,6 @@ module.exports = { create: Components.detect((context, components, utils) => { const typeAliases = {}; const exactWrappers = propWrapperUtil.getExactPropWrapperFunctions(context); - const sourceCode = getSourceCode(context); function getPropTypesErrorMessage() { const formattedWrappers = propWrapperUtil.formatPropWrapperFunctions(exactWrappers); @@ -84,7 +83,7 @@ module.exports = { return ( node && node.type === 'CallExpression' - && !propWrapperUtil.isExactPropWrapperFunction(context, sourceCode.getText(node.callee)) + && !propWrapperUtil.isExactPropWrapperFunction(context, getText(context, node.callee)) ); } diff --git a/lib/rules/prefer-stateless-function.js b/lib/rules/prefer-stateless-function.js index c2477a8dd5..35e471ff9c 100644 --- a/lib/rules/prefer-stateless-function.js +++ b/lib/rules/prefer-stateless-function.js @@ -17,7 +17,7 @@ const docsUrl = require('../util/docsUrl'); const report = require('../util/report'); const eslintUtil = require('../util/eslint'); -const getSourceCode = eslintUtil.getSourceCode; +const getText = eslintUtil.getText; // ------------------------------------------------------------------------------ // Rule Definition @@ -335,7 +335,7 @@ module.exports = { // Mark `ref` usage JSXAttribute(node) { - const name = getSourceCode(context).getText(node.name); + const name = getText(context, node.name); if (name !== 'ref') { return; } diff --git a/lib/rules/sort-default-props.js b/lib/rules/sort-default-props.js index d46ef66f86..7f7243f6b4 100644 --- a/lib/rules/sort-default-props.js +++ b/lib/rules/sort-default-props.js @@ -12,7 +12,7 @@ const report = require('../util/report'); const eslintUtil = require('../util/eslint'); const getFirstTokens = eslintUtil.getFirstTokens; -const getSourceCode = eslintUtil.getSourceCode; +const getText = eslintUtil.getText; // ------------------------------------------------------------------------------ // Rule Definition @@ -81,7 +81,7 @@ module.exports = { } function getKey(node) { - return getSourceCode(context).getText(node.key || node.argument); + return getText(context, node.key || node.argument); } /** diff --git a/lib/rules/sort-prop-types.js b/lib/rules/sort-prop-types.js index 2a9d307bf9..5d44bca744 100644 --- a/lib/rules/sort-prop-types.js +++ b/lib/rules/sort-prop-types.js @@ -10,7 +10,10 @@ const docsUrl = require('../util/docsUrl'); const propWrapperUtil = require('../util/propWrapper'); const propTypesSortUtil = require('../util/propTypesSort'); const report = require('../util/report'); -const getSourceCode = require('../util/eslint').getSourceCode; +const eslintUtil = require('../util/eslint'); + +const getSourceCode = eslintUtil.getSourceCode; +const getText = eslintUtil.getText; // ------------------------------------------------------------------------------ // Rule Definition @@ -29,7 +32,7 @@ function getKey(context, node) { if (node.key && node.key.value) { return node.key.value; } - return getSourceCode(context).getText(node.key || node.argument); + return getText(context, node.key || node.argument); } function getValueName(node) { diff --git a/lib/util/Components.js b/lib/util/Components.js index a927c44e5c..e1803b26e3 100644 --- a/lib/util/Components.js +++ b/lib/util/Components.js @@ -23,7 +23,7 @@ const isFirstLetterCapitalized = require('./isFirstLetterCapitalized'); const isDestructuredFromPragmaImport = require('./isDestructuredFromPragmaImport'); const eslintUtil = require('./eslint'); -const getSourceCode = eslintUtil.getSourceCode; +const getText = eslintUtil.getText; function getId(node) { return node ? `${node.range[0]}:${node.range[1]}` : ''; @@ -285,7 +285,6 @@ function mergeRules(rules) { function componentRule(rule, context) { const pragma = pragmaUtil.getFromContext(context); - const sourceCode = getSourceCode(context); const components = new Components(); const wrapperFunctions = getWrapperFunctions(context, pragma); @@ -684,7 +683,7 @@ function componentRule(rule, context) { if (refId.parent && refId.parent.type === 'MemberExpression') { refId = refId.parent; } - if (sourceCode.getText(refId) !== componentName) { + if (getText(context, refId) !== componentName) { return false; } if (refId.type === 'MemberExpression') { diff --git a/lib/util/componentUtil.js b/lib/util/componentUtil.js index 29720c124f..17249c33f5 100644 --- a/lib/util/componentUtil.js +++ b/lib/util/componentUtil.js @@ -5,6 +5,7 @@ const pragmaUtil = require('./pragma'); const eslintUtil = require('./eslint'); const getSourceCode = eslintUtil.getSourceCode; +const getText = eslintUtil.getText; // eslint-disable-next-line valid-jsdoc /** @@ -159,9 +160,8 @@ function getParentES6Component(context) { */ function isPureComponent(node, context) { const pragma = getPragma(context); - const sourceCode = getSourceCode(context); if (node.superClass) { - return new RegExp(`^(${pragma}\\.)?PureComponent$`).test(sourceCode.getText(node.superClass)); + return new RegExp(`^(${pragma}\\.)?PureComponent$`).test(getText(context, node.superClass)); } return false; } diff --git a/lib/util/defaultProps.js b/lib/util/defaultProps.js index c747030ba3..7cfdc92d52 100644 --- a/lib/util/defaultProps.js +++ b/lib/util/defaultProps.js @@ -10,13 +10,11 @@ const componentUtil = require('./componentUtil'); const propsUtil = require('./props'); const variableUtil = require('./variable'); const propWrapperUtil = require('./propWrapper'); -const getSourceCode = require('./eslint').getSourceCode; +const getText = require('./eslint').getText; const QUOTES_REGEX = /^["']|["']$/g; module.exports = function defaultPropsInstructions(context, components, utils) { - const sourceCode = getSourceCode(context); - /** * Try to resolve the node passed in to a variable in the current scope. If the node passed in is not * an Identifier, then the node is simply returned. @@ -52,7 +50,7 @@ module.exports = function defaultPropsInstructions(context, components, utils) { } return objectExpression.properties.map((defaultProp) => ({ - name: sourceCode.getText(defaultProp.key).replace(QUOTES_REGEX, ''), + name: getText(context, defaultProp.key).replace(QUOTES_REGEX, ''), node: defaultProp, })); } diff --git a/lib/util/eslint.js b/lib/util/eslint.js index bb56f65e2a..edecd9b317 100644 --- a/lib/util/eslint.js +++ b/lib/util/eslint.js @@ -21,9 +21,16 @@ function getFirstTokens(context, node, count) { return sourceCode.getFirstTokens ? sourceCode.getFirstTokens(node, count) : context.getFirstTokens(node, count); } +function getText(context) { + const sourceCode = getSourceCode(context); + const args = Array.prototype.slice.call(arguments, 1); + return sourceCode.getText ? sourceCode.getText.apply(sourceCode, args) : context.getSource.apply(context, args); +} + module.exports = { getAncestors, getFirstTokens, getSourceCode, + getText, markVariableAsUsed, }; diff --git a/lib/util/propTypes.js b/lib/util/propTypes.js index dc22ad4964..1fb81e9942 100644 --- a/lib/util/propTypes.js +++ b/lib/util/propTypes.js @@ -17,6 +17,7 @@ const eslintUtil = require('./eslint'); const getFirstTokens = eslintUtil.getFirstTokens; const getSourceCode = eslintUtil.getSourceCode; +const getText = eslintUtil.getText; /** * Check if node is function type. @@ -907,7 +908,7 @@ module.exports = function propTypesInstructions(context, components, utils) { ignorePropsValidation = true; break; } - const parentProp = context.getSource(propTypes.parent.left.object).replace(/^.*\.propTypes\./, ''); + const parentProp = getText(context, propTypes.parent.left.object).replace(/^.*\.propTypes\./, ''); const types = buildReactDeclarationTypes( propTypes.parent.right, parentProp @@ -953,7 +954,7 @@ module.exports = function propTypesInstructions(context, components, utils) { if ( propWrapperUtil.isPropWrapperFunction( context, - getSourceCode(context).getText(propTypes.callee) + getText(context, propTypes.callee) ) && propTypes.arguments && propTypes.arguments[0] ) { diff --git a/lib/util/propTypesSort.js b/lib/util/propTypesSort.js index 1284b163ca..12982430b3 100644 --- a/lib/util/propTypesSort.js +++ b/lib/util/propTypesSort.js @@ -7,7 +7,10 @@ const toSorted = require('array.prototype.tosorted'); const astUtil = require('./ast'); -const getSourceCode = require('./eslint').getSourceCode; +const eslintUtil = require('./eslint'); + +const getSourceCode = eslintUtil.getSourceCode; +const getText = eslintUtil.getText; /** * Returns the value name of a node. @@ -179,9 +182,9 @@ function fixPropTypesSort( (a, b) => sorter(a, b, context, ignoreCase, requiredFirst, callbacksLast, noSortAlphabetically) ); + const sourceCodeText = getText(context); source = nodes.reduceRight((acc, attr, index) => { const sortedAttr = sortedAttributes[index]; - const sourceCodeText = sourceCode.getText(); const commentNode = commentnodeMap.get(sortedAttr); let sortedAttrText = sourceCodeText.slice(commentNode.start, commentNode.end); if (sortShapeProp && isShapeProp(sortedAttr.value)) { @@ -200,7 +203,7 @@ function fixPropTypesSort( return source; } - const source = sortInSource(declarations, getSourceCode(context).getText()); + const source = sortInSource(declarations, getText(context)); const rangeStart = commentnodeMap.get(declarations[0]).start; const rangeEnd = commentnodeMap.get(declarations[declarations.length - 1]).end;