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 4 commits
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
67 changes: 67 additions & 0 deletions docs/src/rules/no-restricted-imports.md
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/*"],
"importNamePattern": "^foo",
}]
}]
```

**Note:** If `importNames` and `importNamePattern` are used together, it initially reviews the value specified in `importNames`. Afterward, it focuses on assessing the value specified in `importNamePattern`.
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,46 @@ 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/*"],
importNamePattern: '^is',
message: "Use 'isEmpty' from lodash instead."
mdjermanovic marked this conversation as resolved.
Show resolved Hide resolved
}]}]*/

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

:::

::: incorrect { "sourceType": "module" }

```js
/*eslint no-restricted-imports: ["error", { patterns: [{
group: ["foo/*"],
importNamePattern: '^(is|bar)',
message: "Use 'isBar' from baz/bar instead"
}]}]*/

import bar, { isBar } from 'foo/bar';
mdjermanovic marked this conversation as resolved.
Show resolved Hide resolved
```

:::

::: incorrect { "sourceType": "module" }

```js
/*eslint no-restricted-imports: ["error", { patterns: [{
importNames: ["foo"],
group: ["foo/*"],
importNamePattern: '^bar',
}]}]*/

import { bar } from 'foo/bar';
mdjermanovic marked this conversation as resolved.
Show resolved Hide resolved
```

:::

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

:::

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

```js
/*eslint no-restricted-imports: ["error", { patterns: [{
group: ["utils/*"],
importNamePattern: '^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.
116 changes: 90 additions & 26 deletions lib/rules/no-restricted-imports.js
Expand Up @@ -74,6 +74,9 @@ const arrayOfStringsOrObjectPatterns = {
minItems: 1,
uniqueItems: true
},
importNamePattern: {
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 matching '{{importNames}}' pattern from '{{importSource}}' is restricted from being used.",
// 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 matching '{{importNames}}' pattern from '{{importSource}}' is restricted from being used. {{customMessage}}",

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, importNamePattern }) => ({
matcher: ignore({ allowRelativePaths: true, ignorecase: !caseSensitive }).add(group),
customMessage: message,
importNames
importNames,
importNamePattern
}));

// if no imports are restricted we don't need to check
Expand Down Expand Up @@ -248,6 +256,29 @@ module.exports = {
}
}

/**
* Report a restricted path specifically for patterns.
* @param {node} node representing the restricted path reference
* @param {string} importSource representing the restricted import pattern
* @param {string} importName representing restricted import name
* @param {Object} specifier contains location of the node
* @param {string} customMessage contains message related to the restricted import name or pattern
* @returns {void}
* @private
*/
function reportPatternAndImportName(node, importSource, importName, specifier, customMessage) {
context.report({
node,
messageId: customMessage ? "patternAndImportNameWithCustomMessage" : "patternAndImportName",
loc: specifier.loc,
data: {
importSource,
customMessage,
importName
}
});
}

/**
* Report a restricted path specifically for patterns.
* @param {node} node representing the restricted path reference
Expand All @@ -262,20 +293,46 @@ module.exports = {

const customMessage = group.customMessage;
const restrictedImportNames = group.importNames;
const restrictedImportNamePattern = !group.importNamePattern ? null : new RegExp(group.importNamePattern, "u");
mdjermanovic marked this conversation as resolved.
Show resolved Hide resolved

/*
* 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) {
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;
}

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

Expand All @@ -294,26 +351,33 @@ module.exports = {
});
}

restrictedImportNames.forEach(importName => {
if (!importNames.has(importName)) {
return;
}

const specifiers = importNames.get(importName);
if (restrictedImportNamePattern) {
mdjermanovic marked this conversation as resolved.
Show resolved Hide resolved
importNames.forEach((specifiers, importName) => {
specifiers.forEach(specifier => {
if (restrictedImportNames.includes(importName)) {
reportPatternAndImportName(node, importSource, importName, specifier, customMessage);
} else {
if (!restrictedImportNamePattern.test(importName)) {
return;
}

specifiers.forEach(specifier => {
context.report({
node,
messageId: customMessage ? "patternAndImportNameWithCustomMessage" : "patternAndImportName",
loc: specifier.loc,
data: {
importSource,
customMessage,
importName
reportPatternAndImportName(node, importSource, importName, specifier, customMessage);
}
});
});
});
} else {
restrictedImportNames.forEach(importName => {
if (!importNames.has(importName)) {
return;
}

const specifiers = importNames.get(importName);

specifiers.forEach(specifier => {
reportPatternAndImportName(node, importSource, importName, specifier, customMessage);
});
});
}
}

/**
Expand Down