use schemars::{JsonSchema, Schema, generate::SchemaSettings, transform::RecursiveTransform};
use serde_json::Value;
use crate::{
GraphJson, HarnessReport, InitResult, LocateReport, NewResult, ValidateReport, harness,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Output {
Validate,
Graph,
Init,
Harness,
HarnessHookAnswer,
Locate,
New,
}
impl Output {
pub const ALL: [Output; 7] = [
Output::Validate,
Output::Graph,
Output::Init,
Output::Harness,
Output::HarnessHookAnswer,
Output::Locate,
Output::New,
];
pub fn file(self) -> &'static str {
match self {
Output::Validate => "validate-report.schema.json",
Output::Graph => "graph.schema.json",
Output::Init => "init-report.schema.json",
Output::Harness => "harness-report.schema.json",
Output::HarnessHookAnswer => "harness-hook-answer.schema.json",
Output::Locate => "locate-report.schema.json",
Output::New => "new-report.schema.json",
}
}
pub fn schema(self) -> Schema {
match self {
Output::Validate => schema::<ValidateReport>(),
Output::Graph => schema::<GraphJson>(),
Output::Init => schema::<InitResult>(),
Output::Harness => schema::<HarnessReport>(),
Output::HarnessHookAnswer => schema::<harness::HookAnswer>(),
Output::Locate => schema::<LocateReport>(),
Output::New => schema::<NewResult>(),
}
}
pub fn schema_text(self) -> String {
serde_json::to_string_pretty(&self.schema()).expect("a schema serialises") + "\n"
}
}
pub fn output_schemas() -> Vec<(&'static str, Schema)> {
Output::ALL.iter().map(|o| (o.file(), o.schema())).collect()
}
fn schema<T: JsonSchema>() -> Schema {
SchemaSettings::draft2020_12()
.with_transform(RecursiveTransform(unwrap_description))
.into_generator()
.into_root_schema_for::<T>()
}
fn unwrap_description(schema: &mut Schema) {
if let Some(Value::String(text)) = schema.get_mut("description") {
*text = text
.split("\n\n")
.map(|paragraph| paragraph.split('\n').collect::<Vec<_>>().join(" "))
.collect::<Vec<_>>()
.join("\n\n");
}
}