| 1 |
use std::collections::HashMap; |
| 2 |
|
| 3 |
use mdbook_core::utils; |
| 4 |
|
| 5 |
use handlebars::{ |
| 6 |
Context, Handlebars, Helper, HelperDef, Output, RenderContext, RenderError, RenderErrorReason, |
| 7 |
}; |
| 8 |
|
| 9 |
// Handlebars helper to find filenames with hashes in them |
| 10 |
#[derive(Clone)] |
| 11 |
pub(crate) struct ResourceHelper { |
| 12 |
pub hash_map: HashMap<String, String>, |
| 13 |
} |
| 14 |
|
| 15 |
impl HelperDef for ResourceHelper { |
| 16 |
fn call<'reg: 'rc, 'rc>( |
| 17 |
&self, |
| 18 |
h: &Helper<'rc>, |
| 19 |
_r: &'reg Handlebars<'_>, |
| 20 |
ctx: &'rc Context, |
| 21 |
rc: &mut RenderContext<'reg, 'rc>, |
| 22 |
out: &mut dyn Output, |
| 23 |
) -> Result<(), RenderError> { |
| 24 |
let param = h.param(0).and_then(|v| v.value().as_str()).ok_or_else(|| { |
| 25 |
RenderErrorReason::Other( |
| 26 |
"Param 0 with String type is required for resource helper.".to_owned(), |
| 27 |
) |
| 28 |
})?; |
| 29 |
|
| 30 |
let base_path = rc |
| 31 |
.evaluate(ctx, "@root/path")? |
| 32 |
.as_json() |
| 33 |
.as_str() |
| 34 |
.ok_or_else(|| { |
| 35 |
RenderErrorReason::Other("Type error for `path`, string expected".to_owned()) |
| 36 |
})? |
| 37 |
.replace("\"", ""); |
| 38 |
|
| 39 |
let path_to_root = utils::fs::path_to_root(&base_path); |
| 40 |
|
| 41 |
out.write(&path_to_root)?; |
| 42 |
out.write(self.hash_map.get(param).map(|p| &p[..]).unwrap_or(¶m))?; |
| 43 |
Ok(()) |
| 44 |
} |
| 45 |
} |