From 2dafe2d288d1e0d353bb938d12a5da888091cfdb Mon Sep 17 00:00:00 2001 From: Milos Djermanovic Date: Wed, 17 Jul 2019 07:04:51 +0200 Subject: [PATCH] Fix: prefer-const produces invalid autofix (fixes #11699) (#11827) --- lib/rules/prefer-const.js | 12 +++++++++--- tests/lib/rules/prefer-const.js | 20 +++++++++++++++++++- 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/lib/rules/prefer-const.js b/lib/rules/prefer-const.js index 68c07da4ed9..854da310e4b 100644 --- a/lib/rules/prefer-const.js +++ b/lib/rules/prefer-const.js @@ -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 @@ -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 }); }); } diff --git a/tests/lib/rules/prefer-const.js b/tests/lib/rules/prefer-const.js index d8c018bdf3c..d923985337b 100644 --- a/tests/lib/rules/prefer-const.js +++ b/tests/lib/rules/prefer-const.js @@ -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" } + ] + } ] });