use std::fmt;
use serde::ser::{Serialize, SerializeSeq, Serializer};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ValidationErrorKind {
Syntax,
TooLarge,
MissingSchemaVersion,
UnsupportedSchemaVersion,
UnknownKey,
WrongType,
OutOfRange,
InvalidValue,
Conflict,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize)]
#[non_exhaustive]
pub struct ValidationError {
kind: ValidationErrorKind,
path: Option<String>,
message: String,
}
impl ValidationError {
pub(crate) fn new(
kind: ValidationErrorKind,
path: Option<&str>,
message: impl Into<String>,
) -> Self {
Self {
kind,
path: path.map(str::to_owned),
message: message.into(),
}
}
pub(crate) fn at(kind: ValidationErrorKind, path: &str, message: impl Into<String>) -> Self {
Self::new(kind, Some(path), message)
}
pub fn kind(&self) -> ValidationErrorKind {
self.kind
}
pub fn path(&self) -> Option<&str> {
self.path.as_deref()
}
pub fn message(&self) -> &str {
&self.message
}
}
impl fmt::Display for ValidationError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.path {
Some(path) => write!(f, "{path}: {}", self.message),
None => f.write_str(&self.message),
}
}
}
impl std::error::Error for ValidationError {}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct ValidationErrors {
errors: Vec<ValidationError>,
}
impl ValidationErrors {
pub(crate) fn one(error: ValidationError) -> Self {
Self {
errors: vec![error],
}
}
pub(crate) fn from_vec(errors: Vec<ValidationError>) -> Option<Self> {
(!errors.is_empty()).then_some(Self { errors })
}
pub fn as_slice(&self) -> &[ValidationError] {
&self.errors
}
pub fn iter(&self) -> std::slice::Iter<'_, ValidationError> {
self.errors.iter()
}
pub fn len(&self) -> usize {
self.errors.len()
}
pub fn is_empty(&self) -> bool {
self.errors.is_empty()
}
pub fn into_vec(self) -> Vec<ValidationError> {
self.errors
}
}
impl fmt::Display for ValidationErrors {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let n = self.errors.len();
let noun = if n == 1 { "error" } else { "errors" };
write!(f, "invalid configuration ({n} {noun})")?;
for e in &self.errors {
write!(f, "; {e}")?;
}
Ok(())
}
}
impl std::error::Error for ValidationErrors {}
impl Serialize for ValidationErrors {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let mut seq = serializer.serialize_seq(Some(self.errors.len()))?;
for e in &self.errors {
seq.serialize_element(e)?;
}
seq.end()
}
}
impl<'a> IntoIterator for &'a ValidationErrors {
type Item = &'a ValidationError;
type IntoIter = std::slice::Iter<'a, ValidationError>;
fn into_iter(self) -> Self::IntoIter {
self.errors.iter()
}
}
impl IntoIterator for ValidationErrors {
type Item = ValidationError;
type IntoIter = std::vec::IntoIter<ValidationError>;
fn into_iter(self) -> Self::IntoIter {
self.errors.into_iter()
}
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum PreviewError {
#[error("base document is not valid toml: {0}")]
Syntax(ValidationError),
#[error("document is larger than the {limit}-byte limit")]
TooLarge {
limit: usize,
},
#[error("unknown configuration path {path:?}")]
UnknownPath {
path: String,
},
#[error("more than one change for {path}")]
DuplicatePath {
path: String,
},
#[error("cannot edit {path}: the base document does not hold a table or value there")]
NotEditable {
path: String,
},
}