hagrid-keyserver--hagrid/src/template_helpers.rs

86 lines
2.7 KiB
Rust
Raw Normal View History

2019-09-30 10:52:00 +00:00
use std::collections::HashSet;
2022-02-26 15:54:07 +00:00
use std::path::{Path, PathBuf};
2019-09-30 10:52:00 +00:00
use handlebars::Handlebars;
use gettext_macros::include_i18n;
use crate::i18n::I18NHelper;
2022-02-26 15:54:07 +00:00
use crate::Result;
2019-09-30 10:52:00 +00:00
#[derive(Debug)]
2020-01-29 09:54:24 +00:00
pub struct TemplateOverrides(String, HashSet<String>);
2019-09-30 10:52:00 +00:00
impl TemplateOverrides {
pub fn load(template_path: &Path, localized_dir: &str) -> Result<Self> {
load_localized_template_names(template_path, localized_dir)
.map(|vec| Self(localized_dir.to_owned(), vec))
}
2022-02-26 15:54:07 +00:00
pub fn get_template_override(&self, lang: &str, tmpl: &str) -> Option<String> {
2019-09-30 10:52:00 +00:00
let template_name = format!("{}/{}/{}", self.0, lang, tmpl);
if self.1.contains(&template_name) {
println!("{}", &template_name);
Some(template_name)
} else {
None
}
}
}
2022-02-26 15:54:07 +00:00
fn load_localized_template_names(
template_path: &Path,
localized_dir: &str,
) -> Result<HashSet<String>> {
2019-09-30 10:52:00 +00:00
let language_glob = template_path.join(localized_dir).join("*");
glob::glob(language_glob.to_str().expect("valid glob path string"))
.unwrap()
.flatten()
.flat_map(|language_path| {
let mut template_glob = language_path.join("**").join("*");
template_glob.set_extension("hbs");
glob::glob(template_glob.to_str().expect("valid glob path string"))
.unwrap()
.flatten()
.map(move |path| {
// TODO this is a hack
2022-02-26 15:54:07 +00:00
let template_name =
remove_extension(remove_extension(path.strip_prefix(&template_path)?));
2019-09-30 10:52:00 +00:00
Ok(template_name.to_string_lossy().into_owned())
})
2022-02-26 15:54:07 +00:00
})
.collect()
2019-09-30 10:52:00 +00:00
}
pub fn load_handlebars(template_dir: &Path) -> Result<Handlebars<'static>> {
2019-09-30 10:52:00 +00:00
let mut handlebars = Handlebars::new();
let i18ns = include_i18n!();
let i18n_helper = I18NHelper::new(i18ns);
handlebars.register_helper("text", Box::new(i18n_helper));
let mut glob_path = template_dir.join("**").join("*");
glob_path.set_extension("hbs");
let glob_path = glob_path.to_str().expect("valid glob path string");
for path in glob::glob(glob_path).unwrap().flatten() {
2020-03-28 12:48:20 +00:00
let template_name = remove_extension(path.strip_prefix(template_dir)?);
2019-09-30 10:52:00 +00:00
handlebars.register_template_file(&template_name.to_string_lossy(), &path)?;
}
Ok(handlebars)
}
fn remove_extension<P: AsRef<Path>>(path: P) -> PathBuf {
let path = path.as_ref();
let stem = match path.file_stem() {
Some(stem) => stem,
2022-02-26 15:54:07 +00:00
None => return path.to_path_buf(),
2019-09-30 10:52:00 +00:00
};
match path.parent() {
Some(parent) => parent.join(stem),
2022-02-26 15:54:07 +00:00
None => PathBuf::from(stem),
2019-09-30 10:52:00 +00:00
}
}