Skip to content

Commit

Permalink
feat: add build variables
Browse files Browse the repository at this point in the history
closes #92
  • Loading branch information
yuma140902 committed Dec 18, 2023
1 parent c9c80bc commit e373fbb
Show file tree
Hide file tree
Showing 3 changed files with 198 additions and 6 deletions.
161 changes: 161 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ keywords = ["ssg", "templating", "web", "markdown"]

[dependencies]
anyhow = "1.0.75"
chrono = "0.4.31"
clap = { version = "4.4.7", features = ["derive", "help"] }
handlebars = "4.5.0"
matter = "0.1.0-alpha4"
Expand Down
42 changes: 36 additions & 6 deletions src/transformer/template_renderer.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use anyhow::Context;
use chrono::{Datelike, Timelike};
use serde::{Deserialize, Serialize};
use tracing::warn;

Expand Down Expand Up @@ -71,19 +72,48 @@ impl Transformer for TemplateRenderer {
None
};

let value = transform_value_for_rendering(value)
.context("failed to transform value for rendering")?;
let value = add_build_variables(&value).context("failed to add build variables")?;

let result_string = engine
.render(
&self.template_key,
&current_directory,
&transform_value_for_rendering(value)
.context("failed to transform value for rendering")?,
)
.render(&self.template_key, &current_directory, &value)
.context("failed to render template")?;

Ok(Value::JSON(serde_json::Value::String(result_string)))
}
}

fn add_build_variables(value: &serde_json::Value) -> anyhow::Result<serde_json::Value> {
match value {
serde_json::Value::Null
| serde_json::Value::Bool(_)
| serde_json::Value::Number(_)
| serde_json::Value::String(_)
| serde_json::Value::Array(_) => {
anyhow::bail!("failed to add build variables because value is not JSON object")
}
serde_json::Value::Object(map) => {
let now = chrono::Local::now();
let mut build_variables = serde_json::Map::new();
build_variables.insert("datetime".to_string(), now.to_rfc3339().into());
build_variables.insert("year".to_string(), now.year().into());
build_variables.insert("month".to_string(), now.month().into());
build_variables.insert("day".to_string(), now.day().into());
build_variables.insert("hour".to_string(), now.hour().into());
build_variables.insert("minute".to_string(), now.minute().into());
build_variables.insert("second".to_string(), now.second().into());

let mut map = map.clone();
map.insert(
"build".to_string(),
serde_json::Value::Object(build_variables),
);
Ok(serde_json::Value::Object(map))
}
}
}

fn transform_value_for_rendering(value: &Value) -> anyhow::Result<serde_json::Value> {
match value {
Value::Bytes(bytes) => {
Expand Down

0 comments on commit e373fbb

Please sign in to comment.