Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

prefer-ternary: Refactor to use ESLint recommended way to extend fix range #857

Merged
merged 5 commits into from Dec 12, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
14 changes: 6 additions & 8 deletions rules/prefer-ternary.js
@@ -1,9 +1,9 @@
'use strict';
const {isParenthesized} = require('eslint-utils');
const {flatten} = require('lodash');
const FixTracker = require('eslint/lib/rules/utils/fix-tracker');
const getDocumentationUrl = require('./utils/get-documentation-url');
const avoidCapture = require('./utils/avoid-capture');
const extendFixRange = require('./utils/extend-fix-range');

const messageId = 'prefer-ternary';

Expand Down Expand Up @@ -204,7 +204,7 @@ const create = context => {
context.report({
node,
messageId,
fix: fixer => {
* fix(fixer) {
const testText = getParenthesizedText(node.test);
const consequentText = typeof result.consequent === 'string' ?
result.consequent :
Expand Down Expand Up @@ -241,13 +241,11 @@ const create = context => {
}

const fixed = `${before}${testText} ? ${consequentText} : ${alternateText}${after}`;
if (!generateNewVariables) {
return fixer.replaceText(node, fixed);
}
yield fixer.replaceText(node, fixed);

return new FixTracker(fixer, sourceCode)
.retainRange(sourceCode.ast.range)
.replaceTextRange(node.range, fixed);
if (generateNewVariables) {
yield * extendFixRange(fixer, sourceCode.ast.range);
}
}
});
}
Expand Down
15 changes: 15 additions & 0 deletions rules/utils/extend-fix-range.js
@@ -0,0 +1,15 @@
'use strict';

/**
Extend fix range to prevent changes from other rules.
https://github.com/eslint/eslint/pull/13748/files#diff-c692f3fde09eda7c89f1802c908511a3fb59f5d207fe95eb009cb52e46a99e84R348

@param {ruleFixer} fixer - The fixer to fix.
@param {int[]} range - The extended range node.
*/
function * extendFixRange(fixer, range) {
yield fixer.insertTextBeforeRange(range, '');
yield fixer.insertTextAfterRange(range, '');
}

module.exports = extendFixRange;