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

feat: importNamePattern option in no-restricted-imports #17721

Merged
merged 7 commits into from
Dec 1, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
39 changes: 39 additions & 0 deletions docs/src/rules/no-restricted-imports.md
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,19 @@ Pattern matches can restrict specific import names only, similar to the `paths`
}]
```

Regex patterns can also be used to restrict specific import Name:

```json
"no-restricted-imports": ["error", {
"patterns": [{
"group": ["import-foo/*"],
"importNamePatterns": "^foo",
}]
}]
```

**Note:** In patterns array `importNames` and `importNamePatterns` can not be used together. If they are used together then the `importNames` will be considered.
mdjermanovic marked this conversation as resolved.
Show resolved Hide resolved

To restrict the use of all Node.js core imports (via <https://github.com/nodejs/node/tree/master/lib>):

```json
Expand Down Expand Up @@ -264,6 +277,18 @@ import pick from 'fooBar';
import { isEmpty } from 'utils/collection-utils';
```

::: incorrect { "sourceType": "module" }
mdjermanovic marked this conversation as resolved.
Show resolved Hide resolved

```js
/*eslint no-restricted-imports: ["error", { patterns: [{
group: ["utils/*"],
importNamePatterns: '^is',
message: "Use 'isEmpty' from lodash instead."
mdjermanovic marked this conversation as resolved.
Show resolved Hide resolved
}]}]*/

import { isEmpty } from 'utils/collection-utils';
```

:::

Examples of **correct** code for this rule:
Expand Down Expand Up @@ -355,6 +380,20 @@ import { hasValues } from 'utils/collection-utils';

:::

::: correct { "sourceType": "module" }

```js
/*eslint no-restricted-imports: ["error", { patterns: [{
group: ["utils/*"],
importNamePatterns: '^is',
message: "Use 'isEmpty' from lodash instead."
mdjermanovic marked this conversation as resolved.
Show resolved Hide resolved
}]}]*/

