Renamed a couple functions to be more descriptive and ran rustfmt

This commit is contained in:
Michael Bryan 2017-06-17 21:15:54 +08:00
parent deab3ba751
commit 4af10ce60c
1 changed files with 63 additions and 68 deletions

View File

@ -30,6 +30,7 @@ impl HtmlHandlebars {
fn render_item(&self, item: &BookItem, book: &MDBook, data: &mut serde_json::Map<String, serde_json::Value>, fn render_item(&self, item: &BookItem, book: &MDBook, data: &mut serde_json::Map<String, serde_json::Value>,
print_content: &mut String, handlebars: &mut Handlebars, index: &mut bool, destination: &Path) print_content: &mut String, handlebars: &mut Handlebars, index: &mut bool, destination: &Path)
-> Result<(), Box<Error>> { -> Result<(), Box<Error>> {
// FIXME: This should be made DRY-er and rely less on mutable state
match *item { match *item {
BookItem::Chapter(_, ref ch) | BookItem::Chapter(_, ref ch) |
BookItem::Affix(ref ch) => { BookItem::Affix(ref ch) => {
@ -53,8 +54,7 @@ impl HtmlHandlebars {
print_content.push_str(&content); print_content.push_str(&content);
// Update the context with data for this file // Update the context with data for this file
let path = let path = ch.path
ch.path
.to_str() .to_str()
.ok_or_else(|| io::Error::new(io::ErrorKind::Other, "Could not convert path to str"))?; .ok_or_else(|| io::Error::new(io::ErrorKind::Other, "Could not convert path to str"))?;
@ -66,7 +66,7 @@ impl HtmlHandlebars {
// Render the handlebars template with the data // Render the handlebars template with the data
debug!("[*]: Render template"); debug!("[*]: Render template");
let rendered = handlebars.render("index", &data)?; let rendered = handlebars.render("index", &data)?;
let rendered = self.post_processing(rendered); let rendered = self.post_process(rendered);
let filename = Path::new(&ch.path).with_extension("html"); let filename = Path::new(&ch.path).with_extension("html");
@ -80,15 +80,14 @@ impl HtmlHandlebars {
let mut content = String::new(); let mut content = String::new();
let _source = File::open( let _source = File::open(destination.join(&ch.path.with_extension("html")))
destination.join(&ch.path.with_extension("html")) ?
)?.read_to_string(&mut content); .read_to_string(&mut content);
// This could cause a problem when someone displays // This could cause a problem when someone displays
// code containing <base href=...> // code containing <base href=...>
// on the front page, however this case should be very very rare... // on the front page, however this case should be very very rare...
content = content content = content.lines()
.lines()
.filter(|line| !line.contains("<base href=")) .filter(|line| !line.contains("<base href="))
.collect::<Vec<&str>>() .collect::<Vec<&str>>()
.join("\n"); .join("\n");
@ -97,9 +96,9 @@ impl HtmlHandlebars {
info!("[*] Creating index.html from {:?} ✓", info!("[*] Creating index.html from {:?} ✓",
book.get_destination() book.get_destination()
.expect("If the HTML renderer is called, one would assume the HtmlConfig is set... (4)") .expect("If the HTML renderer is called, one would assume the HtmlConfig is \
.join(&ch.path.with_extension("html")) set... (4)")
); .join(&ch.path.with_extension("html")));
*index = false; *index = false;
} }
} }
@ -110,7 +109,7 @@ impl HtmlHandlebars {
Ok(()) Ok(())
} }
fn post_processing(&self, rendered: String) -> String { fn post_process(&self, rendered: String) -> String {
let rendered = build_header_links(rendered, "print.html"); let rendered = build_header_links(rendered, "print.html");
let rendered = fix_anchor_links(rendered, "print.html"); let rendered = fix_anchor_links(rendered, "print.html");
let rendered = fix_code_blocks(rendered); let rendered = fix_code_blocks(rendered);
@ -149,8 +148,7 @@ impl HtmlHandlebars {
let name = match custom_file.strip_prefix(book.get_root()) { let name = match custom_file.strip_prefix(book.get_root()) {
Ok(p) => p.to_str().expect("Could not convert to str"), Ok(p) => p.to_str().expect("Could not convert to str"),
Err(_) => { Err(_) => {
custom_file custom_file.file_name()
.file_name()
.expect("File has a file name") .expect("File has a file name")
.to_str() .to_str()
.expect("Could not convert to str") .expect("Could not convert to str")
@ -175,10 +173,14 @@ impl HtmlHandlebars {
handlebars.register_helper("next", Box::new(helpers::navigation::next)); handlebars.register_helper("next", Box::new(helpers::navigation::next));
} }
fn copy_additional_css(&self, book: &MDBook) -> Result<(), Box<Error>> { /// Copy across any additional CSS and JavaScript files which the book
for custom_file in book.get_additional_css() /// has been configured to use.
fn copy_additional_css_and_js(&self, book: &MDBook) -> Result<(), Box<Error>> {
let custom_files = book.get_additional_css()
.iter() .iter()
.chain(book.get_additional_js().iter()) { .chain(book.get_additional_js().iter());
for custom_file in custom_files {
self.write_custom_file(custom_file, book)?; self.write_custom_file(custom_file, book)?;
} }
@ -195,8 +197,7 @@ impl Renderer for HtmlHandlebars {
let theme = theme::Theme::new(book.get_theme_path()); let theme = theme::Theme::new(book.get_theme_path());
debug!("[*]: Register handlebars template"); debug!("[*]: Register handlebars template");
handlebars handlebars.register_template_string("index", String::from_utf8(theme.index.clone())?)?;
.register_template_string("index", String::from_utf8(theme.index.clone())?)?;
debug!("[*]: Register handlebars helpers"); debug!("[*]: Register handlebars helpers");
self.register_hbs_helpers(&mut handlebars); self.register_hbs_helpers(&mut handlebars);
@ -227,7 +228,7 @@ impl Renderer for HtmlHandlebars {
debug!("[*]: Render template"); debug!("[*]: Render template");
let rendered = handlebars.render("index", &data)?; let rendered = handlebars.render("index", &data)?;
let rendered = self.post_processing(rendered); let rendered = self.post_process(rendered);
book.write_file(Path::new("print").with_extension("html"), &rendered.into_bytes())?; book.write_file(Path::new("print").with_extension("html"), &rendered.into_bytes())?;
info!("[*] Creating print.html ✓"); info!("[*] Creating print.html ✓");
@ -235,7 +236,7 @@ impl Renderer for HtmlHandlebars {
// Copy static files (js, css, images, ...) // Copy static files (js, css, images, ...)
debug!("[*] Copy static files"); debug!("[*] Copy static files");
self.copy_static_files(book, &theme)?; self.copy_static_files(book, &theme)?;
self.copy_additional_css(book)?; self.copy_additional_css_and_js(book)?;
// Copy all remaining files // Copy all remaining files
utils::fs::copy_files_except_ext(book.get_source(), &destination, true, &["md"])?; utils::fs::copy_files_except_ext(book.get_source(), &destination, true, &["md"])?;
@ -268,8 +269,7 @@ fn make_data(book: &MDBook) -> Result<serde_json::Map<String, serde_json::Value>
match style.strip_prefix(book.get_root()) { match style.strip_prefix(book.get_root()) {
Ok(p) => css.push(p.to_str().expect("Could not convert to str")), Ok(p) => css.push(p.to_str().expect("Could not convert to str")),
Err(_) => { Err(_) => {
css.push(style css.push(style.file_name()
.file_name()
.expect("File has a file name") .expect("File has a file name")
.to_str() .to_str()
.expect("Could not convert to str")) .expect("Could not convert to str"))
@ -286,8 +286,7 @@ fn make_data(book: &MDBook) -> Result<serde_json::Map<String, serde_json::Value>
match script.strip_prefix(book.get_root()) { match script.strip_prefix(book.get_root()) {
Ok(p) => js.push(p.to_str().expect("Could not convert to str")), Ok(p) => js.push(p.to_str().expect("Could not convert to str")),
Err(_) => { Err(_) => {
js.push(script js.push(script.file_name()
.file_name()
.expect("File has a file name") .expect("File has a file name")
.to_str() .to_str()
.expect("Could not convert to str")) .expect("Could not convert to str"))
@ -338,8 +337,7 @@ fn build_header_links(html: String, filename: &str) -> String {
let regex = Regex::new(r"<h(\d)>(.*?)</h\d>").unwrap(); let regex = Regex::new(r"<h(\d)>(.*?)</h\d>").unwrap();
let mut id_counter = HashMap::new(); let mut id_counter = HashMap::new();
regex regex.replace_all(&html, |caps: &Captures| {
.replace_all(&html, |caps: &Captures| {
let level = &caps[1]; let level = &caps[1];
let text = &caps[2]; let text = &caps[2];
let mut id = text.to_string(); let mut id = text.to_string();
@ -394,8 +392,7 @@ fn build_header_links(html: String, filename: &str) -> String {
// that in a very inelegant way // that in a very inelegant way
fn fix_anchor_links(html: String, filename: &str) -> String { fn fix_anchor_links(html: String, filename: &str) -> String {
let regex = Regex::new(r##"<a([^>]+)href="#([^"]+)"([^>]*)>"##).unwrap(); let regex = Regex::new(r##"<a([^>]+)href="#([^"]+)"([^>]*)>"##).unwrap();
regex regex.replace_all(&html, |caps: &Captures| {
.replace_all(&html, |caps: &Captures| {
let before = &caps[1]; let before = &caps[1];
let anchor = &caps[2]; let anchor = &caps[2];
let after = &caps[3]; let after = &caps[3];
@ -420,8 +417,7 @@ fn fix_anchor_links(html: String, filename: &str) -> String {
// This function replaces all commas by spaces in the code block classes // This function replaces all commas by spaces in the code block classes
fn fix_code_blocks(html: String) -> String { fn fix_code_blocks(html: String) -> String {
let regex = Regex::new(r##"<code([^>]+)class="([^"]+)"([^>]*)>"##).unwrap(); let regex = Regex::new(r##"<code([^>]+)class="([^"]+)"([^>]*)>"##).unwrap();
regex regex.replace_all(&html, |caps: &Captures| {
.replace_all(&html, |caps: &Captures| {
let before = &caps[1]; let before = &caps[1];
let classes = &caps[2].replace(",", " "); let classes = &caps[2].replace(",", " ");
let after = &caps[3]; let after = &caps[3];
@ -433,8 +429,7 @@ fn fix_code_blocks(html: String) -> String {
fn add_playpen_pre(html: String) -> String { fn add_playpen_pre(html: String) -> String {
let regex = Regex::new(r##"((?s)<code[^>]?class="([^"]+)".*?>(.*?)</code>)"##).unwrap(); let regex = Regex::new(r##"((?s)<code[^>]?class="([^"]+)".*?>(.*?)</code>)"##).unwrap();
regex regex.replace_all(&html, |caps: &Captures| {
.replace_all(&html, |caps: &Captures| {
let text = &caps[1]; let text = &caps[1];
let classes = &caps[2]; let classes = &caps[2];
let code = &caps[3]; let code = &caps[3];