forked from nodejs/node
-
Notifications
You must be signed in to change notification settings - Fork 0
/
no-duplicate-requires.js
64 lines (54 loc) · 1.57 KB
/
no-duplicate-requires.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
62
63
64
/**
* @fileoverview Ensure modules are not required twice at top level of a module
* @author devsnek
*/
'use strict';
const { isRequireCall, isString } = require('./rules-utils.js');
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
function isTopLevel(node) {
do {
if (node.type === 'FunctionDeclaration' ||
node.type === 'FunctionExpression' ||
node.type === 'ArrowFunctionExpression' ||
node.type === 'ClassBody' ||
node.type === 'MethodDefinition') {
return false;
}
} while (node = node.parent);
return true;
}
module.exports = (context) => {
if (context.parserOptions.sourceType === 'module') {
return {};
}
function getRequiredModuleNameFromCall(node) {
// Node has arguments and first argument is string
if (node.arguments.length && isString(node.arguments[0])) {
return node.arguments[0].value.trim();
}
return undefined;
}
const required = new Set();
const rules = {
CallExpression: (node) => {
if (isRequireCall(node) && isTopLevel(node)) {
const moduleName = getRequiredModuleNameFromCall(node);
if (moduleName === undefined) {
return;
}
if (required.has(moduleName)) {
context.report(
node,
'\'{{moduleName}}\' require is duplicated.',
{ moduleName }
);
} else {
required.add(moduleName);
}
}
},
};
return rules;
};