use crate::path::Path;
use crate::problems::{Kind, Problems};
pub struct Report<'a> {
path: &'a Path,
problems: &'a mut Problems,
}
impl<'a> Report<'a> {
pub fn new(path: &'a Path, problems: &'a mut Problems) -> Self {
Self { path, problems }
}
pub fn error(&mut self, field: &str, message: impl Into<String>) {
self.push(Kind::Validation, true, field, message.into());
}
pub fn warning(&mut self, field: &str, message: impl Into<String>) {
self.push(Kind::Validation, false, field, message.into());
}
fn push(&mut self, kind: Kind, failed: bool, field: &str, message: String) {
let path = if field.is_empty() {
self.path.clone()
} else {
self.path.field(&camel_case(field))
};
if failed {
self.problems
.error(kind, &crate::mark::Mark::Model, path, message);
} else {
self.problems
.warning(kind, &crate::mark::Mark::Model, path, message);
}
}
}
fn camel_case(field: &str) -> String {
let mut words = field.split('_');
let mut key = String::from(words.next().unwrap_or(""));
for word in words {
let mut letters = word.chars();
if let Some(first) = letters.next() {
key.push(first.to_ascii_uppercase());
}
key.push_str(letters.as_str());
}
key
}
#[cfg(test)]
mod tests {
use super::{Report, camel_case};
use crate::path::Path;
use crate::problems::{Kind, Problems, Severity};
#[test]
fn field_name_becomes_the_key() {
assert_eq!(camel_case("port"), "port");
assert_eq!(
camel_case("transaction_rollback_timeout"),
"transactionRollbackTimeout"
);
assert_eq!(camel_case("alreadyCamel"), "alreadyCamel");
}
#[test]
fn notes_name_the_section_and_the_field() {
let path = Path::new().field("storage");
let mut problems = Problems::new();
{
let mut report = Report::new(&path, &mut problems);
report.error("max_size", "Must be positive.");
report.warning("", "Falls back to defaults.");
}
let shown: Vec<String> = problems.iter().map(|problem| problem.to_string()).collect();
assert_eq!(
shown,
[
"storage.maxSize: Must be positive.",
"storage: Falls back to defaults."
]
);
assert!(
matches!(problems.iter().next(), Some(problem) if problem.kind == Kind::Validation)
);
assert_eq!(
problems.iter().last().map(|problem| problem.severity),
Some(Severity::Warning)
);
}
}