Skip to content
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
30 changes: 11 additions & 19 deletions crates/oxc_linter/src/rules/import/no_unassigned_import.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
use globset::{Glob, GlobSet, GlobSetBuilder};
use oxc_ast::{
AstKind,
ast::{Argument, Expression},
Expand All @@ -21,7 +20,7 @@ pub struct NoUnassignedImport(Box<NoUnassignedImportConfig>);

#[derive(Debug, Default, Clone)]
pub struct NoUnassignedImportConfig {
globs: GlobSet,
globs: Vec<CompactStr>,
}

impl std::ops::Deref for NoUnassignedImport {
Expand Down Expand Up @@ -71,36 +70,23 @@ declare_oxc_lint!(
suspicious,
);

fn build_globset(patterns: Vec<CompactStr>) -> Result<GlobSet, globset::Error> {
if patterns.is_empty() {
return Ok(GlobSet::empty());
}
let mut builder = GlobSetBuilder::new();
for pattern in patterns {
let pattern_str = pattern.as_str();
builder.add(Glob::new(pattern_str)?);
}
builder.build()
}

impl Rule for NoUnassignedImport {
fn from_configuration(value: Value) -> Self {
let obj = value.get(0);
let allow = obj
let globs = obj
.and_then(|v| v.get("allow"))
.and_then(Value::as_array)
.map(|v| v.iter().filter_map(Value::as_str).map(CompactStr::from).collect())
.unwrap_or_default();
Self(Box::new(NoUnassignedImportConfig { globs: build_globset(allow).unwrap_or_default() }))
Self(Box::new(NoUnassignedImportConfig { globs }))
}
fn run<'a>(&self, node: &AstNode<'a>, ctx: &LintContext<'a>) {
match node.kind() {
AstKind::ImportDeclaration(import_decl) => {
if import_decl.specifiers.is_some() {
return;
}
let source_str = import_decl.source.value.as_str();
if !self.globs.is_match(source_str) {
if !self.is_match_allow_globs(import_decl.source.value.as_str()) {
ctx.diagnostic(no_unassigned_import_diagnostic(
import_decl.span,
"Imported module should be assigned",
Expand All @@ -118,7 +104,7 @@ impl Rule for NoUnassignedImport {
let Argument::StringLiteral(source_str) = first_arg else {
return;
};
if !self.globs.is_match(source_str.value.as_str()) {
if !self.is_match_allow_globs(source_str.value.as_str()) {
ctx.diagnostic(no_unassigned_import_diagnostic(
call_expr.span,
"A `require()` style import is forbidden.",
Expand All @@ -130,6 +116,12 @@ impl Rule for NoUnassignedImport {
}
}

impl NoUnassignedImportConfig {
fn is_match_allow_globs(&self, source: &str) -> bool {
self.globs.iter().any(|glob| fast_glob::glob_match(glob.as_str(), source))
}
}

#[test]
fn test() {
use crate::tester::Tester;
Expand Down
Loading