The preprocessor trait now returns a modified book instead of editing in place

This commit is contained in:
Michael Bryan 2018-08-30 21:31:14 +08:00
parent a0e7b19784
commit 769fd94868
No known key found for this signature in database
GPG Key ID: E9C602B0D9A998DC
6 changed files with 94 additions and 78 deletions

View File

@ -14,45 +14,7 @@ use std::env::{args, args_os};
use std::ffi::OsString; use std::ffi::OsString;
use std::process; use std::process;
struct Deemphasize; const NAME: &str = "md-links-to-html-links";
impl Preprocessor for Deemphasize {
fn name(&self) -> &str {
"md-links-to-html-links"
}
fn run(&self, _ctx: &PreprocessorContext, book: &mut Book) -> Result<()> {
eprintln!("Running '{}' preprocessor", self.name());
let mut res: Option<_> = None;
let mut num_removed_items = 0;
book.for_each_mut(|item: &mut BookItem| {
if let Some(Err(_)) = res {
return;
}
if let BookItem::Chapter(ref mut chapter) = *item {
eprintln!("{}: processing chapter '{}'", self.name(), chapter.name);
res = Some(
match Deemphasize::remove_emphasis(&mut num_removed_items, chapter) {
Ok(md) => {
chapter.content = md;
Ok(())
}
Err(err) => Err(err),
},
);
}
});
eprintln!(
"{}: removed {} events from markdown stream.",
self.name(),
num_removed_items
);
match res {
Some(res) => res,
None => Ok(()),
}
}
}
fn do_it(book: OsString) -> Result<()> { fn do_it(book: OsString) -> Result<()> {
let mut book = MDBook::load(book)?; let mut book = MDBook::load(book)?;
@ -71,24 +33,66 @@ fn main() {
} }
} }
impl Deemphasize { struct Deemphasize;
fn remove_emphasis(num_removed_items: &mut i32, chapter: &mut Chapter) -> Result<String> {
let mut buf = String::with_capacity(chapter.content.len()); impl Preprocessor for Deemphasize {
let events = Parser::new(&chapter.content).filter(|e| { fn name(&self) -> &str {
let should_keep = match *e { NAME
Event::Start(Tag::Emphasis) }
| Event::Start(Tag::Strong)
| Event::End(Tag::Emphasis) fn run(&self, _ctx: &PreprocessorContext, mut book: Book) -> Result<Book> {
| Event::End(Tag::Strong) => false, eprintln!("Running '{}' preprocessor", self.name());
_ => true, let mut num_removed_items = 0;
};
if !should_keep { process(&mut book.sections, &mut num_removed_items)?;
*num_removed_items += 1;
} eprintln!(
should_keep "{}: removed {} events from markdown stream.",
}); self.name(),
cmark(events, &mut buf, None) num_removed_items
.map(|_| buf) );
.map_err(|err| Error::from(format!("Markdown serialization failed: {}", err)))
Ok(book)
} }
} }
fn process<'a, I>(items: I, num_removed_items: &mut usize) -> Result<()>
where
I: IntoIterator<Item = &'a mut BookItem> + 'a,
{
for item in items {
if let BookItem::Chapter(ref mut chapter) = *item {
eprintln!("{}: processing chapter '{}'", NAME, chapter.name);
let md = remove_emphasis(num_removed_items, chapter)?;
chapter.content = md;
}
}
Ok(())
}
fn remove_emphasis(
num_removed_items: &mut usize,
chapter: &mut Chapter,
) -> Result<String> {
let mut buf = String::with_capacity(chapter.content.len());
let events = Parser::new(&chapter.content).filter(|e| {
let should_keep = match *e {
Event::Start(Tag::Emphasis)
| Event::Start(Tag::Strong)
| Event::End(Tag::Emphasis)
| Event::End(Tag::Strong) => false,
_ => true,
};
if !should_keep {
*num_removed_items += 1;
}
should_keep
});
cmark(events, &mut buf, None).map(|_| buf).map_err(|err| {
Error::from(format!("Markdown serialization failed: {}", err))
})
}

View File

