Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

tools: auto fix custom eslint rule for prefer-assert-iferror.js #16648

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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