fix(epub): normalize text nodes in EPUB metadata content.opf (#2222)

Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>
This commit is contained in:
Balázs Szücs
2026-01-10 10:02:06 -07:00
committed by GitHub
parent c184e32a67
commit 24fabc97de
2 changed files with 66 additions and 0 deletions
@@ -142,6 +142,53 @@ class EpubMetadataWriterTest {
}
}
@Nested
@DisplayName("Whitespace Tests")
class WhitespaceTests {
@Test
@DisplayName("Should not add extra whitespace lines on repeated saves")
void saveMetadataToFile_repeatedSaves_shouldNotInflateWhitespace() throws IOException {
String initialOpfContent = """
<?xml version="1.0" encoding="UTF-8"?>
<package xmlns="http://www.idpf.org/2007/opf" version="3.0">
<metadata xmlns:dc="http://purl.org/dc/elements/1.1/">
<dc:title>Original Title</dc:title>
<dc:creator>Original Author</dc:creator>
</metadata>
</package>""";
File epubFile = createEpubWithOpf(initialOpfContent, "test-whitespace-" + System.nanoTime() + ".epub");
BookMetadataEntity newMeta = new BookMetadataEntity();
newMeta.setTitle("Updated Title");
AuthorEntity author = new AuthorEntity();
author.setName("Updated Author");
newMeta.setAuthors(Collections.singleton(author));
writer.saveMetadataToFile(epubFile, newMeta, null, new MetadataClearFlags());
String contentAfterFirstSave = readOpfContent(epubFile);
newMeta.setTitle("Updated Title 2"); // Change title to force write
writer.saveMetadataToFile(epubFile, newMeta, null, new MetadataClearFlags());
String contentAfterSecondSave = readOpfContent(epubFile);
long lines1 = contentAfterFirstSave.lines().count();
long lines2 = contentAfterSecondSave.lines().count();
assertTrue(Math.abs(lines2 - lines1) <= 2, "Line count should be stable");
assertTrue(!contentAfterSecondSave.contains("\n\n"), "Should not contain double newlines");
}
}
private String readOpfContent(File epubFile) throws IOException {
try (ZipFile zf = new ZipFile(epubFile)) {
ZipEntry ze = zf.getEntry("OEBPS/content.opf");
try (InputStream is = zf.getInputStream(ze)) {
return new String(is.readAllBytes(), StandardCharsets.UTF_8);
}
}
}
private File createEpubWithOpf(String opfContent, String filename) throws IOException {
File epubFile = tempDir.resolve(filename).toFile();