use schemars::JsonSchema;
use serde::Serialize;
use super::size::SizeEstimate;
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum Severity {
Warning,
Error,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
#[non_exhaustive]
pub enum Rule {
RequestShape,
UnknownField,
StateMissing,
StateType,
ModelMissing,
ModelType,
QuestionsMissing,
QuestionsType,
QuestionsEmpty,
QuestionIdEmpty,
DuplicateQuestionId,
QuestionShape,
TypeMissing,
TypeUnknown,
InstructionsMissing,
InstructionsType,
CriteriaMissing,
CriteriaType,
CriteriaValueType,
NoulCriteriaKey,
ChoiceNoOptions,
ChoiceTooManyOptions,
ChoiceOptionEmpty,
DuplicateOption,
ScoreTooFewLevels,
ScoreTooManyLevels,
SizeTotal,
SizeQuestion,
ChoiceNoEscapeOption,
ChoiceYesNo,
PathIndexLongArray,
DuplicateDescription,
DuplicateKey,
}
impl Rule {
pub const ALL: [Self; 33] = [
Self::RequestShape,
Self::UnknownField,
Self::StateMissing,
Self::StateType,
Self::ModelMissing,
Self::ModelType,
Self::QuestionsMissing,
Self::QuestionsType,
Self::QuestionsEmpty,
Self::QuestionIdEmpty,
Self::DuplicateQuestionId,
Self::QuestionShape,
Self::TypeMissing,
Self::TypeUnknown,
Self::InstructionsMissing,
Self::InstructionsType,
Self::CriteriaMissing,
Self::CriteriaType,
Self::CriteriaValueType,
Self::NoulCriteriaKey,
Self::ChoiceNoOptions,
Self::ChoiceTooManyOptions,
Self::ChoiceOptionEmpty,
Self::DuplicateOption,
Self::ScoreTooFewLevels,
Self::ScoreTooManyLevels,
Self::SizeTotal,
Self::SizeQuestion,
Self::ChoiceNoEscapeOption,
Self::ChoiceYesNo,
Self::PathIndexLongArray,
Self::DuplicateDescription,
Self::DuplicateKey,
];
#[must_use]
pub const fn id(self) -> &'static str {
match self {
Self::RequestShape => "request-shape",
Self::UnknownField => "unknown-field",
Self::StateMissing => "state-missing",
Self::StateType => "state-type",
Self::ModelMissing => "model-missing",
Self::ModelType => "model-type",
Self::QuestionsMissing => "questions-missing",
Self::QuestionsType => "questions-type",
Self::QuestionsEmpty => "questions-empty",
Self::QuestionIdEmpty => "question-id-empty",
Self::DuplicateQuestionId => "duplicate-question-id",
Self::QuestionShape => "question-shape",
Self::TypeMissing => "type-missing",
Self::TypeUnknown => "type-unknown",
Self::InstructionsMissing => "instructions-missing",
Self::InstructionsType => "instructions-type",
Self::CriteriaMissing => "criteria-missing",
Self::CriteriaType => "criteria-type",
Self::CriteriaValueType => "criteria-value-type",
Self::NoulCriteriaKey => "noul-criteria-key",
Self::ChoiceNoOptions => "choice-no-options",
Self::ChoiceTooManyOptions => "choice-too-many-options",
Self::ChoiceOptionEmpty => "choice-option-empty",
Self::DuplicateOption => "duplicate-option",
Self::ScoreTooFewLevels => "score-too-few-levels",
Self::ScoreTooManyLevels => "score-too-many-levels",
Self::SizeTotal => "size-total",
Self::SizeQuestion => "size-question",
Self::ChoiceNoEscapeOption => "choice-no-escape-option",
Self::ChoiceYesNo => "choice-yes-no",
Self::PathIndexLongArray => "path-index-long-array",
Self::DuplicateDescription => "duplicate-description",
Self::DuplicateKey => "duplicate-key",
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, JsonSchema)]
#[non_exhaustive]
pub struct Finding {
pub severity: Severity,
pub rule: Rule,
#[serde(skip_serializing_if = "Option::is_none")]
pub question: Option<String>,
pub path: String,
pub message: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub suggestion: Option<String>,
}
impl Finding {
pub(crate) fn error(rule: Rule, path: impl Into<String>, message: impl Into<String>) -> Self {
Self::new(Severity::Error, rule, path, message)
}
pub(crate) fn warning(rule: Rule, path: impl Into<String>, message: impl Into<String>) -> Self {
Self::new(Severity::Warning, rule, path, message)
}
fn new(
severity: Severity,
rule: Rule,
path: impl Into<String>,
message: impl Into<String>,
) -> Self {
Self {
severity,
rule,
question: None,
path: path.into(),
message: message.into(),
suggestion: None,
}
}
pub(crate) fn in_question(mut self, id: &str) -> Self {
self.question = Some(id.to_owned());
self
}
pub(crate) fn suggest(mut self, suggestion: impl Into<String>) -> Self {
self.suggestion = Some(suggestion.into());
self
}
}
#[derive(Clone, Debug, PartialEq, Serialize, JsonSchema)]
#[non_exhaustive]
pub struct Report {
pub findings: Vec<Finding>,
#[serde(skip_serializing_if = "Option::is_none")]
pub size: Option<SizeEstimate>,
}
impl Report {
#[must_use]
pub fn is_valid(&self) -> bool {
self.errors().next().is_none()
}
pub fn errors(&self) -> impl Iterator<Item = &Finding> {
self.findings
.iter()
.filter(|finding| finding.severity == Severity::Error)
}
pub fn warnings(&self) -> impl Iterator<Item = &Finding> {
self.findings
.iter()
.filter(|finding| finding.severity == Severity::Warning)
}
}
#[cfg(test)]
mod tests {
use std::collections::HashSet;
use serde_json::json;
use super::{Finding, Rule, Severity};
#[test]
fn every_rule_is_listed_once_and_serialises_to_its_id() {
let ids: HashSet<&str> = Rule::ALL.iter().map(|rule| rule.id()).collect();
assert_eq!(
ids.len(),
Rule::ALL.len(),
"rule ids are unique and ALL has no repeats"
);
for rule in Rule::ALL {
assert_eq!(
serde_json::to_value(rule).unwrap(),
json!(rule.id()),
"{rule:?}"
);
assert!(
rule.id()
.chars()
.all(|c| c.is_ascii_lowercase() || c == '-'),
"{}",
rule.id()
);
}
}
#[test]
fn a_finding_serialises_without_its_empty_fields() {
let bare = Finding::error(Rule::StateMissing, "", "`state` is missing");
let full = Finding::warning(Rule::ChoiceYesNo, "/questions/q/criteria", "yes/no choice")
.in_question("q")
.suggest("use a noul");
assert_eq!(
serde_json::to_value(&bare).unwrap(),
json!({ "severity": "error", "rule": "state-missing", "path": "", "message": "`state` is missing" })
);
assert_eq!(
serde_json::to_value(&full).unwrap(),
json!({
"severity": "warning",
"rule": "choice-yes-no",
"question": "q",
"path": "/questions/q/criteria",
"message": "yes/no choice",
"suggestion": "use a noul"
})
);
assert!(Severity::Error > Severity::Warning);
}
}