Skip to content

Commit

Permalink
tools: add fixer for prefer-assert-iferror.js
Browse files Browse the repository at this point in the history
PR-URL: #16648
Refs: #16636
Reviewed-By: Anatoli Papirovski <[email protected]>
Reviewed-By: Gibson Fahnestock <[email protected]>
Reviewed-By: James M Snell <[email protected]>
Reviewed-By: Ruben Bridgewater <[email protected]>
  • Loading branch information
shobhitchittora authored and MylesBorins committed Feb 21, 2018
1 parent 5439154 commit a33dc81
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 6 deletions.
14 changes: 10 additions & 4 deletions test/parallel/test-eslint-prefer-assert-iferror.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);'
}
]
});
23 changes: 21 additions & 2 deletions tools/eslint-rules/prefer-assert-iferror.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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;
Expand All @@ -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});`
);
}
}
});
}
}
Expand Down

0 comments on commit a33dc81

Please sign in to comment.