0
0
mirror of https://github.com/nodejs/node.git synced 2024-11-28 06:28:40 +01:00
nodejs/tools/eslint-rules/no-duplicate-requires.js
Rich Trott e7d4e6b680 tools: remove conditional assignment in custom ESLint rule
These changes no-duplicate-require.js so that it doesn't use an
assignment in a conditional, which can be easy to misread as a
comparison rather than an assignment. It also means we change a do/while
(which we don't use much in our code) to the much more common while
construct.

PR-URL: https://github.com/nodejs/node/pull/41325
Reviewed-By: Michaël Zasso <targos@protonmail.com>
2022-01-05 06:11:29 -08:00

66 lines
1.5 KiB
JavaScript

/**
* @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
//------------------------------------------------------------------------------
const secondLevelTypes = [
'FunctionDeclaration', 'FunctionExpression', 'ArrowFunctionExpression',
'ClassBody', 'MethodDefinition',
];
function isTopLevel(node) {
while (!secondLevelTypes.includes(node.type)) {
node = node.parent;
if (!node) {
return true;
}
}
return false;
}
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;
};