use crate::xml::functions::Element;
use std::collections::{BTreeMap, BTreeSet};
const PRESERVED_WORKBOOK_CHILDREN: [&str; 11] = [
"fileVersion",
"functionGroups",
"externalReferences",
"oleSize",
"customWorkbookViews",
"pivotCaches",
"smartTagPr",
"smartTagTypes",
"webPublishing",
"fileRecoveryPr",
"extLst",
];
const CANDIDATE_WORKSHEET_CHILDREN: [&str; 23] = [
"pivotTableParts",
"extLst",
"legacyDrawing",
"legacyDrawingHF",
"drawingHF",
"picture",
"oleObjects",
"controls",
"webPublishItems",
"customSheetViews",
"sheetProtection",
"phoneticPr",
"smartTags",
"protectedRanges",
"scenarios",
"cellWatches",
"dataConsolidate",
"drawing",
"tableParts",
"ignoredErrors",
"customProperties",
"oleSize",
"sheetCalcPr",
];
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PreservedRelationship {
pub id: String,
pub relationship_type: String,
pub target: String,
pub target_mode: Option<String>,
}
impl PreservedRelationship {
pub fn internal(
id: impl Into<String>,
relationship_type: impl Into<String>,
target: impl Into<String>,
) -> Self {
PreservedRelationship {
id: id.into(),
relationship_type: relationship_type.into(),
target: target.into(),
target_mode: None,
}
}
pub fn external(
id: impl Into<String>,
relationship_type: impl Into<String>,
target: impl Into<String>,
) -> Self {
PreservedRelationship {
id: id.into(),
relationship_type: relationship_type.into(),
target: target.into(),
target_mode: Some("External".to_string()),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GeneratedRelationship {
pub id: String,
pub relationship_type: String,
pub target: String,
pub target_mode: Option<String>,
}
impl GeneratedRelationship {
pub fn internal(
id: impl Into<String>,
relationship_type: impl Into<String>,
target: impl Into<String>,
) -> Self {
GeneratedRelationship {
id: id.into(),
relationship_type: relationship_type.into(),
target: target.into(),
target_mode: None,
}
}
pub fn to_attributes(&self) -> Vec<(&'static str, String)> {
let mut attributes = vec![
("Id", self.id.clone()),
("Type", self.relationship_type.clone()),
("Target", self.target.clone()),
];
if let Some(mode) = &self.target_mode {
attributes.push(("TargetMode", mode.clone()));
}
attributes
}
}
#[derive(Debug, Default)]
pub struct MergedRelationships {
pub relationships: Vec<GeneratedRelationship>,
pub id_map: BTreeMap<String, String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PreservedContentType {
pub kind: String,
pub name: String,
pub content_type: String,
}
impl PreservedContentType {
pub fn key_attribute(&self) -> &'static str {
if self.kind == "Default" {
"Extension"
} else {
"PartName"
}
}
pub fn covers_part(&self, path: &str) -> bool {
self.kind != "Default" && self.name.trim_start_matches('/') == path
}
pub fn covers_extension(&self, extension: &str) -> bool {
self.kind == "Default" && self.name.eq_ignore_ascii_case(extension)
}
}
#[derive(Debug, Clone, Default)]
pub struct PreservedParts {
parts: BTreeMap<String, Vec<u8>>,
content_types: Vec<PreservedContentType>,
relationships: BTreeMap<String, Vec<PreservedRelationship>>,
workbook_children: Vec<Element>,
worksheet_children: BTreeMap<usize, Vec<Element>>,
macro_extension: Option<String>,
macro_enabled: bool,
}
impl PreservedParts {
pub fn is_empty(&self) -> bool {
self.parts.is_empty()
&& self.relationships.is_empty()
&& self.workbook_children.is_empty()
&& self.worksheet_children.is_empty()
}
pub fn add_part(&mut self, path: impl Into<String>, data: Vec<u8>) {
self.parts.insert(path.into(), data);
}
pub fn add_content_type(&mut self, entry: PreservedContentType) {
self.content_types.push(entry);
}
pub fn add_relationships(
&mut self,
rels_path: impl Into<String>,
relationships: Vec<PreservedRelationship>,
) {
if !relationships.is_empty() {
self.relationships.insert(rels_path.into(), relationships);
}
}
pub fn add_workbook_child(&mut self, child: Element) {
self.workbook_children.push(child);
}
pub fn capture_workbook_children(&mut self, root: &Element) {
self.workbook_children = root
.children()
.into_iter()
.filter(|child| {
local_name(&child.tag)
.is_some_and(|name| PRESERVED_WORKBOOK_CHILDREN.contains(&name))
})
.cloned()
.collect();
}
pub fn capture_worksheet_children(&mut self, sheet: usize, root: &Element) {
let children: Vec<Element> = root
.children()
.into_iter()
.filter(|child| {
local_name(&child.tag)
.is_some_and(|name| CANDIDATE_WORKSHEET_CHILDREN.contains(&name))
})
.cloned()
.collect();
if !children.is_empty() {
self.worksheet_children.insert(sheet, children);
}
}
pub fn set_macro_enabled(&mut self, extension: Option<String>) {
self.macro_enabled = true;
self.macro_extension = extension;
}
pub fn is_macro_enabled(&self) -> bool {
self.macro_enabled
}
pub fn macro_extension(&self) -> Option<&str> {
self.macro_extension.as_deref()
}
pub fn parts(&self) -> &BTreeMap<String, Vec<u8>> {
&self.parts
}
pub fn part(&self, path: &str) -> Option<&[u8]> {
self.parts.get(path).map(|data| data.as_slice())
}
pub fn content_types(&self) -> &[PreservedContentType] {
&self.content_types
}
pub fn relationships(&self, rels_path: &str) -> Option<&[PreservedRelationship]> {
self.relationships
.get(rels_path)
.map(|list| list.as_slice())
}
pub fn all_relationships(&self) -> &BTreeMap<String, Vec<PreservedRelationship>> {
&self.relationships
}
pub fn workbook_children(&self) -> &[Element] {
&self.workbook_children
}
pub fn worksheet_children(&self, sheet: usize) -> &[Element] {
self.worksheet_children
.get(&sheet)
.map(|list| list.as_slice())
.unwrap_or_default()
}
pub fn worksheet_children_excluding(&self, sheet: usize, produced: &[&str]) -> Vec<&Element> {
self.worksheet_children(sheet)
.iter()
.filter(|child| local_name(&child.tag).is_none_or(|name| !produced.contains(&name)))
.collect()
}
pub fn has_worksheet_children(&self, sheet: usize) -> bool {
self.worksheet_children
.get(&sheet)
.is_some_and(|list| !list.is_empty())
}
pub fn untyped_part_paths(&self) -> Vec<&str> {
self.parts
.keys()
.filter(|path| {
let extension = path.rsplit('.').next().unwrap_or_default();
!self
.content_types
.iter()
.any(|entry| entry.covers_part(path) || entry.covers_extension(extension))
})
.map(|path| path.as_str())
.collect()
}
}
fn local_name(tag: &str) -> Option<&str> {
tag.rsplit_once('}').map(|(_, local)| local)
}
#[derive(Debug, Default)]
pub struct IdAllocator {
used: BTreeSet<String>,
}
impl IdAllocator {
pub fn reserve(&mut self, ids: impl IntoIterator<Item = String>) {
self.used.extend(ids);
}
pub fn allocate(&mut self, wanted: &str) -> String {
if !self.used.contains(wanted) {
self.used.insert(wanted.to_string());
return wanted.to_string();
}
let prefix = match wanted.strip_prefix("rId") {
Some(rest) if !rest.is_empty() && rest.chars().all(|c| c.is_ascii_digit()) => {
"rId".to_string()
}
_ => format!("{wanted}_"),
};
let mut counter = 1usize;
loop {
let candidate = format!("{prefix}{counter}");
if !self.used.contains(&candidate) {
self.used.insert(candidate.clone());
return candidate;
}
counter += 1;
}
}
pub fn is_used(&self, id: &str) -> bool {
self.used.contains(id)
}
}
pub fn resolve_target(base_directory: &str, target: &str) -> String {
let absolute = target.starts_with('/');
let trimmed = target.trim_start_matches('/');
let mut segments: Vec<&str> = if absolute || base_directory.is_empty() {
Vec::new()
} else {
base_directory
.split('/')
.filter(|s| !s.is_empty())
.collect()
};
for piece in trimmed.split('/') {
match piece {
"" | "." => {}
".." => {
segments.pop();
}
piece => segments.push(piece.split(['?', '#']).next().unwrap_or(piece)),
}
}
segments.join("/")
}
pub fn rels_base_directory(rels_path: &str) -> String {
if rels_path == "_rels/.rels" || rels_path == ".rels" {
return String::new();
}
let owner = crate::reader::preserved::part_for_rels(rels_path);
match owner.rsplit_once('/') {
Some((directory, _)) => directory.to_string(),
None => String::new(),
}
}
pub fn merge_relationships(
generated: &[GeneratedRelationship],
preserved: &[PreservedRelationship],
rels_path: &str,
) -> MergedRelationships {
let base = rels_base_directory(rels_path);
let mut allocator = IdAllocator::default();
allocator.reserve(generated.iter().map(|entry| entry.id.clone()));
let generated_targets: BTreeSet<String> = generated
.iter()
.map(|entry| resolve_target(&base, &entry.target))
.collect();
let mut merged = MergedRelationships {
relationships: generated.to_vec(),
id_map: BTreeMap::new(),
};
for entry in preserved {
if entry.target_mode.is_none() {
let resolved = resolve_target(&base, &entry.target);
if generated_targets.contains(&resolved)
|| crate::reader::preserved::is_writer_owned(&resolved)
{
continue;
}
}
let id = allocator.allocate(&entry.id);
if id != entry.id {
merged.id_map.insert(entry.id.clone(), id.clone());
}
merged.relationships.push(GeneratedRelationship {
id,
relationship_type: entry.relationship_type.clone(),
target: entry.target.clone(),
target_mode: entry.target_mode.clone(),
});
}
merged
}
pub fn rewrite_relationship_ids(element: &mut Element, id_map: &BTreeMap<String, String>) {
if id_map.is_empty() {
return;
}
for (key, value) in element.attributes.iter_mut() {
let is_relationship_id = key == "r:id" || (key.starts_with('{') && key.ends_with("}id"));
if is_relationship_id {
if let Some(moved) = id_map.get(value.as_str()) {
*value = moved.clone();
}
}
}
for child in element.children.iter_mut() {
rewrite_relationship_ids(child, id_map);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::xml::functions::fromstring;
#[test]
fn an_id_that_is_free_is_kept_so_references_stay_valid() {
let mut allocator = IdAllocator::default();
allocator.reserve(["rId1".to_string(), "rId2".to_string()]);
assert_eq!(allocator.allocate("rId7"), "rId7");
}
#[test]
fn a_colliding_id_is_moved_rather_than_duplicated() {
let mut allocator = IdAllocator::default();
allocator.reserve(["rId1".to_string(), "rId2".to_string()]);
assert_eq!(allocator.allocate("rId2"), "rId3");
assert_eq!(allocator.allocate("rId3"), "rId4");
}
#[test]
fn a_non_numeric_id_gets_a_suffixed_replacement() {
let mut allocator = IdAllocator::default();
allocator.reserve(["pkg1".to_string()]);
assert_eq!(allocator.allocate("pkg1"), "pkg1_1");
}
#[test]
fn nothing_is_reported_preserved_for_an_empty_value() {
assert!(PreservedParts::default().is_empty());
}
#[test]
fn a_part_without_a_content_type_is_reported() {
let mut parts = PreservedParts::default();
parts.add_part("xl/pivotTables/pivotTable1.xml", vec![1]);
parts.add_part("xl/media/image9.png", vec![2]);
parts.add_content_type(PreservedContentType {
kind: "Default".to_string(),
name: "png".to_string(),
content_type: "image/png".to_string(),
});
assert_eq!(
parts.untyped_part_paths(),
vec!["xl/pivotTables/pivotTable1.xml"]
);
}
#[test]
fn an_override_satisfies_a_part_that_its_extension_would_not() {
let mut parts = PreservedParts::default();
parts.add_part("customXml/item1.xml", vec![1]);
parts.add_content_type(PreservedContentType {
kind: "Override".to_string(),
name: "/customXml/item1.xml".to_string(),
content_type: "application/xml".to_string(),
});
assert!(parts.untyped_part_paths().is_empty());
}
#[test]
fn a_relationship_renders_the_two_attribute_spellings_correctly() {
let embedded = GeneratedRelationship::internal("rId1", "type/a", "pivot1.xml");
let attributes: BTreeMap<&str, String> = embedded.to_attributes().into_iter().collect();
assert_eq!(
attributes.get("Target").map(String::as_str),
Some("pivot1.xml")
);
assert!(!attributes.contains_key("TargetMode"));
let linked = GeneratedRelationship {
target_mode: Some("External".to_string()),
..GeneratedRelationship::internal("rId2", "type/b", "https://example.com")
};
let attributes: BTreeMap<&str, String> = linked.to_attributes().into_iter().collect();
assert_eq!(
attributes.get("TargetMode").map(String::as_str),
Some("External")
);
}
#[test]
fn a_content_type_reports_which_attribute_keys_it() {
let by_extension = PreservedContentType {
kind: "Default".to_string(),
name: "bin".to_string(),
content_type: "application/vnd.ms-office.vbaProject".to_string(),
};
let by_part = PreservedContentType {
kind: "Override".to_string(),
name: "/xl/workbook.xml".to_string(),
content_type: "application/xml".to_string(),
};
assert_eq!(by_extension.key_attribute(), "Extension");
assert_eq!(by_part.key_attribute(), "PartName");
}
#[test]
fn a_colliding_preserved_id_is_remapped_and_the_reference_follows_it() {
let generated = vec![
GeneratedRelationship::internal("rId1", "t/sheet", "worksheets/sheet1.xml"),
GeneratedRelationship::internal("rId2", "t/styles", "styles.xml"),
];
let preserved = vec![PreservedRelationship::internal(
"rId2",
"t/pivotCacheDefinition",
"pivotCache/pivotCacheDefinition1.xml",
)];
let merged = merge_relationships(&generated, &preserved, "xl/_rels/workbook.xml.rels");
assert_eq!(merged.relationships.len(), 3);
let moved = merged
.relationships
.last()
.expect("the preserved one is last");
assert_eq!(moved.id, "rId3", "it had to move: rId2 was taken");
assert_eq!(
merged.id_map.get("rId2").map(String::as_str),
Some("rId3"),
"and the reference has to be told where it went"
);
const REL_ID: &str =
"{http://schemas.openxmlformats.org/officeDocument/2006/relationships}id";
let mut element = Element::with_attributes("pivotCache", [(REL_ID, "rId2".to_string())]);
rewrite_relationship_ids(&mut element, &merged.id_map);
assert_eq!(element.get(REL_ID), Some("rId3"));
}
#[test]
fn a_preserved_relationship_the_writer_also_produces_is_dropped() {
let generated = vec![GeneratedRelationship::internal(
"rId1",
"t/theme",
"theme/theme1.xml",
)];
let preserved = vec![PreservedRelationship::internal(
"rId9",
"t/theme",
"theme/theme1.xml",
)];
let merged = merge_relationships(&generated, &preserved, "xl/_rels/workbook.xml.rels");
assert_eq!(merged.relationships.len(), 1);
assert!(
merged.id_map.is_empty(),
"nothing moved, so nothing needs rewriting"
);
}
#[test]
fn a_target_spelled_absolutely_is_recognised_as_the_same_part() {
let generated = vec![GeneratedRelationship::internal(
"rId1",
"t/sheet",
"worksheets/sheet1.xml",
)];
let preserved = vec![PreservedRelationship::internal(
"rId5",
"t/sheet",
"/xl/worksheets/sheet1.xml",
)];
let merged = merge_relationships(&generated, &preserved, "xl/_rels/workbook.xml.rels");
assert_eq!(
merged.relationships.len(),
1,
"one part, one relationship: {:?}",
merged.relationships
);
}
#[test]
fn a_preserved_relationship_to_a_removed_part_is_dropped() {
let generated = vec![
GeneratedRelationship::internal("rId1", "t/sheet", "worksheets/sheet1.xml"),
GeneratedRelationship::internal("rId2", "t/sheet", "worksheets/sheet2.xml"),
];
let preserved = vec![
PreservedRelationship::internal("rId1", "t/sheet", "/xl/worksheets/sheet1.xml"),
PreservedRelationship::internal("rId2", "t/sheet", "/xl/worksheets/sheet2.xml"),
PreservedRelationship::internal("rId3", "t/sheet", "/xl/worksheets/sheet3.xml"),
];
let merged = merge_relationships(&generated, &preserved, "xl/_rels/workbook.xml.rels");
assert_eq!(
merged.relationships.len(),
2,
"the writer said which sheets exist; sheet3.xml is not one of them: {:?}",
merged.relationships
);
}
#[test]
fn a_relationship_to_a_preserved_part_survives() {
let generated = vec![GeneratedRelationship::internal(
"rId1",
"t/sheet",
"worksheets/sheet1.xml",
)];
let preserved = vec![
PreservedRelationship::internal(
"rId2",
"t/pivotCacheDefinition",
"pivotCache/pivotCacheDefinition1.xml",
),
PreservedRelationship::internal("rId3", "t/vbaProject", "vbaProject.bin"),
];
let merged = merge_relationships(
&generated,
&preserved,
"xl/worksheets/_rels/sheet1.xml.rels",
);
assert_eq!(merged.relationships.len(), 3, "{:?}", merged.relationships);
let drawing = [PreservedRelationship::internal(
"rId4",
"t/drawing",
"../drawings/drawing1.xml",
)];
let merged =
merge_relationships(&generated, &drawing, "xl/worksheets/_rels/sheet1.xml.rels");
assert_eq!(
merged.relationships.len(),
2,
"the relationship to the drawing the writer cannot reproduce: {:?}",
merged.relationships
);
}
#[test]
fn a_target_resolves_through_a_step_up_and_to_the_package_root() {
assert_eq!(
resolve_target("xl/worksheets", "../drawings/drawing1.xml"),
"xl/drawings/drawing1.xml"
);
assert_eq!(resolve_target("xl", "/xl/styles.xml"), "xl/styles.xml");
assert_eq!(
resolve_target("xl/worksheets", "../../docProps/app.xml"),
"docProps/app.xml"
);
assert_eq!(rels_base_directory("_rels/.rels"), "");
assert_eq!(rels_base_directory("xl/_rels/workbook.xml.rels"), "xl");
assert_eq!(
rels_base_directory("xl/worksheets/_rels/sheet1.xml.rels"),
"xl/worksheets"
);
}
#[test]
fn an_external_relationship_is_kept_even_when_the_target_looks_internal() {
let generated = vec![GeneratedRelationship::internal(
"rId1",
"t/hyperlink",
"https://example.com",
)];
let preserved = vec![PreservedRelationship::external(
"rId5",
"t/hyperlink",
"https://example.com",
)];
let merged = merge_relationships(&generated, &preserved, "xl/_rels/workbook.xml.rels");
assert_eq!(
merged.relationships.len(),
2,
"a link is not the same as an embedded part"
);
}
#[test]
fn the_writer_produced_children_are_excluded_from_the_preserved_set() {
let root = fromstring(
br#"<worksheet xmlns="x">
<drawing r:id="rId1"/>
<pivotTableParts count="1"><pivotTablePart r:id="rId2"/></pivotTableParts>
</worksheet>"#,
)
.expect("parses");
let mut parts = PreservedParts::default();
parts.capture_worksheet_children(0, &root);
assert_eq!(parts.worksheet_children(0).len(), 2);
assert_eq!(parts.worksheet_children_excluding(0, &["drawing"]).len(), 1);
}
#[test]
fn a_workbook_child_the_writer_will_emit_is_not_preserved() {
let root = fromstring(
br#"<workbook xmlns="x"><sheets><sheet name="a"/></sheets><pivotCaches/></workbook>"#,
)
.expect("parses");
let mut parts = PreservedParts::default();
parts.capture_workbook_children(&root);
assert_eq!(parts.workbook_children().len(), 1);
assert!(
parts.workbook_children()[0].tag.ends_with("pivotCaches"),
"got {:?}",
parts.workbook_children()[0].tag
);
}
}