use std::io::{Cursor, Write as _};
use ::zip::ZipWriter;
use ::zip::result::ZipResult;
use ::zip::write::SimpleFileOptions;
pub const RELATIONSHIPS: &str =
"http://schemas.openxmlformats.org/officeDocument/2006/relationships";
pub const PACKAGE_RELATIONSHIPS: &str = crate::RELATIONSHIPS_NS;
#[derive(Debug, Default)]
pub struct Builder {
parts: Vec<(String, Vec<u8>)>,
relationships: Vec<(String, String)>,
}
impl Builder {
#[must_use]
pub fn part(mut self, name: &str, content: impl Into<Vec<u8>>) -> Self {
self.parts.push((name.to_owned(), content.into()));
self
}
#[must_use]
pub fn relationship(mut self, source: &str, id: &str, kind: &str, target: &str) -> Self {
let element =
format!(r#"<Relationship Id="{id}" Type="{RELATIONSHIPS}/{kind}" Target="{target}"/>"#);
self.relationships.push((source.to_owned(), element));
self
}
#[must_use]
pub fn external_relationship(
mut self,
source: &str,
id: &str,
kind: &str,
target: &str,
) -> Self {
let element = format!(
r#"<Relationship Id="{id}" Type="{RELATIONSHIPS}/{kind}" Target="{target}" TargetMode="External"/>"#
);
self.relationships.push((source.to_owned(), element));
self
}
#[must_use]
pub fn entries(self) -> Vec<(String, Vec<u8>)> {
let mut sources: Vec<(String, String)> = Vec::new();
for (source, element) in self.relationships {
match sources.iter_mut().find(|(name, _)| *name == source) {
Some((_, elements)) => elements.push_str(&element),
None => sources.push((source, element)),
}
}
let mut entries = self.parts;
entries.extend(sources.into_iter().map(|(source, elements)| {
let xml = format!(
r#"<Relationships xmlns="{PACKAGE_RELATIONSHIPS}">{elements}</Relationships>"#
);
(crate::relationships_part(&source), xml.into_bytes())
}));
entries
}
pub fn zip(self) -> ZipResult<Vec<u8>> {
zip(self.entries())
}
}
pub fn zip(entries: impl IntoIterator<Item = (String, Vec<u8>)>) -> ZipResult<Vec<u8>> {
let mut out = ZipWriter::new(Cursor::new(Vec::new()));
for (name, bytes) in entries {
out.start_file(name, SimpleFileOptions::default())?;
out.write_all(&bytes)?;
}
Ok(out.finish()?.into_inner())
}
#[cfg(test)]
mod tests {
use super::Builder;
use crate::{Limits, Package, relationships_part};
#[test]
fn names_the_relationships_part_of_a_part_and_of_the_package() {
assert_eq!(relationships_part(""), "_rels/.rels");
assert_eq!(
relationships_part("word/document.xml"),
"word/_rels/document.xml.rels"
);
assert_eq!(relationships_part("a.xml"), "_rels/a.xml.rels");
}
#[test]
fn zips_a_package_that_the_reader_opens_with_its_relationships() {
let bytes = Builder::default()
.relationship("", "main", "officeDocument", "word/document.xml")
.part("word/document.xml", "<w/>")
.relationship("word/document.xml", "s", "styles", "styles.xml")
.part("word/styles.xml", "<s/>")
.relationship("word/document.xml", "h", "header", "h.xml")
.zip()
.unwrap();
let package = Package::open(&bytes, &Limits::default()).unwrap();
assert_eq!(package.main_document().unwrap(), "word/document.xml");
let targets: Vec<_> = package
.relationships("word/document.xml")
.unwrap()
.relationships
.iter()
.map(|rel| (rel.id.as_str(), rel.target.as_str()))
.collect();
assert_eq!(targets, [("s", "word/styles.xml"), ("h", "word/h.xml")]);
}
}