Skip to content

Instantly share code, notes, and snippets.

@JustSimplyKyle
Last active November 19, 2023 02:28
Show Gist options
  • Save JustSimplyKyle/d13e7821beedfcbd3c141b6f589dc82a to your computer and use it in GitHub Desktop.
Save JustSimplyKyle/d13e7821beedfcbd3c141b6f589dc82a to your computer and use it in GitHub Desktop.
[package]
name = "cbztoepub"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
argh = "0.1.12"
color-eyre = "0.6.2"
pandoc = "0.8.10"
tempfile = "3.8.1"
zip = "0.6.6"
use std::{
fs::{create_dir_all, remove_dir_all, File},
io::Write,
path::PathBuf,
};
use argh::FromArgs;
use color_eyre::eyre::ContextCompat;
use tempfile::tempdir;
#[derive(FromArgs)]
/// Easy conversion from cbz to epub.
struct Arguments {
/// input file.
#[argh(option, short = 'i')]
input: PathBuf,
/// an optional nickname for the pilot
#[argh(option, short = 'o')]
output: PathBuf,
}
fn main() -> color_eyre::Result<()> {
color_eyre::install()?;
let args: Arguments = argh::from_env();
let file = File::open(args.input)?;
let mut archive = zip::ZipArchive::new(file)?;
let temp_dir = tempdir()?.into_path();
archive.extract(&temp_dir)?;
let html_path = temp_dir.join("html_pages");
let mut pandoc = pandoc::new();
create_dir_all(&html_path)?;
let mut sorted_filenames = archive.file_names().collect::<Vec<_>>();
sorted_filenames.sort_unstable();
for (str, path) in sorted_filenames.iter().map(|x| {
(
format!(
"<img src='{}/{x}' style='height: 100%; width: auto'>",
temp_dir.display()
),
html_path.join(x),
)
}) {
let with_html_extension = path.with_extension("html");
let mut file = File::create(&with_html_extension)?;
pandoc.add_input(&with_html_extension);
write!(&mut file, "{str}")?;
}
let first_picture = temp_dir.join(sorted_filenames.first().context("archive is empty.")?);
pandoc.add_option(pandoc::PandocOption::EpubCoverImage(first_picture));
pandoc.set_output(pandoc::OutputKind::File(args.output.with_extension("epub")));
pandoc.execute()?;
remove_dir_all(temp_dir)?;
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment