use crate::Result;
use crate::adapters::docx::{parse_part, serialize};
use crate::context::IntoContext;
use crate::diagnostic::{Diagnostic, View};
use crate::docx::parts::{
DOCUMENT, is_endnotes, is_footer, is_footnotes, is_header, is_main_document,
};
use crate::domain::binding::{BoundTemplate, bind, text_view};
use crate::domain::document::Document;
use crate::domain::engine::{RenderError, evaluate};
use crate::domain::plan::apply;
use crate::error::Error;
use crate::options::TemplateOptions;
use crate::package::{PackageSource, PackageWriter, ZipPackageSource, ZipPackageWriter};
use crate::rendered::RenderedDocument;
use std::io::Read;
use std::path::Path;
pub struct Template<S: PackageSource = ZipPackageSource> {
source: S,
options: TemplateOptions,
document: Document,
bound: BoundTemplate,
secondary: Vec<SecondaryPart>,
}
struct SecondaryPart {
name: String,
bytes: Vec<u8>,
}
impl SecondaryPart {
fn load(&self) -> Result<(Document, BoundTemplate)> {
let document = parse_part(&self.bytes, &self.name).map_err(crate::error::XmlError::from)?;
let bound = bind(&document, &self.name)?;
Ok((document, bound))
}
}
impl<S: PackageSource + std::fmt::Debug> std::fmt::Debug for Template<S> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut names: Vec<&str> = vec![DOCUMENT];
names.extend(self.secondary.iter().map(|part| part.name.as_str()));
f.debug_struct("Template")
.field("source", &self.source)
.field("options", &self.options)
.field("parts", &names)
.field("paragraphs", &self.bound.paragraphs().len())
.field("blocks", &self.bound.blocks().len())
.finish()
}
}
impl Template<ZipPackageSource> {
pub fn from_path(path: impl AsRef<Path>) -> Result<Self> {
let source = ZipPackageSource::from_path(path)?;
Self::from_source(source)
}
pub fn from_reader(reader: impl Read) -> Result<Self> {
let source = ZipPackageSource::from_reader(reader)?;
Self::from_source(source)
}
pub fn from_bytes(bytes: impl Into<Vec<u8>>) -> Result<Self> {
let source = ZipPackageSource::from_bytes(bytes.into())?;
Self::from_source(source)
}
}
impl<S: PackageSource> Template<S> {
pub fn from_source(source: S) -> Result<Self> {
let part_names = source.part_names()?;
crate::docx::validate_package(&part_names)?;
let doc_xml = source.read_part(DOCUMENT)?.ok_or_else(|| {
crate::package::PackageError::MissingRequiredPart(DOCUMENT.to_owned())
})?;
let document = parse_part(&doc_xml, DOCUMENT).map_err(crate::error::XmlError::from)?;
let bound = bind(&document, DOCUMENT)?;
let mut secondary = Vec::new();
for name in part_names.iter().filter(|name| is_secondary_part(name)) {
let bytes = source
.read_part(name)?
.ok_or_else(|| crate::package::PackageError::MissingRequiredPart(name.clone()))?;
secondary.push(SecondaryPart {
name: name.clone(),
bytes,
});
}
Ok(Self {
source,
options: TemplateOptions::default(),
document,
bound,
secondary,
})
}
#[must_use]
pub fn with_options(mut self, options: TemplateOptions) -> Self {
self.options = options;
self
}
#[must_use]
pub fn diagnostic(&self, error: &Error) -> Diagnostic {
let primary = Diagnostic::with_view(error, &self.primary_view());
if primary.line().is_some() {
return primary;
}
for part in &self.secondary {
let Ok(document) = parse_part(&part.bytes, &part.name) else {
continue;
};
let (text, paragraphs) = text_view(&document, &part.name);
let view = View::new(&part.name, &text, ¶graphs);
let diagnostic = Diagnostic::with_view(error, &view);
if diagnostic.line().is_some() {
return diagnostic;
}
}
primary
}
fn primary_view(&self) -> View {
let paragraphs: Vec<_> = self
.bound
.paragraphs()
.iter()
.map(|paragraph| paragraph.text_start..paragraph.text_end)
.collect();
View::new(self.bound.part(), self.bound.text(), ¶graphs)
}
pub fn render(&self, context: impl IntoContext) -> Result<RenderedDocument> {
let mut output = Vec::new();
self.render_to_writer(context, std::io::Cursor::new(&mut output))?;
Ok(RenderedDocument::new(output))
}
pub fn render_to_writer(
&self,
context: impl IntoContext,
writer: impl std::io::Write + std::io::Seek,
) -> Result<()> {
let context = context.into_context()?;
let mut package = ZipPackageWriter::new(writer);
let mut written: Vec<&str> = Vec::with_capacity(1 + self.secondary.len());
let plan = evaluate(&self.document, &self.bound, &context, &self.options)?;
let root = apply(self.document.root(), &plan, self.document.word_prefix())
.map_err(RenderError::from)?;
let rendered_document = Document::new(
self.document.prolog().to_vec(),
root,
self.document.epilogue().to_vec(),
self.document.word_prefix().to_owned(),
);
package.write_part(DOCUMENT, &serialize(&rendered_document))?;
written.push(DOCUMENT);
for part in &self.secondary {
if !self.renders(&part.name) {
continue;
}
let (document, bound) = part.load()?;
let plan = evaluate(&document, &bound, &context, &self.options)?;
let root =
apply(document.root(), &plan, document.word_prefix()).map_err(RenderError::from)?;
let rendered_document = Document::new(
document.prolog().to_vec(),
root,
document.epilogue().to_vec(),
document.word_prefix().to_owned(),
);
package.write_part(&part.name, &serialize(&rendered_document))?;
written.push(&part.name);
}
for name in self.source.part_names()? {
if !written.contains(&name.as_str()) {
package.copy_part(&self.source, &name)?;
}
}
package.finish()?;
Ok(())
}
fn renders(&self, name: &str) -> bool {
if is_main_document(name) {
return true;
}
if is_header(name) || is_footer(name) {
return self.options.headers_and_footers;
}
if is_footnotes(name) || is_endnotes(name) {
return self.options.footnotes;
}
false
}
}
fn is_secondary_part(name: &str) -> bool {
is_header(name) || is_footer(name) || is_footnotes(name) || is_endnotes(name)
}
pub fn render(path: impl AsRef<Path>, context: impl IntoContext) -> Result<RenderedDocument> {
Template::from_path(path)?.render(context)
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)]
use super::*;
use crate::package::InMemoryPackageSource;
use serde_json::json;
fn make_test_template(logical_text: &str) -> Template<InMemoryPackageSource> {
let mut source = InMemoryPackageSource::new();
source.add_part(
"[Content_Types].xml",
br#"<?xml version="1.0"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"></Types>"#.to_vec(),
);
source.add_part(
"_rels/.rels",
br#"<?xml version="1.0"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"></Relationships>"#.to_vec(),
);
let doc_xml = format!(
r#"<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body><w:p><w:r><w:t>{}</w:t></w:r></w:p></w:body></w:document>"#,
logical_text
);
source.add_part("word/document.xml", doc_xml.into_bytes());
Template::from_source(source).unwrap()
}
fn document_xml(rendered: &RenderedDocument) -> String {
use std::io::Cursor;
use zip::ZipArchive;
let cursor = Cursor::new(rendered.as_bytes());
let mut archive = ZipArchive::new(cursor).unwrap();
let mut doc_file = archive.by_name("word/document.xml").unwrap();
let mut doc_xml = String::new();
std::io::Read::read_to_string(&mut doc_file, &mut doc_xml).unwrap();
doc_xml
}
#[test]
fn from_source_validates_package() {
let source = InMemoryPackageSource::new();
let result = Template::from_source(source);
assert!(result.is_err());
}
#[test]
fn from_source_parses_ast() {
let template = make_test_template("Hello {{name}}!");
let inline = template.bound.inline();
assert_eq!(inline.len(), 1);
assert_eq!(inline[0].nodes.len(), 3); }
#[test]
fn with_options_sets_config() {
let template = make_test_template("{{name}}").with_options(
TemplateOptions::default()
.missing_value_policy(crate::options::MissingValuePolicy::Empty),
);
assert_eq!(
template.options.missing_value_policy,
crate::options::MissingValuePolicy::Empty
);
}
#[test]
fn render_replaces_variable() {
let template = make_test_template("Hello {{name}}!");
let rendered = template.render(json!({"name": "Ada"})).unwrap();
assert!(document_xml(&rendered).contains("Hello Ada!"));
}
#[test]
fn render_accepts_a_borrowed_struct() {
#[derive(serde::Serialize)]
struct Data {
name: &'static str,
}
let template = make_test_template("Hello {{name}}!");
let rendered = template.render(&Data { name: "Ada" }).unwrap();
assert!(document_xml(&rendered).contains("Hello Ada!"));
}
#[test]
fn render_handles_missing_with_error_policy() {
let template = make_test_template("Hello {{missing}}!");
let result = template.render(json!({}));
assert!(result.is_err());
}
#[test]
fn render_handles_missing_with_empty_policy() {
let template = make_test_template("Hello {{missing}}!").with_options(
TemplateOptions::default()
.missing_value_policy(crate::options::MissingValuePolicy::Empty),
);
let rendered = template.render(json!({})).unwrap();
assert!(document_xml(&rendered).contains("Hello !"));
}
}