Skip to content

Commit

Permalink
Fix: extend prefer-const fixer range to whole declaration (fixes #13899
Browse files Browse the repository at this point in the history
…) (#14033)

* Fix: extend fixer range of prefer const to whole declaration

* Chore: update prefer-const test case
  • Loading branch information
snitin315 committed Jan 30, 2021
1 parent e0b05c7 commit fb27422
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 5 deletions.
21 changes: 17 additions & 4 deletions lib/rules/prefer-const.js
Expand Up @@ -5,6 +5,11 @@

"use strict";

//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------

const FixTracker = require("./utils/fix-tracker");
const astUtils = require("./utils/ast-utils");

//------------------------------------------------------------------------------
Expand Down Expand Up @@ -451,10 +456,18 @@ module.exports = {
messageId: "useConst",
data: node,
fix: shouldFix
? fixer => fixer.replaceText(
sourceCode.getFirstToken(varDeclParent, t => t.value === varDeclParent.kind),
"const"
)
? fixer => {
const letKeywordToken = sourceCode.getFirstToken(varDeclParent, t => t.value === varDeclParent.kind);

/**
* Extend the replacement range to the whole declaration,
* in order to prevent other fixes in the same pass
* https://github.com/eslint/eslint/issues/13899
*/
return new FixTracker(fixer, sourceCode)
.retainRange(varDeclParent.range)
.replaceTextRange(letKeywordToken.range, "const");
}
: null
});
});
Expand Down
11 changes: 10 additions & 1 deletion tests/lib/rules/prefer-const.js
Expand Up @@ -500,9 +500,11 @@ ruleTester.run("prefer-const", rule, {
{ message: "'b' is never reassigned. Use 'const' instead.", type: "Identifier" }
]
},

// The inner `let` will be auto-fixed in the second pass
{
code: "let someFunc = () => { let a = 1, b = 2; foo(a, b) }",
output: "const someFunc = () => { const a = 1, b = 2; foo(a, b) }",
output: "const someFunc = () => { let a = 1, b = 2; foo(a, b) }",
errors: [
{ message: "'someFunc' is never reassigned. Use 'const' instead.", type: "Identifier" },
{ message: "'a' is never reassigned. Use 'const' instead.", type: "Identifier" },
Expand Down Expand Up @@ -546,6 +548,13 @@ ruleTester.run("prefer-const", rule, {
{ message: "'bar' is never reassigned. Use 'const' instead.", type: "Identifier" },
{ message: "'bar' is never reassigned. Use 'const' instead.", type: "Identifier" }
]
},

// https://github.com/eslint/eslint/issues/13899
{
code: "/*eslint no-undef-init:error*/ let foo = undefined;",
output: "/*eslint no-undef-init:error*/ const foo = undefined;",
errors: 2
}
]
});

0 comments on commit fb27422

Please sign in to comment.