From 6b620519425e1a9a4e3acd750a1b7d8380f07198 Mon Sep 17 00:00:00 2001 From: Kenneth Gitere Date: Sat, 6 Feb 2021 13:53:04 +0300 Subject: [PATCH] Add `replace_metadata_value` function --- src/epub.rs | 38 +++++++++++++++++++++++++++++++++++--- 1 file changed, 35 insertions(+), 3 deletions(-) diff --git a/src/epub.rs b/src/epub.rs index 7ffcc9c..714bd73 100644 --- a/src/epub.rs +++ b/src/epub.rs @@ -20,11 +20,14 @@ pub fn generate_epub(extractor: Extractor) { let html_buf = std::str::from_utf8(&html_buf).unwrap(); let mut epub = EpubBuilder::new(ZipLibrary::new().unwrap()).unwrap(); if let Some(author) = extractor.metadata().byline() { - epub.metadata("author", author.replace("&", "&")) + epub.metadata("author", replace_metadata_value(author)) .unwrap(); } - epub.metadata("title", extractor.metadata().title().replace("&", "&")) - .unwrap(); + epub.metadata( + "title", + replace_metadata_value(extractor.metadata().title()), + ) + .unwrap(); epub.add_content(EpubContent::new("index.xhtml", html_buf.as_bytes())) .unwrap(); for img in extractor.img_urls { @@ -38,3 +41,32 @@ pub fn generate_epub(extractor: Extractor) { epub.generate(&mut out_file).unwrap(); println!("Created {:?}", file_name); } + +/// Replaces characters that have to be escaped before adding to the epub's metadata +fn replace_metadata_value(value: &str) -> String { + value + .replace("&", "&") + .replace("<", "<") + .replace(">", ">") +} + +#[cfg(test)] +mod test { + use super::replace_metadata_value; + + #[test] + fn test_replace_metadata_value() { + let mut value = "Lorem ipsum"; + assert_eq!(replace_metadata_value(value), "Lorem ipsum"); + value = "Memory safe > memory unsafe"; + assert_eq!( + replace_metadata_value(value), + "Memory safe > memory unsafe" + ); + value = "Author Name "; + assert_eq!( + replace_metadata_value(value), + "Author Name <author@mail.example>" + ); + } +}