From ae9b2c675046c224d0efa1eb7127cc00ca5b9895 Mon Sep 17 00:00:00 2001 From: Weijia Wang <381152119@qq.com> Date: Tue, 31 Oct 2017 23:51:59 +0800 Subject: [PATCH] tools: Implement automatic fix for no-let-in-for-declaration Refs: https://github.com/nodejs/node/issues/16636 --- .../test-eslint-no-let-in-for-declaration.js | 3 +++ tools/eslint-rules/no-let-in-for-declaration.js | 16 +++++++++++++--- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/test/parallel/test-eslint-no-let-in-for-declaration.js b/test/parallel/test-eslint-no-let-in-for-declaration.js index b6b7c357455ab9..c3c1e17a729252 100644 --- a/test/parallel/test-eslint-no-let-in-for-declaration.js +++ b/test/parallel/test-eslint-no-let-in-for-declaration.js @@ -24,14 +24,17 @@ ruleTester.run('no-let-in-for-declaration', rule, { invalid: [ { code: 'for (let foo = 1;;);', + output: 'for (var foo = 1;;);', errors: [{ message }] }, { code: 'for (let foo in bar);', + output: 'for (var foo in bar);', errors: [{ message }] }, { code: 'for (let foo of bar);', + output: 'for (var foo of bar);', errors: [{ message }] } ] diff --git a/tools/eslint-rules/no-let-in-for-declaration.js b/tools/eslint-rules/no-let-in-for-declaration.js index 8b1a6783e0773d..34ad2d5761fda2 100644 --- a/tools/eslint-rules/no-let-in-for-declaration.js +++ b/tools/eslint-rules/no-let-in-for-declaration.js @@ -14,7 +14,7 @@ module.exports = { create(context) { - + const sourceCode = context.getSourceCode(); const msg = 'Use of `let` as the loop variable in a for-loop is ' + 'not recommended. Please use `var` instead.'; @@ -23,7 +23,12 @@ module.exports = { */ function testForLoop(node) { if (node.init && node.init.kind === 'let') { - context.report(node.init, msg); + context.report({ + node: node.init, + message: msg, + fix: (fixer) => + fixer.replaceText(sourceCode.getFirstToken(node.init), 'var') + }); } } @@ -33,7 +38,12 @@ module.exports = { */ function testForInOfLoop(node) { if (node.left && node.left.kind === 'let') { - context.report(node.left, msg); + context.report({ + node: node.left, + message: msg, + fix: (fixer) => + fixer.replaceText(sourceCode.getFirstToken(node.left), 'var') + }); } }