Skip to main content

sokf_core/
output_schema.rs

1//! This module generates the JSON Schema of each JSON output that the tool prints or writes.
2//! It builds each schema from the type that the tool serialises, so a schema cannot differ
3//! from the output. A test checks that the files in `/knowledge/json/` match the schemas that
4//! `output_schemas` returns.
5
6use schemars::{JsonSchema, Schema, generate::SchemaSettings, transform::RecursiveTransform};
7use serde_json::Value;
8
9use crate::{
10    FormatsJson, GraphJson, GuideReport, HarnessReport, InitResult, LocateReport, NewResult,
11    ValidateReport, harness,
12};
13
14/// `Output` names each JSON output that the tool prints or writes.
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub enum Output {
17    /// The report of `validate --json`.
18    Validate,
19    /// The graph of `graph --json`.
20    Graph,
21    /// The report of `init --json`.
22    Init,
23    /// The report of `harness install --json` and `harness status --json`.
24    Harness,
25    /// The answer that `harness hook` writes for the harness.
26    HarnessHookAnswer,
27    /// The report of `locate --json`.
28    Locate,
29    /// The report of `new --json`.
30    New,
31    /// The registry of `info formats --json`.
32    InfoFormats,
33    /// The report of `guide --json`.
34    Guide,
35}
36
37impl Output {
38    /// `ALL` lists every output, in the order of `output_schemas`.
39    pub const ALL: [Output; 9] = [
40        Output::Validate,
41        Output::Graph,
42        Output::Init,
43        Output::Harness,
44        Output::HarnessHookAnswer,
45        Output::Locate,
46        Output::New,
47        Output::InfoFormats,
48        Output::Guide,
49    ];
50
51    /// `file` returns the name of the output's schema file in `/knowledge/json/`.
52    pub fn file(self) -> &'static str {
53        match self {
54            Output::Validate => "validate-report.schema.json",
55            Output::Graph => "graph.schema.json",
56            Output::Init => "init-report.schema.json",
57            Output::Harness => "harness-report.schema.json",
58            Output::HarnessHookAnswer => "harness-hook-answer.schema.json",
59            Output::Locate => "locate-report.schema.json",
60            Output::New => "new-report.schema.json",
61            Output::InfoFormats => "info-formats-registry.schema.json",
62            Output::Guide => "guide-report.schema.json",
63        }
64    }
65
66    /// `schema` returns the JSON Schema of the output.
67    pub fn schema(self) -> Schema {
68        match self {
69            Output::Validate => schema::<ValidateReport>(),
70            Output::Graph => schema::<GraphJson>(),
71            Output::Init => schema::<InitResult>(),
72            Output::Harness => schema::<HarnessReport>(),
73            Output::HarnessHookAnswer => schema::<harness::HookAnswer>(),
74            Output::Locate => schema::<LocateReport>(),
75            Output::New => schema::<NewResult>(),
76            Output::InfoFormats => schema::<FormatsJson>(),
77            Output::Guide => schema::<GuideReport>(),
78        }
79    }
80
81    /// `schema_text` returns the schema as the file in `/knowledge/json/` holds it: pretty
82    /// JSON with a final newline.
83    pub fn schema_text(self) -> String {
84        serde_json::to_string_pretty(&self.schema()).expect("a schema serialises") + "\n"
85    }
86}
87
88/// `output_schemas` returns the schema of each output, paired with the name of its file in
89/// `/knowledge/json/`.
90pub fn output_schemas() -> Vec<(&'static str, Schema)> {
91    Output::ALL.iter().map(|o| (o.file(), o.schema())).collect()
92}
93
94// `schema` generates a Draft 2020-12 schema. It joins the lines of each paragraph of a
95// description into one line, because a doc comment wraps its lines for the source, not for
96// the reader of the schema.
97fn schema<T: JsonSchema>() -> Schema {
98    SchemaSettings::draft2020_12()
99        .with_transform(RecursiveTransform(unwrap_description))
100        .into_generator()
101        .into_root_schema_for::<T>()
102}
103
104fn unwrap_description(schema: &mut Schema) {
105    if let Some(Value::String(text)) = schema.get_mut("description") {
106        *text = text
107            .split("\n\n")
108            .map(|paragraph| paragraph.split('\n').collect::<Vec<_>>().join(" "))
109            .collect::<Vec<_>>()
110            .join("\n\n");
111    }
112}