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(lint/noRestrictedImports): add rule #1723

Merged
merged 3 commits into from
Feb 6, 2024
Merged
Show file tree
Hide file tree
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
1 change: 1 addition & 0 deletions crates/biome_diagnostics_categories/src/categories.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ define_categories! {
"lint/nursery/noMisleadingCharacterClass": "https://biomejs.dev/linter/rules/no-misleading-character-class",
"lint/nursery/noNodejsModules": "https://biomejs.dev/linter/rules/no-nodejs-modules",
"lint/nursery/noReExportAll": "https://biomejs.dev/linter/rules/no-re-export-all",
"lint/nursery/noRestrictedImports": "https://biomejs.dev/linter/rules/no-restricted-imports",
"lint/nursery/noSkippedTests": "https://biomejs.dev/linter/rules/no-skipped-tests",
"lint/nursery/noThenProperty": "https://biomejs.dev/linter/rules/no-then-property",
"lint/nursery/noTypeOnlyImportAttributes": "https://biomejs.dev/linter/rules/no-type-only-import-attributes",
Expand Down
2 changes: 2 additions & 0 deletions crates/biome_js_analyze/src/analyzers/nursery.rs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
use biome_analyze::context::RuleContext;
use biome_analyze::{declare_rule, Ast, Rule, RuleDiagnostic, RuleSource};
use biome_console::markup;
use biome_deserialize_macros::Deserializable;
use biome_js_syntax::inner_string_text;
use biome_rowan::TextRange;
use rustc_hash::FxHashMap;
use serde::{Deserialize, Serialize};

use super::use_nodejs_import_protocol::AnyJsImportLike;

declare_rule! {
/// Disallow specified modules when loaded by import or require.
///
/// ## Options
///
/// ```json
/// {
/// "noRestrictedImports": {
/// "options": {
/// "paths": {
/// "lodash": "Using lodash is not encouraged",
/// "underscore": "Using underscore is not encouraged"
/// }
/// }
/// }
/// }
/// ```
pub(crate) NoRestrictedImports {
version: "next",
name: "noRestrictedImports",
source: RuleSource::Eslint("no-restricted-imports"),
recommended: false,
}
}

/// Options for the rule `noRestrictedImports`.
#[derive(Clone, Debug, Default, Deserialize, Deserializable, Eq, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct RestrictedImportsOptions {
/// A list of names that should trigger the rule
#[serde(skip_serializing_if = "FxHashMap::is_empty")]
paths: FxHashMap<String, String>,
}

impl Rule for NoRestrictedImports {
type Query = Ast<AnyJsImportLike>;
type State = (TextRange, String);
anonrig marked this conversation as resolved.
Show resolved Hide resolved
type Signals = Option<Self::State>;
type Options = RestrictedImportsOptions;

fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let module_name = ctx.query().module_name_token()?;
let inner_text = inner_string_text(&module_name);

ctx.options()
.paths
.get(inner_text.text())
.map(|message| (module_name.text_trimmed_range(), message.to_string()))
anonrig marked this conversation as resolved.
Show resolved Hide resolved
}

fn diagnostic(_ctx: &RuleContext<Self>, (span, text): &Self::State) -> Option<RuleDiagnostic> {
Some(RuleDiagnostic::new(
rule_category!(),
*span,
markup! {
{text}
},
))
}
}
12 changes: 12 additions & 0 deletions crates/biome_js_analyze/src/options.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
//! This module contains the rules that have options

use crate::analyzers::nursery::no_restricted_imports::RestrictedImportsOptions;
use crate::analyzers::nursery::use_consistent_array_type::ConsistentArrayTypeOptions;
use crate::analyzers::nursery::use_filenaming_convention::FilenamingConventionOptions;
use crate::semantic_analyzers::correctness::use_exhaustive_dependencies::HooksOptions;
Expand Down Expand Up @@ -37,6 +38,8 @@ pub enum PossibleOptions {
NamingConvention(NamingConventionOptions),
/// Options for `noRestrictedGlobals` rule
RestrictedGlobals(RestrictedGlobalsOptions),
/// Options for `noRestrictedImports` rule
RestrictedImports(RestrictedImportsOptions),
/// Options for `useValidAriaRole` rule
ValidAriaRole(ValidAriaRoleOptions),
/// Options for `useSortedClasses` rule
Expand Down Expand Up @@ -101,6 +104,13 @@ impl PossibleOptions {
};
RuleOptions::new(options)
}
"noRestrictedImports" => {
let options = match self {
PossibleOptions::RestrictedImports(options) => options.clone(),
_ => RestrictedImportsOptions::default(),
};
RuleOptions::new(options)
}
"useValidAriaRole" => {
let options = match self {
PossibleOptions::ValidAriaRole(options) => options.clone(),
Expand Down Expand Up @@ -133,6 +143,8 @@ impl Deserializable for PossibleOptions {
}
"noRestrictedGlobals" => Deserializable::deserialize(value, "options", diagnostics)
.map(Self::RestrictedGlobals),
"noRestrictedImports" => Deserializable::deserialize(value, "options", diagnostics)
.map(Self::RestrictedImports),
"useConsistentArrayType" => Deserializable::deserialize(value, "options", diagnostics)
.map(Self::ConsistentArrayType),
"useExhaustiveDependencies" => {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
import eslint from 'eslint';
const l = require('lodash');
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
---
source: crates/biome_js_analyze/tests/spec_tests.rs
expression: invalid.js
---
# Input
```jsx
import eslint from 'eslint';
const l = require('lodash');

```

# Diagnostics
```
invalid.js:1:20 lint/nursery/noRestrictedImports ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

! Importing Eslint is forbidden

> 1 │ import eslint from 'eslint';
│ ^^^^^^^^
2 │ const l = require('lodash');
3 │


```

```
invalid.js:2:19 lint/nursery/noRestrictedImports ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

! It's not recommended to use lodash

1 │ import eslint from 'eslint';
> 2 │ const l = require('lodash');
│ ^^^^^^^^
3 │


```


Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"$schema": "../../../../../../packages/@biomejs/biome/configuration_schema.json",
"linter": {
"enabled": true,
"rules": {
"nursery": {
"noRestrictedImports": {
"level": "error",
"options": {
"paths": {
"eslint": "Importing Eslint is forbidden",
"lodash": "It's not recommended to use lodash"
}
}
}
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
const path = require('lodash');
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
source: crates/biome_js_analyze/tests/spec_tests.rs
expression: valid.js
---
# Input
```jsx
const path = require('lodash');

```


Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"$schema": "../../../../../../packages/@biomejs/biome/configuration_schema.json",
"linter": {
"rules": {
"nursery": {
"noRestrictedImports": {
"level": "error",
"options": {
"paths": {}
}
}
}
}
}
}
Loading
Loading