import isEmpty, { hasValue } from 'utils/collection-utils';
```

:::

## When Not To Use It

Don't use this rule or don't include a module in the list for this rule if you want to be able to import a module in your project without an ESLint error or warning.
63 changes: 53 additions & 10 deletions lib/rules/no-restricted-imports.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,9 @@ const arrayOfStringsOrObjectPatterns = {
minItems: 1,
uniqueItems: true
},
importNamePatterns: {
mdjermanovic marked this conversation as resolved.
Show resolved Hide resolved
type: "string"
},
message: {
type: "string",
minLength: 1
Expand Down Expand Up @@ -115,8 +118,12 @@ module.exports = {
patternAndImportNameWithCustomMessage: "'{{importName}}' import from '{{importSource}}' is restricted from being used by a pattern. {{customMessage}}",

patternAndEverything: "* import is invalid because '{{importNames}}' from '{{importSource}}' is restricted from being used by a pattern.",

patternAndEverythingWithRegexImportName: "* import is invalid because import name with '{{importNames}}' regex pattern from '{{importSource}}' is restricted from being used by a pattern.",
mdjermanovic marked this conversation as resolved.
Show resolved Hide resolved
// eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period
patternAndEverythingWithCustomMessage: "* import is invalid because '{{importNames}}' from '{{importSource}}' is restricted from being used by a pattern. {{customMessage}}",
// eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period
patternAndEverythingWithRegexImportNameAndCustomMessage: "* import is invalid because import name with '{{importNames}}' regex pattern from '{{importSource}}' is restricted from being used by a pattern. {{customMessage}}",
mdjermanovic marked this conversation as resolved.
Show resolved Hide resolved

everything: "* import is invalid because '{{importNames}}' from '{{importSource}}' is restricted.",
// eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period
Expand Down Expand Up @@ -175,10 +182,11 @@ module.exports = {
}

// relative paths are supported for this rule
const restrictedPatternGroups = restrictedPatterns.map(({ group, message, caseSensitive, importNames }) => ({
const restrictedPatternGroups = restrictedPatterns.map(({ group, message, caseSensitive, importNames, importNamePatterns }) => ({
matcher: ignore({ allowRelativePaths: true, ignorecase: !caseSensitive }).add(group),
customMessage: message,
importNames
importNames,
importNamePattern: new RegExp(importNamePatterns, "u")
}));

// if no imports are restricted we don't need to check
Expand Down Expand Up @@ -262,20 +270,55 @@ module.exports = {

const customMessage = group.customMessage;
const restrictedImportNames = group.importNames;
const restrictedImportNamePattern = group.importNamePattern;

/*
* If we are not restricting to any specific import names and just the pattern itself,
* report the error and move on
*/
if (!restrictedImportNames) {
context.report({
node,
messageId: customMessage ? "patternWithCustomMessage" : "patterns",
data: {
importSource,
customMessage
}
});
if (!restrictedImportNamePattern.test("")) {
mdjermanovic marked this conversation as resolved.
Show resolved Hide resolved
importNames.forEach((specifiers, importName) => {
specifiers.forEach(specifier => {
if (!restrictedImportNamePattern.test(importName)) {
if (importName === "*") {
context.report({
node,
messageId: customMessage ? "patternAndEverythingWithRegexImportNameAndCustomMessage" : "patternAndEverythingWithRegexImportName",
loc: specifier.loc,
data: {
importSource,
importNames: restrictedImportNamePattern,
customMessage
}
});
}

return;
}

context.report({
node,
messageId: customMessage ? "patternAndImportNameWithCustomMessage" : "patternAndImportName",
loc: specifier.loc,
data: {
importSource,
importName,
customMessage
}
});
});
});
} else {
context.report({
node,
messageId: customMessage ? "patternWithCustomMessage" : "patterns",
data: {
importSource,
customMessage
}
});
}
return;
}

Expand Down
115 changes: 115 additions & 0 deletions tests/lib/rules/no-restricted-imports.js
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,15 @@ ruleTester.run("no-restricted-imports", rule, {
importNames: ["Foo"]
}]
}]
},
{
code: "import Foo from '../../my/relative-module';",
options: [{
patterns: [{
group: ["**/my/relative-module"],
importNamePatterns: "^Foo"
}]
}]
}
],
invalid: [{
Expand Down Expand Up @@ -1235,6 +1244,112 @@ ruleTester.run("no-restricted-imports", rule, {
endColumn: 11,
message: "'default' import from 'mod' is restricted from being used by a pattern."
}]
},
{
code: "import { Foo } from '../../my/relative-module';",
options: [{
patterns: [{
group: ["**/my/relative-module"],
importNamePatterns: "^Foo"
}]
}],
errors: [{
type: "ImportDeclaration",
line: 1,
column: 10,
endColumn: 13,
message: "'Foo' import from '../../my/relative-module' is restricted from being used by a pattern."
}]
},
{
code: "import { FooBar } from '../../my/relative-module';",
options: [{
patterns: [{
group: ["**/my/relative-module"],
importNamePatterns: "^Foo"
}]
}],
errors: [{
type: "ImportDeclaration",
line: 1,
column: 10,
endColumn: 16,
message: "'FooBar' import from '../../my/relative-module' is restricted from being used by a pattern."
}]
},
{
code: "import Foo, { Bar } from '../../my/relative-module';",
options: [{
patterns: [{
group: ["**/my/relative-module"],
importNamePatterns: "^Foo|^Bar"
}]
}],
errors: [{
type: "ImportDeclaration",
line: 1,
column: 15,
endColumn: 18,
message: "'Bar' import from '../../my/relative-module' is restricted from being used by a pattern."
}]
},
{
code: "import { Foo, Bar } from '../../my/relative-module';",
options: [{
patterns: [{
group: ["**/my/relative-module"],
importNamePatterns: "^Foo|^Bar"
}]
}],
errors: [
{
type: "ImportDeclaration",
line: 1,
column: 10,
endColumn: 13,
message: "'Foo' import from '../../my/relative-module' is restricted from being used by a pattern."
},
{
type: "ImportDeclaration",
line: 1,
column: 15,
endColumn: 18,
message: "'Bar' import from '../../my/relative-module' is restricted from being used by a pattern."
}
]
},
{
code: "import * as All from '../../my/relative-module';",
options: [{
patterns: [{
group: ["**/my/relative-module"],
importNamePatterns: "^Foo"
}]
}],
errors: [{
message: "* import is invalid because import name with '/^Foo/u' regex pattern from '../../my/relative-module' is restricted from being used by a pattern.",
type: "ImportDeclaration",
line: 1,
column: 8,
endColumn: 16
}]
},
{
code: "import * as AllWithCustomMessage from '../../my/relative-module';",
options: [{
patterns: [{
group: ["**/my/relative-module"],
importNamePatterns: "^Foo",
message: "Import from @/utils instead."
}]
}],
errors: [{
message: "* import is invalid because import name with '/^Foo/u' regex pattern from '../../my/relative-module' is restricted from being used by a pattern. Import from @/utils instead.",
type: "ImportDeclaration",
line: 1,
column: 8,
endColumn: 33
}]
}
]
});