Skip to content

Commit

Permalink
Merge pull request #36 from yuma140902/template-engine
Browse files Browse the repository at this point in the history
add `TemplateEngine`
  • Loading branch information
yuma140902 authored Oct 14, 2023
2 parents d75008e + cf8d60a commit 5c4eb84
Show file tree
Hide file tree
Showing 4 changed files with 93 additions and 62 deletions.
67 changes: 5 additions & 62 deletions src/generator/handlebars_generator.rs
Original file line number Diff line number Diff line change
@@ -1,78 +1,21 @@
use std::{
borrow::Borrow,
fs,
path::{Path, PathBuf},
};
use std::{borrow::Borrow, fs, path::Path};

use anyhow::Context as _;
use handlebars::{
handlebars_helper, Context, Handlebars, Helper, HelperResult, JsonRender, Output,
RenderContext, RenderError,
};
use handlebars::Handlebars;
use path_absolutize::Absolutize;
use serde_json::{Map, Value as Json};
use serde_yaml::Value as Yaml;
use tracing::info;
use walkdir::WalkDir;

use crate::{directory, project_config::GeneratorRule};
use crate::{directory, handlebars_helpers, project_config::GeneratorRule};

use super::{Generator, GeneratorResult};

handlebars_helper!(md2html: |markdown: String| {
let options = pulldown_cmark::Options::empty();
let parser = pulldown_cmark::Parser::new_ext(&markdown, options);
let mut html_output = String::new();
pulldown_cmark::html::push_html(&mut html_output, parser);
html_output
});

fn resolve(
h: &Helper<'_, '_>,
_: &Handlebars<'_>,
ctx: &Context,
_rc: &mut RenderContext<'_, '_>,
out: &mut dyn Output,
) -> HelperResult {
let target_input_path = PathBuf::from(
h.param(0)
.and_then(|v| v.value().as_str())
.ok_or_else(|| RenderError::new("target_input_path not specified"))?,
);
let project_root = PathBuf::from(
ctx.data()
.get("project_root")
.ok_or_else(|| RenderError::new("project_root not specified"))?
.render()
.as_str(),
);
let output_directory = directory::get_output_directory(project_root);
let self_output_filepath = PathBuf::from(
ctx.data()
.get("output_file")
.ok_or_else(|| RenderError::new("output_file not specified"))?
.render()
.as_str(),
);
let self_output_parent = self_output_filepath.parent().ok_or_else(|| {
RenderError::new(format!(
"could not get parent directory for output_file '{}'",
self_output_filepath.display()
))
})?;

let target_output_path = output_directory.join(target_input_path); //TODO:
//rule.export_extension
//rule.export_base
let relative_path = directory::get_relative_path(target_output_path, self_output_parent);
write!(out, "{}", relative_path.display())?;
Ok(())
}

fn setup_handlebars(project_root: impl AsRef<Path>) -> Handlebars<'static> {
let mut handlebars = Handlebars::new();
handlebars.register_helper("md2html", Box::new(md2html));
handlebars.register_helper("resolve", Box::new(resolve));
handlebars.register_helper("md2html", Box::new(handlebars_helpers::md2html));
handlebars.register_helper("resolve", Box::new(handlebars_helpers::resolve));

// enumerate template files
for path in WalkDir::new(directory::get_templates_directory(project_root))
Expand Down
62 changes: 62 additions & 0 deletions src/handlebars_helpers.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
//! This module defines a custom Helper for Tempura.
//! Helper is a term used in Handlebars to refer to a kind of function that can be called from a template.

use std::path::PathBuf;

use handlebars::{
handlebars_helper, Context, Handlebars, Helper, HelperResult, JsonRender, Output,
RenderContext, RenderError,
};

use crate::directory;

handlebars_helper!(md2html: |markdown: String| {
let options = pulldown_cmark::Options::empty();
let parser = pulldown_cmark::Parser::new_ext(&markdown, options);
let mut html_output = String::new();
pulldown_cmark::html::push_html(&mut html_output, parser);
html_output
});

// TODO:
pub fn resolve(
h: &Helper<'_, '_>,
_: &Handlebars<'_>,
ctx: &Context,
_rc: &mut RenderContext<'_, '_>,
out: &mut dyn Output,
) -> HelperResult {
let target_input_path = PathBuf::from(
h.param(0)
.and_then(|v| v.value().as_str())
.ok_or_else(|| RenderError::new("target_input_path not specified"))?,
);
let project_root = PathBuf::from(
ctx.data()
.get("project_root")
.ok_or_else(|| RenderError::new("project_root not specified"))?
.render()
.as_str(),
);
let output_directory = directory::get_output_directory(project_root);
let self_output_filepath = PathBuf::from(
ctx.data()
.get("output_file")
.ok_or_else(|| RenderError::new("output_file not specified"))?
.render()
.as_str(),
);
let self_output_parent = self_output_filepath.parent().ok_or_else(|| {
RenderError::new(format!(
"could not get parent directory for output_file '{}'",
self_output_filepath.display()
))
})?;

let target_output_path = output_directory.join(target_input_path); //TODO:
//rule.export_extension
//rule.export_base
let relative_path = directory::get_relative_path(target_output_path, self_output_parent);
write!(out, "{}", relative_path.display())?;
Ok(())
}
3 changes: 3 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,14 @@ use crate::project_config::ProjectConfig;
pub mod cli;
pub mod directory;
pub mod generator;
pub mod handlebars_helpers;
mod loader;
pub mod project_config;
mod template_engine;
mod value;

pub use loader::*;
pub use template_engine::*;
pub use value::*;

fn build_single_file(
Expand Down
23 changes: 23 additions & 0 deletions src/template_engine.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
use handlebars::Handlebars;

use crate::handlebars_helpers;

/// TemplateEngine is a wrapper for Handlebars and processes templates and [`Value`](crate::Value)s.
pub struct TemplateEngine(Handlebars<'static>);

impl TemplateEngine {
pub fn new() -> Self {
let mut handlebars = Handlebars::new();

handlebars.register_helper("md2html", Box::new(handlebars_helpers::md2html));
handlebars.register_helper("resolve", Box::new(handlebars_helpers::resolve));

Self(handlebars)
}
}

impl Default for TemplateEngine {
fn default() -> Self {
Self::new()
}
}

0 comments on commit 5c4eb84

Please sign in to comment.