Skip to content

Commit

Permalink
fix(linter): rule no-restricted-imports support missing options - bui…
Browse files Browse the repository at this point in the history
…ld regex in `from_configuration`
  • Loading branch information
Sysix committed Dec 26, 2024
1 parent 0da9b9d commit 87d8da7
Showing 1 changed file with 35 additions and 19 deletions.
54 changes: 35 additions & 19 deletions crates/oxc_linter/src/rules/eslint/no_restricted_imports.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@ use oxc_macros::declare_oxc_lint;
use oxc_span::{CompactStr, Span};
use regex::Regex;
use rustc_hash::FxHashMap;
use serde::Deserialize;
use serde::{de::Error, Deserialize, Deserializer};
use serde_json::Value;
use std::borrow::Cow;

use crate::{
context::LintContext,
Expand Down Expand Up @@ -58,15 +59,42 @@ struct RestrictedPath {
#[serde(rename_all = "camelCase")]
struct RestrictedPattern {
group: Option<Vec<CompactStr>>,
regex: Option<CompactStr>,
regex: Option<SerdeRegexWrapper<Regex>>,
import_names: Option<Vec<CompactStr>>,
import_name_pattern: Option<CompactStr>,
import_name_pattern: Option<SerdeRegexWrapper<Regex>>,
allow_import_names: Option<Vec<CompactStr>>,
allow_import_name_pattern: Option<CompactStr>,
allow_import_name_pattern: Option<SerdeRegexWrapper<Regex>>,
case_sensitive: Option<bool>,
message: Option<CompactStr>,
}

/// A wrapper type which implements `Serialize` and `Deserialize` for
/// types involving `Regex`
#[derive(Debug, Clone, Eq, Hash, PartialEq)]
pub struct SerdeRegexWrapper<T>(pub T);

impl std::ops::Deref for SerdeRegexWrapper<Regex> {
type Target = Regex;

fn deref(&self) -> &Self::Target {
&self.0
}
}

impl<'de> Deserialize<'de> for SerdeRegexWrapper<Regex> {
fn deserialize<D>(d: D) -> Result<SerdeRegexWrapper<Regex>, D::Error>
where
D: Deserializer<'de>,
{
let s = <Cow<str>>::deserialize(d)?;

match s.parse() {
Ok(regex) => Ok(SerdeRegexWrapper(regex)),
Err(err) => Err(D::Error::custom(err)),
}
}
}

#[derive(Debug)]
enum GlobResult {
Found,
Expand Down Expand Up @@ -323,35 +351,23 @@ impl RestrictedPattern {
return false;
};

let Ok(reg_exp) = Regex::new(regex.as_str()) else {
return false;
};

reg_exp.find(name.name()).is_some()
regex.find(name.name()).is_some()
}

fn get_import_name_pattern_result(&self, name: &CompactStr) -> bool {
let Some(import_name_pattern) = &self.import_name_pattern else {
return false;
};

let Ok(reg_exp) = Regex::new(import_name_pattern.as_str()) else {
return false;
};

reg_exp.find(name).is_some()
import_name_pattern.find(name).is_some()
}

fn get_allow_import_name_pattern_result(&self, name: &CompactStr) -> bool {
let Some(allow_import_names) = &self.allow_import_name_pattern else {
return false;
};

let Ok(reg_exp) = Regex::new(allow_import_names.as_str()) else {
return false;
};

reg_exp.find(name).is_some()
allow_import_names.find(name).is_some()
}
}

Expand Down

0 comments on commit 87d8da7

Please sign in to comment.