@ -149,23 +149,35 @@ impl MDBook {
pub fn build(&self) -> Result<()> { pub fn build(&self) -> Result<()> {
info!("Book building has started"); info!("Book building has started");
let mut preprocessed_book = self.book.clone();
let preprocess_ctx = PreprocessorContext::new(self.root.clone(), self.config.clone());
for preprocessor in &self.preprocessors {
debug!("Running the {} preprocessor.", preprocessor.name());
preprocessor.run(&preprocess_ctx, &mut preprocessed_book)?;
}
for renderer in &self.renderers { for renderer in &self.renderers {
info!("Running the {} backend", renderer.name()); self.execute_build_process(&**renderer)?;
self.run_renderer(&preprocessed_book, renderer.as_ref())?;
} }
Ok(()) Ok(())
} }
fn run_renderer(&self, preprocessed_book: &Book, renderer: &Renderer) -> Result<()> { fn execute_build_process(&self, renderer: &Renderer) -> Result<()> {
let mut preprocessed_book = self.book.clone();
let preprocess_ctx =
PreprocessorContext::new(self.root.clone(), self.config.clone());
for preprocessor in &self.preprocessors {
debug!("Running the {} preprocessor.", preprocessor.name());
preprocessed_book =
preprocessor.run(&preprocess_ctx, preprocessed_book)?;
}
info!("Running the {} backend", renderer.name());
self.render(&preprocessed_book, renderer)?;
Ok(())
}
fn render(
&self,
preprocessed_book: &Book,
renderer: &Renderer,
) -> Result<()> {
let name = renderer.name(); let name = renderer.name();
let build_dir = self.build_dir_for(name); let build_dir = self.build_dir_for(name);
if build_dir.exists() { if build_dir.exists() {
@ -217,11 +229,11 @@ impl MDBook {
let preprocess_context = PreprocessorContext::new(self.root.clone(), self.config.clone()); let preprocess_context = PreprocessorContext::new(self.root.clone(), self.config.clone());
LinkPreprocessor::new().run(&preprocess_context, &mut self.book)?; let book = LinkPreprocessor::new().run(&preprocess_context, self.book.clone())?;
// Index Preprocessor is disabled so that chapter paths continue to point to the // Index Preprocessor is disabled so that chapter paths continue to point to the
// actual markdown files. // actual markdown files.
for item in self.iter() { for item in book.iter() {
if let BookItem::Chapter(ref ch) = *item { if let BookItem::Chapter(ref ch) = *item {
if !ch.path.as_os_str().is_empty() { if !ch.path.as_os_str().is_empty() {
let path = self.source_dir().join(&ch.path); let path = self.source_dir().join(&ch.path);

View File

@ -22,7 +22,7 @@ impl Preprocessor for IndexPreprocessor {
"index" "index"
} }
fn run(&self, ctx: &PreprocessorContext, book: &mut Book) -> Result<()> { fn run(&self, ctx: &PreprocessorContext, mut book: Book) -> Result<Book> {
let source_dir = ctx.root.join(&ctx.config.book.src); let source_dir = ctx.root.join(&ctx.config.book.src);
book.for_each_mut(|section: &mut BookItem| { book.for_each_mut(|section: &mut BookItem| {
if let BookItem::Chapter(ref mut ch) = *section { if let BookItem::Chapter(ref mut ch) = *section {
@ -37,7 +37,7 @@ impl Preprocessor for IndexPreprocessor {
} }
}); });
Ok(()) Ok(book)
} }
} }

View File

@ -27,7 +27,7 @@ impl Preprocessor for LinkPreprocessor {
"links" "links"
} }
fn run(&self, ctx: &PreprocessorContext, book: &mut Book) -> Result<()> { fn run(&self, ctx: &PreprocessorContext, mut book: Book) -> Result<Book> {
let src_dir = ctx.root.join(&ctx.config.book.src); let src_dir = ctx.root.join(&ctx.config.book.src);
book.for_each_mut(|section: &mut BookItem| { book.for_each_mut(|section: &mut BookItem| {
@ -43,7 +43,7 @@ impl Preprocessor for LinkPreprocessor {
} }
}); });
Ok(()) Ok(book)
} }
} }

View File

@ -36,5 +36,5 @@ pub trait Preprocessor {
/// Run this `Preprocessor`, allowing it to update the book before it is /// Run this `Preprocessor`, allowing it to update the book before it is
/// given to a renderer. /// given to a renderer.
fn run(&self, ctx: &PreprocessorContext, book: &mut Book) -> Result<()>; fn run(&self, ctx: &PreprocessorContext, book: Book) -> Result<Book>;
} }

View File

@ -39,9 +39,9 @@ fn mdbook_runs_preprocessors() {
"dummy" "dummy"
} }
fn run(&self, _ctx: &PreprocessorContext, _book: &mut Book) -> Result<()> { fn run(&self, _ctx: &PreprocessorContext, book: Book) -> Result<Book> {
*self.0.lock().unwrap() = true; *self.0.lock().unwrap() = true;
Ok(()) Ok(book)
} }
} }