use std::fmt;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Error {
Missing {
name: String,
},
Invalid {
name: String,
expected: String,
got: String,
},
Conflict {
message: String,
},
}
impl Error {
#[must_use]
pub fn missing(name: impl Into<String>) -> Self {
Self::Missing { name: name.into() }
}
#[must_use]
pub fn invalid(
name: impl Into<String>,
expected: impl Into<String>,
got: impl Into<String>,
) -> Self {
Self::Invalid {
name: name.into(),
expected: expected.into(),
got: got.into(),
}
}
#[must_use]
pub fn conflict(message: impl Into<String>) -> Self {
Self::Conflict {
message: message.into(),
}
}
#[must_use]
pub fn name(&self) -> Option<&str> {
match self {
Self::Missing { name } | Self::Invalid { name, .. } => Some(name),
Self::Conflict { .. } => None,
}
}
}
impl fmt::Display for Error {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Missing { name } => {
write!(formatter, "missing required configuration: {name}")
}
Self::Invalid {
name,
expected,
got,
} => write!(
formatter,
"invalid configuration: {name} must be {expected}, got {got:?}"
),
Self::Conflict { message } => formatter.write_str(message),
}
}
}
impl std::error::Error for Error {}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Errors(Vec<Error>);
impl Errors {
#[must_use]
pub fn new(errors: Vec<Error>) -> Self {
assert!(!errors.is_empty(), "Errors must hold at least one problem");
Self(errors)
}
#[must_use]
pub fn len(&self) -> usize {
self.0.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
pub fn iter(&self) -> std::slice::Iter<'_, Error> {
self.0.iter()
}
#[must_use]
pub fn into_inner(self) -> Vec<Error> {
self.0
}
}
impl fmt::Display for Errors {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut first = true;
for error in &self.0 {
if !first {
writeln!(formatter)?;
}
write!(formatter, "{error}")?;
first = false;
}
Ok(())
}
}
impl std::error::Error for Errors {}
impl<'a> IntoIterator for &'a Errors {
type Item = &'a Error;
type IntoIter = std::slice::Iter<'a, Error>;
fn into_iter(self) -> Self::IntoIter {
self.0.iter()
}
}
impl IntoIterator for Errors {
type Item = Error;
type IntoIter = std::vec::IntoIter<Error>;
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_missing_variable_names_itself() {
assert_eq!(
Error::missing("DATABASE_URL").to_string(),
"missing required configuration: DATABASE_URL"
);
}
#[test]
fn an_invalid_value_is_quoted_so_whitespace_is_visible() {
assert_eq!(
Error::invalid("PORT", "a whole number", "2576 ").to_string(),
r#"invalid configuration: PORT must be a whole number, got "2576 ""#
);
}
#[test]
fn problems_render_one_per_line() {
let errors = Errors::new(vec![
Error::missing("A"),
Error::invalid("B", "a whole number", "x"),
]);
let text = errors.to_string();
assert_eq!(text.lines().count(), 2);
assert!(text.starts_with("missing required configuration: A\n"));
}
#[test]
fn a_conflict_names_no_single_variable() {
assert_eq!(Error::conflict("either, not both").name(), None);
assert_eq!(Error::missing("A").name(), Some("A"));
assert_eq!(Error::invalid("B", "x", "y").name(), Some("B"));
}
#[test]
#[should_panic(expected = "at least one problem")]
fn an_empty_error_list_is_not_representable() {
let _ = Errors::new(Vec::new());
}
}