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: remove redudant code from eslint require rule #54892

Merged
merged 1 commit into from
Sep 23, 2024
Merged
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
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;
},
};
Loading