amdc/lib.rs
1//! Convert documents between Markdown and the Atlassian formats.
2//!
3//! Every conversion goes through one typed intermediate representation — see
4//! [`ir`] — so each format needs a reader and a writer rather than a converter
5//! per pair, and any supported format converts to any other.
6//!
7//! ```no_run
8//! use amdc::{Format, Options, convert};
9//!
10//! let out = convert("# Hello", Format::Markdown, Format::Adf, &Options::default())?;
11//! println!("{}", out.text);
12//! for warning in &out.warnings {
13//! eprintln!("{warning}");
14//! }
15//! # Ok::<(), amdc::Error>(())
16//! ```
17//!
18//! ## What a conversion promises
19//!
20//! Constructs the target format can't express are preserved as a tagged payload
21//! the reverse conversion re-inflates verbatim ([`escape`]), so round-tripping a
22//! document through a format that doesn't understand half of it still gives the
23//! document back. Anything genuinely lost is reported on
24//! [`Output::warnings`] rather than raised, because a caller converting an issue
25//! body usually wants the body, not a failure. Callers who want strictness check
26//! that the warnings are empty.
27//!
28//! An [`Error`] means the input couldn't be read at all.
29//!
30//! ## Status
31//!
32//! Every format in [`Format`] is implemented in both directions, so all 36
33//! directed pairs convert.
34
35pub mod error;
36pub mod escape;
37pub mod format;
38pub mod ir;
39pub mod parse;
40pub mod render;
41pub mod wiki;
42
43pub use error::{Error, Warning, WarningKind};
44pub use format::{Format, Options, UnknownFormat, detect};
45pub use ir::Document;
46
47/// A rendered document, plus whatever the conversion couldn't carry over.
48#[derive(Debug, Clone, PartialEq, Eq)]
49pub struct Output {
50 pub text: String,
51 pub warnings: Vec<Warning>,
52}
53
54impl Output {
55 /// A clean conversion.
56 pub fn new(text: impl Into<String>) -> Self {
57 Self {
58 text: text.into(),
59 warnings: Vec::new(),
60 }
61 }
62
63 /// Whether everything in the source survived.
64 pub fn is_lossless(&self) -> bool {
65 self.warnings.is_empty()
66 }
67}
68
69/// Read `input` as `from`.
70///
71/// See [`parse::parse`].
72pub fn parse(input: &str, from: Format) -> Result<Document, Error> {
73 parse::parse(input, from)
74}
75
76/// Write `doc` as `to`.
77///
78/// See [`render::render`].
79pub fn render(doc: &Document, to: Format, options: &Options) -> Result<Output, Error> {
80 render::render(doc, to, options)
81}
82
83/// Convert `input` from one format to another.
84pub fn convert(input: &str, from: Format, to: Format, options: &Options) -> Result<Output, Error> {
85 let document = parse(input, from)?;
86 render(&document, to, options)
87}
88
89#[cfg(test)]
90mod tests {
91 use super::*;
92
93 #[test]
94 fn output_reports_losslessness() {
95 let clean = Output::new("hi");
96 assert!(clean.is_lossless());
97
98 let lossy = Output {
99 text: "hi".into(),
100 warnings: vec![Warning::lossy("table alignment", Format::Adf)],
101 };
102 assert!(!lossy.is_lossless());
103 }
104
105 #[test]
106 fn unreadable_input_errors_rather_than_returning_an_empty_document() {
107 // The failure this guards against is a silent one: an empty `Ok` would look
108 // like a document that legitimately had no content. Only the two
109 // structured formats can fail this way — a text markup always parses.
110 let err = parse("{not json", Format::Adf).unwrap_err();
111 assert!(matches!(err, Error::Json(_)), "{err}");
112
113 let err = parse("<p>unclosed", Format::ConfluenceStorage).unwrap_err();
114 assert!(matches!(err, Error::Malformed { .. }), "{err}");
115 }
116
117 #[test]
118 fn every_declared_format_converts_in_both_directions() {
119 // `Error::UnsupportedSource` / `UnsupportedTarget` are now unreachable, and
120 // this is what says so — if a format is ever added to `Format` without a
121 // reader and a writer, this fails rather than the omission being found by a
122 // caller.
123 for format in Format::ALL {
124 let parsed = parse("", format);
125 assert!(
126 !matches!(parsed, Err(Error::UnsupportedSource(_))),
127 "no reader for {format}"
128 );
129 let rendered = render(&Document::default(), format, &Options::default());
130 assert!(
131 !matches!(rendered, Err(Error::UnsupportedTarget(_))),
132 "no writer for {format}"
133 );
134 }
135 }
136}