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

Fix: operator-assignment invalid autofix with adjacent tokens #12483

Merged
merged 1 commit into from Oct 25, 2019
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
12 changes: 11 additions & 1 deletion lib/rules/operator-assignment.js
Expand Up @@ -194,7 +194,17 @@ module.exports = {
) {
rightText = `${sourceCode.text.slice(operatorToken.range[1], node.right.range[0])}(${sourceCode.getText(node.right)})`;
} else {
rightText = sourceCode.text.slice(operatorToken.range[1], node.range[1]);
const firstRightToken = sourceCode.getFirstToken(node.right);
let rightTextPrefix = "";

if (
operatorToken.range[1] === firstRightToken.range[0] &&
!astUtils.canTokensBeAdjacent(newOperator, firstRightToken)
) {
rightTextPrefix = " "; // foo+=+bar -> foo= foo+ +bar
}

rightText = `${rightTextPrefix}${sourceCode.text.slice(operatorToken.range[1], node.range[1])}`;
}

return fixer.replaceText(node, `${leftText}= ${leftText}${newOperator}${rightText}`);
Expand Down
25 changes: 25 additions & 0 deletions tests/lib/rules/operator-assignment.js
Expand Up @@ -230,6 +230,31 @@ ruleTester.run("operator-assignment", rule, {
output: "foo = foo * (bar + 1)",
options: ["never"],
errors: UNEXPECTED_OPERATOR_ASSIGNMENT
}, {
code: "foo+=-bar",
output: "foo= foo+-bar", // tokens can be adjacent
options: ["never"],
errors: UNEXPECTED_OPERATOR_ASSIGNMENT
}, {
code: "foo+=+bar",
output: "foo= foo+ +bar", // tokens cannot be adjacent, insert a space between
options: ["never"],
errors: UNEXPECTED_OPERATOR_ASSIGNMENT
}, {
code: "foo+= +bar",
output: "foo= foo+ +bar", // tokens cannot be adjacent, but there is already a space between
options: ["never"],
errors: UNEXPECTED_OPERATOR_ASSIGNMENT
}, {
code: "foo+=/**/+bar",
output: "foo= foo+/**/+bar", // tokens cannot be adjacent, but there is a comment between
options: ["never"],
errors: UNEXPECTED_OPERATOR_ASSIGNMENT
}, {
code: "foo+=+bar===baz",
output: "foo= foo+(+bar===baz)", // tokens cannot be adjacent, but the right side will be parenthesised
options: ["never"],
errors: UNEXPECTED_OPERATOR_ASSIGNMENT
}]

});