Skip to main content

amdc/
error.rs

1//! Failures, and the softer report of what a conversion couldn't carry over.
2//!
3//! The split is deliberate. An [`Error`] means the input could not be read at
4//! all — malformed ADF JSON, unparseable XHTML. Everything else is a
5//! [`Warning`]: the conversion produced output, and the output is imperfect in a
6//! way the caller may or may not care about. Text markup therefore never fails,
7//! because the worst reading of any string is that it's a paragraph.
8
9use crate::Format;
10
11/// A conversion could not be performed.
12#[derive(Debug, thiserror::Error)]
13pub enum Error {
14    /// ADF input wasn't valid JSON.
15    #[error("invalid ADF JSON: {0}")]
16    Json(#[from] serde_json::Error),
17
18    /// ADF input was valid JSON but not an ADF document.
19    #[error("expected an ADF node of type \"doc\", found {found:?}")]
20    NotAdfDoc { found: String },
21
22    /// Structured input was readable but malformed in a way that can't be
23    /// papered over.
24    #[error("malformed {format} input: {detail}")]
25    Malformed { format: Format, detail: String },
26
27    /// This crate can't parse that format yet. v0.1 ships Markdown, GFM, ADF
28    /// and Jira wiki markup; the Confluence dialects land in v0.2.
29    #[error("parsing {0} is not implemented yet")]
30    UnsupportedSource(Format),
31
32    /// This crate can't render that format yet.
33    #[error("rendering {0} is not implemented yet")]
34    UnsupportedTarget(Format),
35}
36
37/// How badly a construct fared.
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39pub enum WarningKind {
40    /// Rendered as the closest thing the target format has. Readable, not
41    /// faithful — GFM column alignment on the way into ADF, say.
42    Lossy,
43    /// Not representable at all, and not preserved. Only happens with
44    /// [`Options::escape_hatch`](crate::Options::escape_hatch) off.
45    Dropped,
46    /// Preserved verbatim as a tagged payload rather than as native syntax, so
47    /// the reverse conversion can restore it. Lossless, but the output has a
48    /// blob in it where a human would want prose.
49    Escaped,
50}
51
52impl std::fmt::Display for WarningKind {
53    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
54        f.write_str(match self {
55            WarningKind::Lossy => "lossy",
56            WarningKind::Dropped => "dropped",
57            WarningKind::Escaped => "escaped",
58        })
59    }
60}
61
62/// Something a conversion couldn't carry over cleanly.
63///
64/// Collected on [`Output::warnings`](crate::Output::warnings) rather than
65/// raised, so that a caller who wants strictness can check
66/// `warnings.is_empty()` and one who doesn't is not forced to.
67#[derive(Debug, Clone, PartialEq, Eq)]
68pub struct Warning {
69    pub kind: WarningKind,
70    /// What couldn't be carried, named the way the source names it: `"table
71    /// alignment"`, `"adf:panel"`, `"{color}"`.
72    pub construct: String,
73    /// The format being rendered to.
74    pub format: Format,
75    /// Anything else worth saying.
76    pub detail: Option<String>,
77}
78
79impl Warning {
80    pub fn lossy(construct: impl Into<String>, format: Format) -> Self {
81        Self::new(WarningKind::Lossy, construct, format)
82    }
83
84    pub fn dropped(construct: impl Into<String>, format: Format) -> Self {
85        Self::new(WarningKind::Dropped, construct, format)
86    }
87
88    pub fn escaped(construct: impl Into<String>, format: Format) -> Self {
89        Self::new(WarningKind::Escaped, construct, format)
90    }
91
92    fn new(kind: WarningKind, construct: impl Into<String>, format: Format) -> Self {
93        Self {
94            kind,
95            construct: construct.into(),
96            format,
97            detail: None,
98        }
99    }
100
101    /// Attach an explanation.
102    pub fn with_detail(mut self, detail: impl Into<String>) -> Self {
103        self.detail = Some(detail.into());
104        self
105    }
106}
107
108impl std::fmt::Display for Warning {
109    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
110        write!(f, "{}: {} in {}", self.kind, self.construct, self.format)?;
111        if let Some(detail) = &self.detail {
112            write!(f, " ({detail})")?;
113        }
114        Ok(())
115    }
116}
117
118#[cfg(test)]
119mod tests {
120    use super::*;
121
122    #[test]
123    fn warnings_describe_themselves() {
124        let warning = Warning::lossy("table alignment", Format::Adf)
125            .with_detail("ADF has no per-column alignment");
126        assert_eq!(
127            warning.to_string(),
128            "lossy: table alignment in ADF (ADF has no per-column alignment)"
129        );
130    }
131
132    #[test]
133    fn detail_is_optional() {
134        let warning = Warning::escaped("adf:panel", Format::JiraWiki);
135        assert_eq!(
136            warning.to_string(),
137            "escaped: adf:panel in Jira wiki markup"
138        );
139    }
140}