Skip to main content

standout_dispatch/
diagnostic.rs

1//! The diagnostic document: the one shape a failure takes on stdout under a
2//! structured output mode.
3//!
4//! A handler returns a [`Diagnostic`] as its error when it has a `detail` or a
5//! source `range` to report; any other error type reaches the document with
6//! its `Display` text as `summary` and an empty `detail`. `kind` is the
7//! [`DiagnosticKind`] projected from the [`RunErrorKind`] the framework
8//! assigned when the error crossed the dispatch boundary, so a value a handler
9//! constructs carries a placeholder that the framework overwrites. The wire
10//! vocabulary is fixed: every `FinalWrite` payload is the one `final-write`,
11//! while hook phases stay distinct. `framework` is the one kind outside that
12//! projection: a `severity: warning` entry the framework raises on its own
13//! account under `ndjson`, which no run failure classifies.
14
15use serde::{Deserialize, Serialize};
16use std::fmt;
17
18use crate::contract::ContractSurface;
19use crate::handler::RunErrorKind;
20use crate::hooks::HookPhase;
21
22#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
23pub struct Diagnostic {
24    #[serde(rename = "type", with = "document_type")]
25    document_type: (),
26    schema_version: u32,
27    pub severity: Severity,
28    pub kind: DiagnosticKind,
29    pub summary: String,
30    pub detail: String,
31    #[serde(default, skip_serializing_if = "Option::is_none")]
32    pub range: Option<DiagnosticRange>,
33}
34
35impl ContractSurface for Diagnostic {
36    const SCHEMA_VERSION: u32 = 1;
37}
38
39impl Diagnostic {
40    pub fn error(summary: impl Into<String>) -> Self {
41        Self::new(Severity::Error, summary)
42    }
43
44    pub fn warning(summary: impl Into<String>) -> Self {
45        Self::new(Severity::Warning, summary)
46    }
47
48    fn new(severity: Severity, summary: impl Into<String>) -> Self {
49        Self {
50            document_type: (),
51            schema_version: Self::SCHEMA_VERSION,
52            severity,
53            kind: DiagnosticKind::Handler,
54            summary: summary.into(),
55            detail: String::new(),
56            range: None,
57        }
58    }
59
60    pub fn detail(mut self, detail: impl Into<String>) -> Self {
61        self.detail = detail.into();
62        self
63    }
64
65    pub fn range(mut self, filename: impl Into<String>, line: u64, column: u64) -> Self {
66        self.range = Some(DiagnosticRange {
67            filename: filename.into(),
68            start: DiagnosticPosition { line, column },
69        });
70        self
71    }
72
73    pub const fn schema_version(&self) -> u32 {
74        self.schema_version
75    }
76}
77
78impl fmt::Display for Diagnostic {
79    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
80        if let Some(range) = &self.range {
81            write!(
82                f,
83                "{}:{}:{}: ",
84                range.filename, range.start.line, range.start.column
85            )?;
86        }
87        f.write_str(&self.summary)?;
88        if !self.detail.is_empty() {
89            write!(f, "\n{}", self.detail)?;
90        }
91        Ok(())
92    }
93}
94
95impl std::error::Error for Diagnostic {}
96
97#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
98#[serde(rename_all = "lowercase")]
99pub enum Severity {
100    Error,
101    Warning,
102}
103
104#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
105#[serde(rename_all = "kebab-case")]
106pub enum DiagnosticKind {
107    ClapUsage,
108    DefaultCommand,
109    Handler,
110    HookPreDispatch,
111    HookPostDispatch,
112    HookPostOutput,
113    Render,
114    FinalWrite,
115    External,
116    App,
117    Framework,
118}
119
120impl From<RunErrorKind> for DiagnosticKind {
121    fn from(kind: RunErrorKind) -> Self {
122        match kind {
123            RunErrorKind::ClapUsage => Self::ClapUsage,
124            RunErrorKind::DefaultCommand => Self::DefaultCommand,
125            RunErrorKind::Handler => Self::Handler,
126            RunErrorKind::Hook(HookPhase::PreDispatch) => Self::HookPreDispatch,
127            RunErrorKind::Hook(HookPhase::PostDispatch) => Self::HookPostDispatch,
128            RunErrorKind::Hook(HookPhase::PostOutput) => Self::HookPostOutput,
129            RunErrorKind::Render => Self::Render,
130            RunErrorKind::FinalWrite(_) => Self::FinalWrite,
131            RunErrorKind::External => Self::External,
132            RunErrorKind::App => Self::App,
133        }
134    }
135}
136
137#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
138pub struct DiagnosticRange {
139    pub filename: String,
140    pub start: DiagnosticPosition,
141}
142
143#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
144pub struct DiagnosticPosition {
145    pub line: u64,
146    pub column: u64,
147}
148
149mod document_type {
150    use serde::de::Error;
151    use serde::{Deserialize, Deserializer, Serializer};
152
153    const TAG: &str = "diagnostic";
154
155    pub fn serialize<S: Serializer>(_: &(), serializer: S) -> Result<S::Ok, S::Error> {
156        serializer.serialize_str(TAG)
157    }
158
159    pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<(), D::Error> {
160        let tag = String::deserialize(deserializer)?;
161        if tag == TAG {
162            Ok(())
163        } else {
164            Err(D::Error::custom(format!(
165                "expected a \"{TAG}\" document, found type {tag:?}"
166            )))
167        }
168    }
169}
170
171#[cfg(test)]
172mod tests {
173    use super::*;
174    use crate::handler::OutputKind;
175
176    #[test]
177    fn a_ranged_diagnostic_serializes_flat_with_the_fixed_type_tag() {
178        let diagnostic = Diagnostic::error("config line 2 does not parse")
179            .detail("expected `resource <name> <state>`")
180            .range("main.tfl", 2, 1);
181        let json = serde_json::to_value(&diagnostic).unwrap();
182        assert_eq!(
183            json,
184            serde_json::json!({
185                "type": "diagnostic",
186                "schema_version": 1,
187                "severity": "error",
188                "kind": "handler",
189                "summary": "config line 2 does not parse",
190                "detail": "expected `resource <name> <state>`",
191                "range": { "filename": "main.tfl", "start": { "line": 2, "column": 1 } },
192            })
193        );
194        let back: Diagnostic = serde_json::from_value(json).unwrap();
195        assert_eq!(back, diagnostic);
196    }
197
198    #[test]
199    fn an_unranged_diagnostic_omits_the_range_key() {
200        let mut diagnostic = Diagnostic::warning("soft");
201        diagnostic.kind = DiagnosticKind::HookPostOutput;
202        let json = serde_json::to_string(&diagnostic).unwrap();
203        assert_eq!(
204            json,
205            r#"{"type":"diagnostic","schema_version":1,"severity":"warning","kind":"hook-post-output","summary":"soft","detail":""}"#
206        );
207        assert_eq!(
208            serde_json::from_str::<Diagnostic>(&json).unwrap(),
209            diagnostic
210        );
211    }
212
213    #[test]
214    fn every_run_error_kind_projects_onto_the_fixed_wire_vocabulary() {
215        let expected = [
216            (RunErrorKind::ClapUsage, "clap-usage"),
217            (RunErrorKind::DefaultCommand, "default-command"),
218            (RunErrorKind::Handler, "handler"),
219            (
220                RunErrorKind::Hook(HookPhase::PreDispatch),
221                "hook-pre-dispatch",
222            ),
223            (
224                RunErrorKind::Hook(HookPhase::PostDispatch),
225                "hook-post-dispatch",
226            ),
227            (
228                RunErrorKind::Hook(HookPhase::PostOutput),
229                "hook-post-output",
230            ),
231            (RunErrorKind::Render, "render"),
232            (RunErrorKind::FinalWrite(OutputKind::Text), "final-write"),
233            (RunErrorKind::FinalWrite(OutputKind::Binary), "final-write"),
234            (
235                RunErrorKind::FinalWrite(OutputKind::Artifact),
236                "final-write",
237            ),
238            (RunErrorKind::External, "external"),
239            (RunErrorKind::App, "app"),
240        ];
241        for (kind, name) in expected {
242            let wire = DiagnosticKind::from(kind);
243            assert_eq!(serde_json::to_value(wire).unwrap(), name, "{kind:?}");
244            assert_eq!(
245                serde_json::from_value::<DiagnosticKind>(name.into()).unwrap(),
246                wire
247            );
248        }
249        assert!(serde_json::from_value::<DiagnosticKind>("final-write-text".into()).is_err());
250    }
251
252    #[test]
253    fn a_document_of_another_type_is_refused() {
254        let error = serde_json::from_str::<Diagnostic>(
255            r#"{"type":"result","schema_version":1,"severity":"error","kind":"handler","summary":"","detail":""}"#,
256        )
257        .unwrap_err();
258        assert!(error.to_string().contains("\"diagnostic\""), "{error}");
259    }
260
261    #[test]
262    fn display_is_the_human_prose_form() {
263        assert_eq!(Diagnostic::error("boom").to_string(), "boom");
264        assert_eq!(
265            Diagnostic::error("boom")
266                .detail("why")
267                .range("a.cfg", 3, 7)
268                .to_string(),
269            "a.cfg:3:7: boom\nwhy"
270        );
271    }
272}