Skip to content
Permalink
Browse files
Fix: extend prefer-const fixer range to whole declaration (fixes #13899
…) (#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 fb274226242eaebc1480fc9c901202986afc3c8a
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 5 deletions.
@@ -5,6 +5,11 @@

"use strict";

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

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

//------------------------------------------------------------------------------
@@ -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
});
});
@@ -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" },
@@ -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.