use std::fmt;
use std::path::{Path, PathBuf};
use serde::Serialize;
use crate::error::{SigmaParserError, SigmaParserErrorKind, SourceLocation};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum DiagnosticSeverity {
Error,
Warning,
}
impl fmt::Display for DiagnosticSeverity {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
DiagnosticSeverity::Error => "error",
DiagnosticSeverity::Warning => "warning",
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum DiagnosticKind {
YamlSyntax,
NotAMapping,
CollectionAction,
Document(SigmaParserErrorKind),
Metadata,
File(SigmaParserErrorKind),
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub struct CollectionDiagnostic {
pub kind: DiagnosticKind,
pub severity: DiagnosticSeverity,
pub message: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub document: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
pub path: Option<PathBuf>,
#[serde(skip_serializing_if = "Option::is_none")]
pub location: Option<SourceLocation>,
}
impl CollectionDiagnostic {
pub fn error(kind: DiagnosticKind, message: impl Into<String>) -> Self {
Self::new(kind, DiagnosticSeverity::Error, message.into())
}
pub fn warning(kind: DiagnosticKind, message: impl Into<String>) -> Self {
Self::new(kind, DiagnosticSeverity::Warning, message.into())
}
pub fn document(error: &SigmaParserError) -> Self {
Self::error(DiagnosticKind::Document(error.kind()), error.to_string())
.with_location(error.location())
}
pub fn file(path: &Path, error: &SigmaParserError) -> Self {
Self::error(
DiagnosticKind::File(error.kind()),
format!("{}: {error}", path.display()),
)
.with_path(path)
.with_location(error.location())
}
fn new(kind: DiagnosticKind, severity: DiagnosticSeverity, message: String) -> Self {
Self {
kind,
severity,
message,
document: None,
path: None,
location: None,
}
}
pub fn with_document(mut self, index: usize) -> Self {
self.document = Some(index);
self
}
pub fn with_path(mut self, path: impl Into<PathBuf>) -> Self {
self.path = Some(path.into());
self
}
pub fn with_location(mut self, location: Option<SourceLocation>) -> Self {
self.location = location;
self
}
pub fn is_error(&self) -> bool {
self.severity == DiagnosticSeverity::Error
}
}
impl fmt::Display for CollectionDiagnostic {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.message)
}
}