docx-templating 1.0.0

Rust library for DOCX templating with variable replacement, conditionals, and loops
Documentation
//! ZIP-backed `PackageWriter` implementation.

use std::io::{Cursor, Seek, Write};

use zip::write::SimpleFileOptions;
use zip::{ZipArchive, ZipWriter};

use crate::Result;
use crate::package::validation::validate_part_name;
use crate::package::{PackageError, PackageSource, PackageWriter};

/// A DOCX package writer backed by a ZIP archive.
///
/// Usage:
/// 1. Construct via [`new`].
/// 2. Call [`write_part`] or [`copy_part`] for each part.
/// 3. Call [`finish`] to seal the archive; or [`finish_into_inner`] to reclaim
///    the underlying writer (useful in tests).
///
/// [`new`]: ZipPackageWriter::new
/// [`write_part`]: PackageWriter::write_part
/// [`copy_part`]: PackageWriter::copy_part
/// [`finish`]: PackageWriter::finish
/// [`finish_into_inner`]: ZipPackageWriter::finish_into_inner
pub struct ZipPackageWriter<W: Write + Seek> {
    zip: ZipWriter<W>,
}

impl<W: Write + Seek + std::fmt::Debug> std::fmt::Debug for ZipPackageWriter<W> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ZipPackageWriter").finish()
    }
}

impl<W: Write + Seek> ZipPackageWriter<W> {
    /// Create a new writer around any `Write + Seek` destination.
    ///
    /// Common destinations:
    /// - `std::fs::File` for writing to disk
    /// - `std::io::Cursor<Vec<u8>>` for in-memory output (useful in tests)
    pub fn new(writer: W) -> Self {
        Self {
            zip: ZipWriter::new(writer),
        }
    }

    /// Finish the ZIP archive and return the underlying writer.
    ///
    /// Prefer [`PackageWriter::finish`] for fire-and-forget scenarios.
    /// Use this method in tests where you need to inspect the bytes.
    pub fn finish_into_inner(self) -> Result<W> {
        self.zip
            .finish()
            .map_err(|_| crate::package::PackageError::MalformedArchive.into())
    }

    /// Default file options: Deflated compression, no extra metadata.
    fn file_options() -> SimpleFileOptions {
        SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated)
    }
}

impl<W: Write + Seek> PackageWriter for ZipPackageWriter<W> {
    fn write_part(&mut self, name: &str, contents: &[u8]) -> Result<()> {
        validate_part_name(name)?;
        self.zip
            .start_file(name, Self::file_options())
            .map_err(|_| PackageError::MalformedArchive)?;
        self.zip.write_all(contents)?;
        Ok(())
    }

    fn copy_part(&mut self, source: &dyn PackageSource, name: &str) -> Result<()> {
        validate_part_name(name)?;

        // Fast path: if the source exposes its raw ZIP bytes, copy the entry
        // verbatim without decompressing and recompressing it.
        if let Some(raw) = source.raw_archive_bytes() {
            let cursor = Cursor::new(raw);
            if let Ok(mut archive) = ZipArchive::new(cursor)
                && let Ok(zip_file) = archive.by_name(name)
                && self.zip.raw_copy_file(zip_file).is_ok()
            {
                return Ok(());
            }
            // Raw copy failed — fall through to the safe path below.
        }

        // Safe fallback: decompress then recompress.
        let data = source
            .read_part(name)?
            .ok_or_else(|| PackageError::MissingRequiredPart(name.to_owned()))?;
        self.write_part(name, &data)
    }

    fn finish(self) -> Result<()> {
        self.finish_into_inner().map(|_| ())
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)]

    use super::*;
    use crate::package::memory_source::InMemoryPackageSource;

    fn in_memory_writer() -> ZipPackageWriter<std::io::Cursor<Vec<u8>>> {
        ZipPackageWriter::new(std::io::Cursor::new(Vec::new()))
    }

    #[test]
    fn write_single_part_and_read_back() {
        let mut w = in_memory_writer();
        w.write_part("word/document.xml", b"<doc/>").unwrap();
        let cursor = w.finish_into_inner().unwrap();

        let src = crate::package::ZipPackageSource::from_bytes(cursor.into_inner()).unwrap();
        let data = src.read_part("word/document.xml").unwrap().unwrap();
        assert_eq!(data, b"<doc/>");
    }

    #[test]
    fn copy_part_from_memory_source() {
        let mut mem = InMemoryPackageSource::new();
        mem.add_part("word/document.xml", b"<doc/>".to_vec());

        let mut w = in_memory_writer();
        w.copy_part(&mem, "word/document.xml").unwrap();
        let cursor = w.finish_into_inner().unwrap();

        let src = crate::package::ZipPackageSource::from_bytes(cursor.into_inner()).unwrap();
        assert_eq!(
            src.read_part("word/document.xml").unwrap().unwrap(),
            b"<doc/>"
        );
    }

    #[test]
    fn copy_part_missing_returns_error() {
        let mem = InMemoryPackageSource::new();
        let mut w = in_memory_writer();
        let err = w.copy_part(&mem, "word/document.xml").unwrap_err();
        assert!(err.to_string().contains("word/document.xml"));
    }

    #[test]
    fn write_part_rejects_traversal_name() {
        let mut w = in_memory_writer();
        let err = w.write_part("../secret.txt", b"oops").unwrap_err();
        assert!(err.to_string().contains("unsupported ZIP entry"));
    }

    #[test]
    fn finish_produces_valid_zip() {
        let mut w = in_memory_writer();
        w.write_part("[Content_Types].xml", b"<ct/>").unwrap();
        w.write_part("_rels/.rels", b"<rels/>").unwrap();
        w.write_part("word/document.xml", b"<body/>").unwrap();
        let cursor = w.finish_into_inner().unwrap();

        let src = crate::package::ZipPackageSource::from_bytes(cursor.into_inner()).unwrap();
        let names = src.part_names().unwrap();
        assert_eq!(names.len(), 3);
    }

    #[test]
    fn raw_copy_produces_identical_content() {
        // Build a source ZIP with known content.
        let mut src_writer = in_memory_writer();
        src_writer
            .write_part("[Content_Types].xml", b"<ct/>")
            .unwrap();
        src_writer.write_part("_rels/.rels", b"<rels/>").unwrap();
        src_writer
            .write_part("word/document.xml", b"<doc/>")
            .unwrap();
        let src_bytes = src_writer.finish_into_inner().unwrap().into_inner();
        let src = crate::package::ZipPackageSource::from_bytes(src_bytes).unwrap();

        // Copy all parts via copy_part (raw path for ZipPackageSource).
        let mut dst_writer = in_memory_writer();
        for name in src.part_names().unwrap() {
            dst_writer.copy_part(&src, &name).unwrap();
        }
        let dst_bytes = dst_writer.finish_into_inner().unwrap().into_inner();
        let dst = crate::package::ZipPackageSource::from_bytes(dst_bytes).unwrap();

        // Every part must round-trip bit-for-bit.
        for name in src.part_names().unwrap() {
            let original = src.read_part(&name).unwrap().unwrap();
            let copied = dst.read_part(&name).unwrap().unwrap();
            assert_eq!(
                original, copied,
                "part {name} content changed after raw copy"
            );
        }
    }
}