refactor(linter): clean up diagnostics

This commit is contained in:
Boshen 2024-05-12 11:23:26 +08:00
parent 570a45add3
commit f7a37739c8
No known key found for this signature in database
GPG key ID: 9C7A8C8AB22BEBD1
4 changed files with 35 additions and 91 deletions

View file

@ -1,46 +0,0 @@
use oxc_diagnostics::{
miette::{self, Diagnostic},
thiserror::Error,
Report,
};
use std::path::PathBuf;
#[derive(Debug, Error, Diagnostic)]
#[error("Failed to parse config {0:?} with error {1:?}")]
#[diagnostic()]
pub struct FailedToParseConfigJsonError(pub PathBuf, pub String);
#[derive(Debug, Error, Diagnostic)]
#[error("Failed to parse eslint config")]
#[diagnostic()]
pub struct FailedToParseConfigError(#[related] pub Vec<Report>);
#[derive(Debug, Error, Diagnostic)]
#[error("Failed to parse config with error {0:?}")]
#[diagnostic()]
pub struct FailedToParseConfigPropertyError(pub String);
#[derive(Debug, Error, Diagnostic)]
#[error("Failed to rule value {0:?} with error {1:?}")]
#[diagnostic()]
pub struct FailedToParseRuleValueError(pub String, pub &'static str);
#[derive(Debug, Error, Diagnostic)]
#[error(r#"Failed to parse rule severity, expected one of "allow", "off", "deny", "error" or "warn", but got {0:?}"#)]
#[diagnostic()]
pub struct FailedToParseAllowWarnDenyFromStringError(pub String);
#[derive(Debug, Error, Diagnostic)]
#[error(r#"Failed to parse rule severity, expected one of `0`, `1` or `2`, but got {0:?}"#)]
#[diagnostic()]
pub struct FailedToParseAllowWarnDenyFromNumberError(pub String);
#[derive(Debug, Error, Diagnostic)]
#[error(r#"Failed to parse rule severity, expected a string or a number, but got {0:?}"#)]
#[diagnostic()]
pub struct FailedToParseAllowWarnDenyFromJsonValueError(pub String);
#[derive(Debug, Error, Diagnostic)]
#[error("Failed to parse jsonc file {0:?}")]
#[diagnostic()]
pub struct FailedToParseJsonc(pub PathBuf);

View file

@ -1,21 +1,16 @@
mod env;
pub mod errors;
mod globals;
mod rules;
mod settings;
use std::path::Path;
use oxc_diagnostics::{Error, FailedToOpenFileError, Report};
use oxc_diagnostics::OxcDiagnostic;
use rustc_hash::FxHashSet;
use serde::Deserialize;
use crate::{rules::RuleEnum, AllowWarnDeny};
use self::errors::{
FailedToParseConfigError, FailedToParseConfigJsonError, FailedToParseConfigPropertyError,
FailedToParseJsonc,
};
pub use self::{
env::ESLintEnv, globals::ESLintGlobals, rules::ESLintRules,
settings::jsdoc::JSDocPluginSettings, settings::ESLintSettings,
@ -36,37 +31,33 @@ impl ESLintConfig {
/// # Errors
///
/// * Parse Failure
pub fn from_file(path: &Path) -> Result<Self, Report> {
pub fn from_file(path: &Path) -> Result<Self, OxcDiagnostic> {
let mut string = std::fs::read_to_string(path).map_err(|e| {
FailedToParseConfigError(vec![Error::new(FailedToOpenFileError(path.to_path_buf(), e))])
OxcDiagnostic::error(format!("Failed to parse config {path:?} with error {e:?}"))
})?;
// jsonc support
json_strip_comments::strip(&mut string)
.map_err(|_| FailedToParseJsonc(path.to_path_buf()))?;
json_strip_comments::strip(&mut string).map_err(|err| {
OxcDiagnostic::error(format!("Failed to parse jsonc file {path:?}: {err:?}"))
})?;
let json = serde_json::from_str::<serde_json::Value>(&string).map_err(|err| {
let guess = mime_guess::from_path(path);
let err = match guess.first() {
// syntax error
Some(mime) if mime.subtype() == "json" => err.to_string(),
Some(_) => "only json configuration is supported".to_string(),
Some(_) => "Only json configuration is supported".to_string(),
None => {
format!(
"{err}, if the configuration is not a json file, please use json instead."
)
}
};
FailedToParseConfigError(vec![Error::new(FailedToParseConfigJsonError(
path.to_path_buf(),
err,
))])
OxcDiagnostic::error(format!("Failed to parse eslint config {path:?}.\n{err}"))
})?;
let config = Self::deserialize(&json).map_err(|err| {
FailedToParseConfigError(vec![Error::new(FailedToParseConfigPropertyError(
err.to_string(),
))])
OxcDiagnostic::error(format!("Failed to parse config with error {err:?}"))
})?;
Ok(config)

View file

@ -1,6 +1,5 @@
use super::errors::FailedToParseRuleValueError;
use crate::AllowWarnDeny;
use oxc_diagnostics::Error;
use oxc_diagnostics::{Error, OxcDiagnostic};
use serde::de::{self, Deserializer, Visitor};
use serde::Deserialize;
use std::fmt;
@ -88,8 +87,8 @@ fn parse_rule_value(
serde_json::Value::Array(v) => {
if v.is_empty() {
return Err(FailedToParseRuleValueError(
value.to_string(),
return Err(failed_to_parse_rule_value(
&value.to_string(),
"Type should be `[SeverityConf, ...any[]`",
)
.into());
@ -108,8 +107,8 @@ fn parse_rule_value(
Ok((severity, config))
}
_ => Err(FailedToParseRuleValueError(
value.to_string(),
_ => Err(failed_to_parse_rule_value(
&value.to_string(),
"Type should be `SeverityConf | [SeverityConf, ...any[]]`",
)
.into()),
@ -124,6 +123,10 @@ impl Deref for ESLintRules {
}
}
fn failed_to_parse_rule_value(value: &str, err: &str) -> OxcDiagnostic {
OxcDiagnostic::error(format!("Failed to rule value {value:?} with error {err:?}"))
}
#[cfg(test)]
mod test {
use super::ESLintRules;

View file

@ -3,19 +3,9 @@ use std::path::PathBuf;
use rustc_hash::FxHashSet;
use serde_json::{Number, Value};
use oxc_diagnostics::Error;
use oxc_diagnostics::{Error, OxcDiagnostic};
use crate::{
config::{
errors::{
FailedToParseAllowWarnDenyFromJsonValueError,
FailedToParseAllowWarnDenyFromNumberError, FailedToParseAllowWarnDenyFromStringError,
},
ESLintConfig,
},
rules::RULES,
RuleCategory, RuleEnum,
};
use crate::{config::ESLintConfig, rules::RULES, RuleCategory, RuleEnum};
#[derive(Debug)]
pub struct LintOptions {
@ -124,39 +114,45 @@ impl AllowWarnDeny {
}
impl TryFrom<&str> for AllowWarnDeny {
type Error = Error;
type Error = OxcDiagnostic;
fn try_from(s: &str) -> Result<Self, <Self as TryFrom<&str>>::Error> {
fn try_from(s: &str) -> Result<Self, Self::Error> {
match s {
"allow" | "off" => Ok(Self::Allow),
"deny" | "error" => Ok(Self::Deny),
"warn" => Ok(Self::Warn),
_ => Err(FailedToParseAllowWarnDenyFromStringError(s.to_string()).into()),
_ => Err(OxcDiagnostic::error(format!(
r#"Failed to parse rule severity, expected one of "allow", "off", "deny", "error" or "warn", but got {s:?}"#
))),
}
}
}
impl TryFrom<&Value> for AllowWarnDeny {
type Error = Error;
type Error = OxcDiagnostic;
fn try_from(value: &Value) -> Result<Self, <Self as TryFrom<&Value>>::Error> {
fn try_from(value: &Value) -> Result<Self, OxcDiagnostic> {
match value {
Value::String(s) => Self::try_from(s.as_str()),
Value::Number(n) => Self::try_from(n),
_ => Err(FailedToParseAllowWarnDenyFromJsonValueError(value.to_string()).into()),
_ => Err(OxcDiagnostic::error(format!(
"Failed to parse rule severity, expected a string or a number, but got {value:?}"
))),
}
}
}
impl TryFrom<&Number> for AllowWarnDeny {
type Error = Error;
type Error = OxcDiagnostic;
fn try_from(value: &Number) -> Result<Self, <Self as TryFrom<&Number>>::Error> {
fn try_from(value: &Number) -> Result<Self, Self::Error> {
match value.as_i64() {
Some(0) => Ok(Self::Allow),
Some(1) => Ok(Self::Warn),
Some(2) => Ok(Self::Deny),
_ => Err(FailedToParseAllowWarnDenyFromNumberError(value.to_string()).into()),
_ => Err(OxcDiagnostic::error(format!(
r#"Failed to parse rule severity, expected one of `0`, `1` or `2`, but got {value:?}"#
))),
}
}
}