1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
use mdbook::renderer::{RenderContext, Renderer};
use mdbook::book::BookItem;
use mdbook::errors::Result;

use std::fs::create_dir_all;
use std::fs::OpenOptions;
use std::io::Write;

/// An implementation of a renderer which writes all preprocessed markdown files.
///
/// This can be useful for debugging.
pub struct Rewrite;

impl Rewrite {
    pub fn new() -> Self {
        Rewrite
    }
}

impl Renderer for Rewrite {
    fn name(&self) -> &str {
        "markdown-rewrite"
    }

    fn render(&self, ctx: &RenderContext) -> Result<()> {
        for item in ctx.book.iter() {
            if let &BookItem::Chapter(ref chapter) = item {
                let dir = ctx.destination
                    .join(&chapter.path.parent().expect("at least filename"));
                create_dir_all(&dir)?;
                let output_file = dir.join(&chapter.path);
                let mut fout = OpenOptions::new()
                    .write(true)
                    .create(true)
                    .open(&output_file)?;
                fout.write_all(chapter.content.as_bytes())?;
                eprintln!("Wrote markdown file at '{}'.", chapter.path.display());
            }
        }
        Ok(())
    }
}