Skip to content

Commit

Permalink
Add support for epub-version parameter in mdbook-epub plugin
Browse files Browse the repository at this point in the history
  • Loading branch information
dluschan committed Oct 29, 2024
1 parent 0347a01 commit b6fe2f9
Show file tree
Hide file tree
Showing 4 changed files with 88 additions and 2 deletions.
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,11 @@ its section number.
`curly-quotes`: Enable converting straight quotes `'x'` and `"x"` to `‘x’` and
`“x”` (aka *smart quotes*).

`epub-version`: Specifies the EPUB version to use. If omitted, the epub-builder
default version is used.
- `2` — EPUB 2.0.1
- `3` — EPUB 3.0.1

```toml
[output.epub]
additional-css = ["./path/to/main.css"]
Expand All @@ -83,6 +88,7 @@ cover-image = "ebook-cover.png"
additional-resources = ["./assets/Open-Sans-Regular.ttf"]
no-section-label = true
curly-quotes = true
epub-version = 3
```

## Logging, seeing progress
Expand Down
3 changes: 3 additions & 0 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ pub struct Config {
pub no_section_label: bool,
/// Use "smart quotes" instead of the usual `"` character.
pub curly_quotes: bool,
/// EPUB version to use if specified, otherwise defaults to the epub-builder default.
pub epub_version: Option<u8>,
}

impl Config {
Expand Down Expand Up @@ -68,6 +70,7 @@ impl Default for Config {
additional_resources: Vec::new(),
no_section_label: false,
curly_quotes: false,
epub_version: None,
}
}
}
Expand Down
16 changes: 14 additions & 2 deletions src/generator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use std::{
path::{Path, PathBuf},
};

use epub_builder::{EpubBuilder, EpubContent, ZipLibrary};
use epub_builder::{EpubBuilder, EpubContent, EpubVersion, ZipLibrary};
use handlebars::{Handlebars, RenderError, RenderErrorReason};
use html_parser::{Dom, Node};
use mdbook::book::{BookItem, Chapter};
Expand Down Expand Up @@ -44,9 +44,21 @@ impl<'a> Generator<'a> {
handler: impl ContentRetriever + 'static,
) -> Result<Generator<'a>, Error> {
let handler = Box::new(handler);
let builder = EpubBuilder::new(ZipLibrary::new()?)?;
let config = Config::from_render_context(ctx)?;

// Проверка epub_version перед созданием builder
let epub_version = match config.epub_version {
Some(2) => Some(EpubVersion::V20),
Some(3) => Some(EpubVersion::V30),
Some(v) => return Err(Error::EpubDocCreate(format!("Unsupported epub version specified in book.toml: {}", v))),
None => None,
};

let mut builder = EpubBuilder::new(ZipLibrary::new()?)?;
if let Some(version) = epub_version {
builder.epub_version(version);
}

let mut hbs = Handlebars::new();
hbs.register_template_string("index", config.template()?)
.map_err(|_| Error::TemplateParse)?;
Expand Down
65 changes: 65 additions & 0 deletions tests/epub_version.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
use std::fs;
use std::io::{self, Write};
use std::process::Command;
use tempfile::TempDir;

fn create_book_with_epub_version(epub_version: &str) -> io::Result<String> {
let temp_dir = TempDir::new()?;
let book_path = temp_dir.path();

Command::new("mdbook")
.arg("init")
.arg(book_path)
.arg("--title")
.arg("Dummy Book")
.output()?;

let book_toml_path = book_path.join("book.toml");
let mut book_toml = fs::OpenOptions::new()
.append(true)
.open(&book_toml_path)?;
writeln!(book_toml, "[output.epub]\nepub-version = {}", epub_version)?;

let build_output = Command::new("mdbook")
.arg("build")
.arg(book_path)
.output()?;

if !build_output.status.success() {
let stderr = String::from_utf8_lossy(&build_output.stderr);
return Err(io::Error::new(io::ErrorKind::Other, stderr.to_string()));
}

Ok("Book built successfully".to_string())
}


#[test]
fn test_valid_epub_version_2() {
create_book_with_epub_version("2").expect("Expected EPUB version 2 to build successfully");
}

#[test]
fn test_valid_epub_version_3() {
create_book_with_epub_version("3").expect("Expected EPUB version 3 to build successfully");
}

#[test]
fn test_invalid_epub_version_5() {
let result = create_book_with_epub_version("5").expect_err("Expected EPUB version 5 to fail");
assert!(
result.to_string().contains("Unsupported epub version specified in book.toml: 5"),
"Unexpected error message: {}",
result
);
}

#[test]
fn test_invalid_epub_version_string() {
let result = create_book_with_epub_version("\"3.0.1\"").expect_err("Expected EPUB version '3.0.1' to fail");
assert!(
result.to_string().contains("expected u8 for key `epub-version`"),
"Unexpected error message: {}",
result
);
}

0 comments on commit b6fe2f9

Please sign in to comment.