Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Fix: prefer-const produces invalid autofix (fixes #11699) (#11827)
  • Loading branch information
mdjermanovic authored and mysticatea committed Jul 17, 2019
1 parent cb475fd commit 2dafe2d
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 4 deletions.
12 changes: 9 additions & 3 deletions lib/rules/prefer-const.js
Expand Up @@ -420,8 +420,9 @@ module.exports = {

let shouldFix = varDeclParent &&

// Don't do a fix unless the variable is initialized (or it's in a for-in or for-of loop)
(varDeclParent.parent.type === "ForInStatement" || varDeclParent.parent.type === "ForOfStatement" || varDeclParent.declarations[0].init) &&
// Don't do a fix unless all variables in the declarations are initialized (or it's in a for-in or for-of loop)
(varDeclParent.parent.type === "ForInStatement" || varDeclParent.parent.type === "ForOfStatement" ||
varDeclParent.declarations.every(declaration => declaration.init)) &&

/*
* If options.destructuring is "all", then this warning will not occur unless
Expand Down Expand Up @@ -450,7 +451,12 @@ module.exports = {
node,
messageId: "useConst",
data: node,
fix: shouldFix ? fixer => fixer.replaceText(sourceCode.getFirstToken(varDeclParent), "const") : null
fix: shouldFix
? fixer => fixer.replaceText(
sourceCode.getFirstToken(varDeclParent, t => t.value === varDeclParent.kind),
"const"
)
: null
});
});
}
Expand Down
20 changes: 19 additions & 1 deletion tests/lib/rules/prefer-const.js
Expand Up @@ -508,7 +508,25 @@ ruleTester.run("prefer-const", rule, {
{ message: "'a' is never reassigned. Use 'const' instead.", type: "Identifier" },
{ message: "'b' is never reassigned. Use 'const' instead.", type: "Identifier" }
]
}
},

// https://github.com/eslint/eslint/issues/11699
{
code: "let {a, b} = c, d;",
output: null,
errors: [
{ messageId: "useConst", data: { name: "a" }, type: "Identifier" },
{ messageId: "useConst", data: { name: "b" }, type: "Identifier" }
]
},
{
code: "let {a, b, c} = {}, e, f;",
output: null,
errors: [
{ messageId: "useConst", data: { name: "a" }, type: "Identifier" },
{ messageId: "useConst", data: { name: "b" }, type: "Identifier" },
{ messageId: "useConst", data: { name: "c" }, type: "Identifier" }
]
}
]
});

0 comments on commit 2dafe2d

Please sign in to comment.