From a33dc81b2fe8d6548ae46032b895e430a74ce2c3 Mon Sep 17 00:00:00 2001 From: Shobhit Chittora Date: Wed, 1 Nov 2017 01:31:02 +0530 Subject: [PATCH] tools: add fixer for prefer-assert-iferror.js PR-URL: https://github.com/nodejs/node/pull/16648 Refs: https://github.com/nodejs/node/issues/16636 Reviewed-By: Anatoli Papirovski Reviewed-By: Gibson Fahnestock Reviewed-By: James M Snell Reviewed-By: Ruben Bridgewater --- .../test-eslint-prefer-assert-iferror.js | 14 +++++++---- tools/eslint-rules/prefer-assert-iferror.js | 23 +++++++++++++++++-- 2 files changed, 31 insertions(+), 6 deletions(-) diff --git a/test/parallel/test-eslint-prefer-assert-iferror.js b/test/parallel/test-eslint-prefer-assert-iferror.js index 6e577b1fc35ace..8a9723f4b21f6a 100644 --- a/test/parallel/test-eslint-prefer-assert-iferror.js +++ b/test/parallel/test-eslint-prefer-assert-iferror.js @@ -14,12 +14,18 @@ new RuleTester().run('prefer-assert-iferror', rule, { ], invalid: [ { - code: 'if (err) throw err;', - errors: [{ message: 'Use assert.ifError(err) instead.' }] + code: 'require("assert");\n' + + 'if (err) throw err;', + errors: [{ message: 'Use assert.ifError(err) instead.' }], + output: 'require("assert");\n' + + 'assert.ifError(err);' }, { - code: 'if (error) { throw error; }', - errors: [{ message: 'Use assert.ifError(error) instead.' }] + code: 'require("assert");\n' + + 'if (error) { throw error; }', + errors: [{ message: 'Use assert.ifError(error) instead.' }], + output: 'require("assert");\n' + + 'assert.ifError(error);' } ] }); diff --git a/tools/eslint-rules/prefer-assert-iferror.js b/tools/eslint-rules/prefer-assert-iferror.js index e15287417693e0..399ee7403a6c88 100644 --- a/tools/eslint-rules/prefer-assert-iferror.js +++ b/tools/eslint-rules/prefer-assert-iferror.js @@ -5,9 +5,12 @@ 'use strict'; +const utils = require('./rules-utils.js'); + module.exports = { create(context) { const sourceCode = context.getSourceCode(); + var assertImported = false; function hasSameTokens(nodeA, nodeB) { const aTokens = sourceCode.getTokens(nodeA); @@ -20,8 +23,15 @@ module.exports = { }); } + function checkAssertNode(node) { + if (utils.isRequired(node, ['assert'])) { + assertImported = true; + } + } + return { - IfStatement(node) { + 'CallExpression': (node) => checkAssertNode(node), + 'IfStatement': (node) => { const firstStatement = node.consequent.type === 'BlockStatement' ? node.consequent.body[0] : node.consequent; @@ -30,10 +40,19 @@ module.exports = { firstStatement.type === 'ThrowStatement' && hasSameTokens(node.test, firstStatement.argument) ) { + const argument = sourceCode.getText(node.test); context.report({ node: firstStatement, message: 'Use assert.ifError({{argument}}) instead.', - data: { argument: sourceCode.getText(node.test) } + data: { argument }, + fix: (fixer) => { + if (assertImported) { + return fixer.replaceText( + node, + `assert.ifError(${argument});` + ); + } + } }); } }