mdbook_driver/builtin_renderers/
markdown_renderer.rs

1use anyhow::{Context, Result};
2use mdbook_core::utils::fs;
3use mdbook_renderer::{RenderContext, Renderer};
4use tracing::trace;
5
6/// A renderer to output the Markdown after the preprocessors have run. Mostly useful
7/// when debugging preprocessors.
8#[derive(Default)]
9#[non_exhaustive]
10pub struct MarkdownRenderer;
11
12impl MarkdownRenderer {
13    /// Create a new `MarkdownRenderer` instance.
14    pub fn new() -> Self {
15        MarkdownRenderer
16    }
17}
18
19impl Renderer for MarkdownRenderer {
20    fn name(&self) -> &str {
21        "markdown"
22    }
23
24    fn render(&self, ctx: &RenderContext) -> Result<()> {
25        let destination = &ctx.destination;
26        let book = &ctx.book;
27
28        if destination.exists() {
29            fs::remove_dir_content(destination)
30                .with_context(|| "Unable to remove stale Markdown output")?;
31        }
32
33        trace!("markdown render");
34        for ch in book.chapters() {
35            let path = ctx
36                .destination
37                .join(ch.path.as_ref().expect("Checked path exists before"));
38            fs::write(path, &ch.content)?;
39        }
40
41        fs::create_dir_all(destination)
42            .with_context(|| "Unexpected error when constructing destination path")?;
43
44        Ok(())
45    }
46}