docx-templating 1.0.0

Rust library for DOCX templating with variable replacement, conditionals, and loops
Documentation
//! Diagnostics: the compiler style error display.

use docx_templating::package::{PackageWriter, ZipPackageWriter};
use docx_templating::{Diagnostic, Template, diagnose};
use serde_json::json;
use std::io::Cursor;

/// Write a minimal DOCX package around one `word/document.xml`.
fn package(document_xml: &str) -> Vec<u8> {
    let content_types = br#"<?xml version="1.0"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"></Types>"#;
    let rels = br#"<?xml version="1.0"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"></Relationships>"#;

    let mut writer = ZipPackageWriter::new(Cursor::new(Vec::new()));
    writer
        .write_part("[Content_Types].xml", content_types)
        .expect("content types must be written");
    writer
        .write_part("_rels/.rels", rels)
        .expect("relationships must be written");
    writer
        .write_part("word/document.xml", document_xml.as_bytes())
        .expect("document part must be written");
    writer
        .finish_into_inner()
        .expect("package must finish")
        .into_inner()
}

fn document(body: &str) -> String {
    format!(
        r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>{body}</w:body></w:document>"#
    )
}

fn paragraph(text: &str) -> String {
    format!(r#"<w:p><w:r><w:t xml:space="preserve">{text}</w:t></w:r></w:p>"#)
}

#[test]
fn a_load_error_points_at_the_paragraph_that_caused_it() {
    let xml = document(&paragraph("{% for item in items %}"));
    let bytes = package(&xml);

    let error = Template::from_bytes(bytes.clone()).expect_err("the loop is never closed");
    let diagnostic = diagnose(&bytes, &error);
    let rendered = diagnostic.to_string();

    assert_eq!(diagnostic.part(), Some("word/document.xml"));
    assert_eq!(diagnostic.line(), Some(1));
    assert_eq!(diagnostic.column(), Some(1));
    assert!(
        rendered.contains("--> word/document.xml:1:1"),
        "missing location line:\n{rendered}"
    );
    assert!(
        rendered.contains("1 | {% for item in items %}"),
        "missing snippet:\n{rendered}"
    );
    assert!(
        rendered.contains("^^^^^^^^^^^^^^^^^^^^^^^ this block is never closed"),
        "missing caret:\n{rendered}"
    );
    assert!(
        rendered.contains("= help: add the matching closing tag"),
        "missing help:\n{rendered}"
    );
}

#[test]
fn a_caret_lands_under_the_tag_in_a_later_paragraph() {
    let xml = document(&format!(
        "{}{}{}",
        paragraph("Report title"),
        paragraph("Body text"),
        paragraph("{% endif %}")
    ));
    let bytes = package(&xml);

    let error = Template::from_bytes(bytes.clone()).expect_err("the tag has no opening block");
    let diagnostic = diagnose(&bytes, &error);

    assert_eq!(diagnostic.line(), Some(3));
    assert_eq!(diagnostic.column(), Some(1));

    let rendered = diagnostic.to_string();
    assert!(rendered.contains("3 | {% endif %}"), "{rendered}");
    assert!(rendered.contains("no block is open here"), "{rendered}");
}

#[test]
fn a_render_error_carries_help_without_a_snippet() {
    let bytes = std::fs::read("tests/fixtures/inline/missing-value.docx")
        .expect("missing-value fixture must exist");
    let template = Template::from_bytes(bytes).expect("fixture must load");

    let error = template
        .render(json!({}))
        .expect_err("the context has no value");
    let diagnostic = template.diagnostic(&error);
    let rendered = diagnostic.to_string();

    assert_eq!(diagnostic.part(), Some("word/document.xml"));
    assert_eq!(diagnostic.line(), None);
    assert!(diagnostic.help().is_some());
    assert!(rendered.starts_with("error: missing value"), "{rendered}");
    assert!(rendered.contains("= help:"), "{rendered}");
    assert!(!rendered.contains("-->"), "{rendered}");
}

#[test]
fn a_missing_value_diagnostic_names_the_path() {
    let bytes = std::fs::read("tests/fixtures/inline/missing-value.docx")
        .expect("missing-value fixture must exist");
    let template = Template::from_bytes(bytes).expect("fixture must load");

    let error = template
        .render(json!({}))
        .expect_err("the context has no value");

    assert!(error.is_missing_value());
    assert!(
        template
            .diagnostic(&error)
            .message()
            .contains("missing value"),
        "{}",
        template.diagnostic(&error)
    );
}

#[test]
fn an_unreadable_package_falls_back_to_the_message() {
    let error = Template::from_bytes(b"not a zip".to_vec()).expect_err("bytes are not a ZIP");
    let diagnostic = diagnose(b"not a zip", &error);

    assert_eq!(diagnostic.line(), None);
    assert_eq!(diagnostic.message(), error.to_string());
    assert_eq!(diagnostic.to_string(), format!("error: {error}"));
}

#[test]
fn a_package_error_is_displayed_without_a_location() {
    let diagnostic: Diagnostic = diagnose(
        [],
        &docx_templating::Error::Io(std::io::Error::new(std::io::ErrorKind::NotFound, "missing")),
    );

    assert_eq!(diagnostic.part(), None);
    assert_eq!(diagnostic.line(), None);
    assert_eq!(diagnostic.help(), None);
    assert_eq!(diagnostic.to_string(), "error: I/O error");
}