From f71f6ba5228b43ae3254c84deb5d78698a172452 Mon Sep 17 00:00:00 2001 From: Justin braun Date: Thu, 2 Mar 2023 11:17:19 +0100 Subject: [PATCH] + Added no-index-import rule to prevent cyclic imports --- src/index.js | 1 + src/rules/no-index-import.js | 40 ++++++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+) create mode 100644 src/rules/no-index-import.js diff --git a/src/index.js b/src/index.js index 15f98d96f..72501833a 100644 --- a/src/index.js +++ b/src/index.js @@ -15,6 +15,7 @@ export const rules = { 'consistent-type-specifier-style': require('./rules/consistent-type-specifier-style'), 'no-self-import': require('./rules/no-self-import'), + 'no-index-import': require('./rules/no-index-import'), 'no-cycle': require('./rules/no-cycle'), 'no-named-default': require('./rules/no-named-default'), 'no-named-as-default': require('./rules/no-named-as-default'), diff --git a/src/rules/no-index-import.js b/src/rules/no-index-import.js new file mode 100644 index 000000000..7fa670e6c --- /dev/null +++ b/src/rules/no-index-import.js @@ -0,0 +1,40 @@ +/** + * @fileOverview Forbids a module from importing itself + * @author Gio d'Amelio + */ + +import resolve from 'eslint-module-utils/resolve'; +import moduleVisitor from 'eslint-module-utils/moduleVisitor'; +import docsUrl from '../docsUrl'; + +var path = require('path'); +const isIndexRegex = /index\.(ts|js)/; +const isNodeModuleRegex = /node_modules/; + +module.exports = { + meta: { + type: 'problem', + docs: { + category: 'Static analysis', + description: 'Forbid a module to import any index to prevent cyclic imports', + recommended: false, + url: docsUrl('no-index-import'), + }, + schema: [], + }, + create(context) { + return moduleVisitor((source, node) => { + const filePath = context.getPhysicalFilename ? context.getPhysicalFilename() : context.getFilename(); + const fileName = path.basename(filePath); + const resolved = resolve(source.value, context); + const resolveFileName = path.basename(resolved); + + if (!isNodeModuleRegex.test(resolved) && !isIndexRegex.test(fileName) && isIndexRegex.test(resolveFileName)) { + context.report({ + node, + message: 'Index imports are not allowed', + }); + } + }, {commonjs: true}); + }, +};