Skip to content

Commit

Permalink
tools: remove redudant code from eslint require rule
Browse files Browse the repository at this point in the history
PR-URL: nodejs#54892
Reviewed-By: James M Snell <[email protected]>
Reviewed-By: Antoine du Hamel <[email protected]>
  • Loading branch information
RedYetiDev authored and louwers committed Nov 2, 2024
1 parent c6cc4a6 commit fc3201f
Showing 1 changed file with 22 additions and 35 deletions.
57 changes: 22 additions & 35 deletions tools/eslint-rules/no-duplicate-requires.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
/**
* @fileoverview Ensure modules are not required twice at top level of a module
* @author devsnek
* @author RedYetiDev
*/
'use strict';

Expand All @@ -10,58 +11,44 @@ const { isRequireCall, isString } = require('./rules-utils.js');
// Rule Definition
//------------------------------------------------------------------------------

const secondLevelTypes = [
const topLevelTypes = new Set([
'FunctionDeclaration', 'FunctionExpression', 'ArrowFunctionExpression',
'ClassBody', 'MethodDefinition',
];
]);

function isTopLevel(node) {
while (!secondLevelTypes.includes(node.type)) {
const isTopLevel = (node) => {
while (node) {
if (topLevelTypes.has(node.type)) return false;
node = node.parent;
if (!node) {
return true;
}
}
return false;
}
return true;
};

module.exports = {
create(context) {
if (context.languageOptions.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 requiredModules = new Set();

const required = new Set();

const rules = {
CallExpression: (node) => {
return {
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);
const [firstArg] = node.arguments;
if (isString(firstArg)) {
const moduleName = firstArg.value.trim();
if (requiredModules.has(moduleName)) {
context.report({
node,
message: `'${moduleName}' require is duplicated.`,
});
} else {
requiredModules.add(moduleName);
}
}
}
},
};

return rules;
},
};

0 comments on commit fc3201f

Please sign in to comment.