|
| 1 | +use anyhow::{anyhow, Result}; |
| 2 | +use mdbook::renderer::RenderContext; |
| 3 | +use std::path::Path; |
| 4 | +use tera::Tera; |
| 5 | + |
| 6 | +/// Renderer for the tera backend. |
| 7 | +/// |
| 8 | +/// This will read all the files in the `RenderContext` and render them using the `Tera` template. |
| 9 | +/// ``` |
| 10 | +pub struct Renderer { |
| 11 | + ctx: RenderContext, |
| 12 | + tera_template: Tera, |
| 13 | +} |
| 14 | + |
| 15 | +impl Renderer { |
| 16 | + /// Create a new `Renderer` from the `RenderContext` and `Tera` template. |
| 17 | + pub fn new(ctx: RenderContext, tera_template: Tera) -> Self { |
| 18 | + Renderer { ctx, tera_template } |
| 19 | + } |
| 20 | + |
| 21 | + /// Render the book. This goes through the output of the HTML renderer |
| 22 | + /// by considering all the output HTML files as input to the Tera template. |
| 23 | + /// It overwrites the preexisting files with their Tera-rendered version. |
| 24 | + pub fn render_book(&mut self) -> Result<()> { |
| 25 | + let dest_dir = self.ctx.destination.parent().unwrap().join("html"); |
| 26 | + if !dest_dir.is_dir() { |
| 27 | + return Err(anyhow!( |
| 28 | + "{dest_dir:?} is not a directory. Please make sure the HTML renderer is enabled." |
| 29 | + )); |
| 30 | + } |
| 31 | + self.render_book_directory(&dest_dir) |
| 32 | + } |
| 33 | + |
| 34 | + /// Render the book directory located at `path` recursively. |
| 35 | + fn render_book_directory(&mut self, path: &Path) -> Result<()> { |
| 36 | + for entry in path.read_dir()? { |
| 37 | + let entry = entry?; |
| 38 | + let path = entry.path(); |
| 39 | + if path.is_dir() { |
| 40 | + self.render_book_directory(&path)?; |
| 41 | + } else { |
| 42 | + self.process_file(&path)?; |
| 43 | + } |
| 44 | + } |
| 45 | + Ok(()) |
| 46 | + } |
| 47 | + |
| 48 | + /// Reads the file at `path` and renders it. |
| 49 | + fn process_file(&mut self, path: &Path) -> Result<()> { |
| 50 | + if path.extension().unwrap_or_default() != "html" { |
| 51 | + return Ok(()); |
| 52 | + } |
| 53 | + let file_content = std::fs::read_to_string(path)?; |
| 54 | + let output = self.render_file_content(&file_content, path)?; |
| 55 | + Ok(std::fs::write(path, output)?) |
| 56 | + } |
| 57 | + |
| 58 | + /// Creates the rendering context to be passed to the templates. |
| 59 | + /// |
| 60 | + /// # Arguments |
| 61 | + /// |
| 62 | + /// `path`: The path to the file that will be added as extra context to the renderer. |
| 63 | + fn create_context(&mut self, path: &Path) -> Result<tera::Context> { |
| 64 | + let mut context = tera::Context::new(); |
| 65 | + let book_dir = self.ctx.destination.parent().unwrap(); |
| 66 | + let relative_path = path.strip_prefix(book_dir).unwrap(); |
| 67 | + context.insert("path", &relative_path); |
| 68 | + context.insert("book_dir", &self.ctx.destination.parent().unwrap()); |
| 69 | + |
| 70 | + Ok(context) |
| 71 | + } |
| 72 | + |
| 73 | + /// Rendering logic for an individual file. |
| 74 | + fn render_file_content(&mut self, file_content: &str, path: &Path) -> Result<String> { |
| 75 | + let tera_context = self.create_context(path)?; |
| 76 | + |
| 77 | + let rendered_file = self |
| 78 | + .tera_template |
| 79 | + .render_str(file_content, &tera_context) |
| 80 | + .map_err(|e| anyhow!("Error rendering file {path:?}: {e:?}"))?; |
| 81 | + Ok(rendered_file) |
| 82 | + } |
| 83 | +} |
| 84 | + |
| 85 | +#[cfg(test)] |
| 86 | +mod test { |
| 87 | + use tempdir::TempDir; |
| 88 | + |
| 89 | + use super::*; |
| 90 | + use crate::tera_renderer::custom_component::TeraRendererConfig; |
| 91 | + use anyhow::Result; |
| 92 | + |
| 93 | + const RENDER_CONTEXT_STR: &str = r#" |
| 94 | + { |
| 95 | + "version":"0.4.32", |
| 96 | + "root":"", |
| 97 | + "book":{ |
| 98 | + "sections": [], |
| 99 | + "__non_exhaustive": null |
| 100 | + }, |
| 101 | + "destination": "", |
| 102 | + "config":{ |
| 103 | + "book":{ |
| 104 | + "authors":[ |
| 105 | + "Martin Geisler" |
| 106 | + ], |
| 107 | + "language":"en", |
| 108 | + "multilingual":false, |
| 109 | + "src":"src", |
| 110 | + "title":"Comprehensive Rust 🦀" |
| 111 | + }, |
| 112 | + "build":{ |
| 113 | + "build-dir":"book", |
| 114 | + "use-default-preprocessors":true |
| 115 | + }, |
| 116 | + "output":{ |
| 117 | + "tera-backend": { |
| 118 | + "template_dir": "templates" |
| 119 | + }, |
| 120 | + "renderers":[ |
| 121 | + "html", |
| 122 | + "tera-backend" |
| 123 | + ] |
| 124 | + } |
| 125 | + } |
| 126 | + }"#; |
| 127 | + |
| 128 | + const HTML_FILE: &str = r#" |
| 129 | + <!DOCTYPE html> |
| 130 | + {% include "test_template.html" %} |
| 131 | + PATH: {{ path }} |
| 132 | + </html> |
| 133 | + "#; |
| 134 | + |
| 135 | + const TEMPLATE_FILE: &str = "RENDERED"; |
| 136 | + |
| 137 | + const RENDERED_HTML_FILE: &str = r#" |
| 138 | + <!DOCTYPE html> |
| 139 | + RENDERED |
| 140 | + PATH: html/test.html |
| 141 | + </html> |
| 142 | + "#; |
| 143 | + |
| 144 | + #[test] |
| 145 | + fn test_renderer() -> Result<()> { |
| 146 | + let mut ctx = RenderContext::from_json(RENDER_CONTEXT_STR.as_bytes()).unwrap(); |
| 147 | + |
| 148 | + let tmp_dir = TempDir::new("output")?; |
| 149 | + let html_path = tmp_dir.path().join("html"); |
| 150 | + let templates_path = tmp_dir.path().join("templates"); |
| 151 | + |
| 152 | + std::fs::create_dir(&html_path)?; |
| 153 | + std::fs::create_dir(&templates_path)?; |
| 154 | + |
| 155 | + let html_file_path = html_path.join("test.html"); |
| 156 | + std::fs::write(&html_file_path, HTML_FILE)?; |
| 157 | + std::fs::write(templates_path.join("test_template.html"), TEMPLATE_FILE)?; |
| 158 | + |
| 159 | + ctx.destination = tmp_dir.path().join("tera-renderer"); |
| 160 | + ctx.root = tmp_dir.path().to_owned(); |
| 161 | + |
| 162 | + let config: TeraRendererConfig = ctx |
| 163 | + .config |
| 164 | + .get_deserialized_opt("output.tera-backend")? |
| 165 | + .ok_or_else(|| anyhow!("No tera backend configuration."))?; |
| 166 | + |
| 167 | + let tera_template = config.create_template(&ctx.root)?; |
| 168 | + let mut renderer = Renderer::new(ctx, tera_template); |
| 169 | + renderer.render_book().expect("Failed to render book"); |
| 170 | + |
| 171 | + assert_eq!(std::fs::read_to_string(html_file_path)?, RENDERED_HTML_FILE); |
| 172 | + Ok(()) |
| 173 | + } |
| 174 | +} |
0 commit comments