forked from nodejs/node
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprefer-assert-iferror.js
61 lines (54 loc) · 1.63 KB
/
prefer-assert-iferror.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/**
* @fileoverview Prohibit the `if (err) throw err;` pattern
* @author Teddy Katz
*/
'use strict';
const utils = require('./rules-utils.js');
module.exports = {
create(context) {
const sourceCode = context.getSourceCode();
let assertImported = false;
function hasSameTokens(nodeA, nodeB) {
const aTokens = sourceCode.getTokens(nodeA);
const bTokens = sourceCode.getTokens(nodeB);
return aTokens.length === bTokens.length &&
aTokens.every((token, index) => {
return token.type === bTokens[index].type &&
token.value === bTokens[index].value;
});
}
function checkAssertNode(node) {
if (utils.isRequired(node, ['assert'])) {
assertImported = true;
}
}
return {
'CallExpression': (node) => checkAssertNode(node),
'IfStatement': (node) => {
const firstStatement = node.consequent.type === 'BlockStatement' ?
node.consequent.body[0] :
node.consequent;
if (
firstStatement &&
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 },
fix: (fixer) => {
if (assertImported) {
return fixer.replaceText(
node,
`assert.ifError(${argument});`
);
}
}
});
}
}
};
}
};