use std::{
collections::{BTreeMap, HashSet},
sync::LazyLock,
};
use heck::{
ToKebabCase, ToLowerCamelCase, ToShoutySnakeCase, ToSnakeCase, ToTitleCase, ToUpperCamelCase,
};
use minijinja::{Environment, Error, ErrorKind, State, Value};
use serde::{Serialize, de::DeserializeOwned};
pub type RenderError = Error;
pub fn environment() -> Environment<'static> {
let mut env = Environment::new();
env.set_keep_trailing_newline(true);
env.set_auto_escape_callback(|_| minijinja::AutoEscape::None);
env.set_formatter(|out, state, value| {
minijinja::escape_formatter(
out,
state,
if value.is_none() {
&Value::UNDEFINED
} else {
value
},
)
});
env.add_filter("kebab", |s: String| s.to_kebab_case());
env.add_filter("snake", |s: String| s.to_snake_case());
env.add_filter("camel", |s: String| s.to_lower_camel_case());
env.add_filter("pascal", |s: String| s.to_upper_camel_case());
env.add_filter("constant", |s: String| s.to_shouty_snake_case());
env.add_filter("title", |s: String| s.to_title_case());
env.add_filter("toyaml", toyaml);
env.add_function("now", |state: &State| {
state.lookup("__toha_now").unwrap_or(Value::UNDEFINED)
});
env.add_filter(
"dateformat",
|value: String, pattern: Option<String>| -> Result<String, Error> {
let zoned: jiff::Zoned = value.parse().map_err(|err: jiff::Error| {
Error::new(ErrorKind::InvalidOperation, err.to_string())
})?;
Ok(zoned
.strftime(pattern.as_deref().unwrap_or("%Y-%m-%d"))
.to_string())
},
);
env
}
fn toyaml(value: &Value) -> Result<Value, Error> {
let yaml = serde_norway::to_string(value).map_err(|err| {
Error::new(ErrorKind::InvalidOperation, "cannot serialize to YAML").with_source(err)
})?;
let body = yaml.strip_prefix("---\n").unwrap_or(&yaml);
let parse = |text: &str| serde_norway::from_str::<serde_json::Value>(text).ok();
let body = match body.strip_suffix('\n') {
Some(stripped) if parse(stripped).is_some_and(|v| Some(v) == parse(body)) => stripped,
_ => body,
};
Ok(Value::from_safe_string(body.to_owned()))
}
static GLOBALS: LazyLock<HashSet<String>> = LazyLock::new(|| {
environment()
.globals()
.map(|(name, _)| name.to_owned())
.collect()
});
pub fn is_global(name: &str) -> bool {
GLOBALS.contains(name)
}
pub struct Tmpl {
source: String,
env: Environment<'static>,
referenced_ids: HashSet<String>,
}
impl std::fmt::Debug for Tmpl {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Tmpl")
.field("source", &self.source)
.finish()
}
}
impl Tmpl {
pub fn compile(source: String) -> Result<Self, Error> {
let mut env = environment();
env.add_template_owned("value", source.clone())?;
reject_loaderless_statements(&source)?;
let referenced_ids = env.get_template("value")?.undeclared_variables(false);
Ok(Self {
source,
env,
referenced_ids,
})
}
pub fn references(&self) -> &HashSet<String> {
&self.referenced_ids
}
pub(crate) fn nested_references(&self) -> HashSet<String> {
self.env
.get_template("value")
.expect("compiled template")
.undeclared_variables(true)
}
pub fn source(&self) -> &str {
&self.source
}
pub fn render<S: Serialize>(&self, ctx: S) -> Result<String, RenderError> {
self.env.get_template("value")?.render(ctx)
}
}
pub struct Expr {
source: String,
referenced_ids: HashSet<String>,
}
impl std::fmt::Debug for Expr {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Expr")
.field("source", &self.source)
.finish()
}
}
impl Expr {
pub fn compile(source: String) -> Result<Self, Error> {
let env = environment();
let referenced_ids = env.compile_expression(&source)?.undeclared_variables(false);
Ok(Self {
source,
referenced_ids,
})
}
pub fn references(&self) -> &HashSet<String> {
&self.referenced_ids
}
pub(crate) fn nested_references(&self) -> HashSet<String> {
environment()
.compile_expression(&self.source)
.expect("compiled expression")
.undeclared_variables(true)
}
pub fn source(&self) -> &str {
&self.source
}
pub fn eval<S: Serialize>(&self, ctx: S) -> Result<Value, Error> {
environment().compile_expression(&self.source)?.eval(ctx)
}
}
#[derive(Debug)]
pub enum Typed<T> {
Literal(T),
Expr(Expr),
}
impl<T: Clone + DeserializeOwned> Typed<T> {
pub fn eval<S: Serialize>(&self, ctx: S) -> Result<T, Error> {
match self {
Self::Literal(value) => Ok(value.clone()),
Self::Expr(expr) => {
let value = expr.eval(ctx)?;
serde_json::from_value(
serde_json::to_value(value)
.map_err(|err| Error::new(ErrorKind::InvalidOperation, err.to_string()))?,
)
.map_err(|err| {
Error::new(
ErrorKind::InvalidOperation,
format!("typed expression: {err}"),
)
})
}
}
}
pub fn source(&self) -> Option<&str> {
match self {
Self::Literal(_) => None,
Self::Expr(expr) => Some(expr.source()),
}
}
pub fn literal(&self) -> Option<&T> {
match self {
Self::Literal(value) => Some(value),
Self::Expr(_) => None,
}
}
pub fn references(&self) -> HashSet<String> {
match self {
Self::Literal(_) => HashSet::new(),
Self::Expr(expr) => expr.references().clone(),
}
}
}
pub(crate) fn is_reserved(name: &str) -> bool {
crate::context::RESERVED_NAMES.contains(&name)
}
pub(crate) fn template_needs_environment(source: &str) -> bool {
match minijinja::machinery::parse(source, "<analysis>", Default::default(), Default::default())
{
Ok(stmt) => {
let mut walk = NeedWalk::new();
walk.stmt(&stmt);
walk.needed
}
Err(_) => true,
}
}
pub(crate) fn expr_needs_environment(source: &str) -> bool {
match minijinja::machinery::parse_expr(source) {
Ok(expr) => {
let mut walk = NeedWalk::new();
walk.expr(&expr);
walk.needed
}
Err(_) => true,
}
}
impl Tmpl {
pub(crate) fn needs_environment(&self) -> bool {
template_needs_environment(&self.source)
}
}
impl Expr {
pub(crate) fn needs_environment(&self) -> bool {
expr_needs_environment(&self.source)
}
}
impl<T: Clone + DeserializeOwned> Typed<T> {
pub(crate) fn needs_environment(&self) -> bool {
match self {
Self::Literal(_) => false,
Self::Expr(expr) => expr.needs_environment(),
}
}
}
struct NeedWalk {
needed: bool,
scopes: Vec<std::collections::HashSet<String>>,
}
impl NeedWalk {
fn new() -> Self {
Self {
needed: false,
scopes: vec![std::collections::HashSet::new()],
}
}
fn push(&mut self) {
self.scopes.push(std::collections::HashSet::new());
}
fn pop(&mut self) {
self.scopes.pop();
}
fn bind(&mut self, name: &str) {
if let Some(top) = self.scopes.last_mut() {
top.insert(name.to_owned());
}
}
fn bound(&self, name: &str) -> bool {
self.scopes.iter().any(|frame| frame.contains(name))
}
fn bind_target(&mut self, target: &minijinja::machinery::ast::Expr) {
use minijinja::machinery::ast::Expr;
match target {
Expr::Var(var) => self.bind(var.id),
Expr::List(list) => {
for item in &list.items {
self.bind_target(item);
}
}
other => self.expr(other),
}
}
fn block(&mut self, stmts: &[minijinja::machinery::ast::Stmt]) {
for stmt in stmts {
self.stmt(stmt);
}
}
fn macro_decl(&mut self, decl: &minijinja::machinery::ast::Macro) {
for default in &decl.defaults {
self.expr(default);
}
self.push();
for arg in &decl.args {
self.bind_target(arg);
}
self.bind(decl.name);
self.block(&decl.body);
self.pop();
self.bind(decl.name);
}
fn call(&mut self, call: &minijinja::machinery::ast::Call) {
self.expr(&call.expr);
for arg in &call.args {
self.call_arg(arg);
}
}
fn call_arg(&mut self, arg: &minijinja::machinery::ast::CallArg) {
use minijinja::machinery::ast::CallArg;
match arg {
CallArg::Pos(e) | CallArg::PosSplat(e) | CallArg::KwargSplat(e) => self.expr(e),
CallArg::Kwarg(_, e) => self.expr(e),
}
}
fn stmt(&mut self, stmt: &minijinja::machinery::ast::Stmt) {
use minijinja::machinery::ast::Stmt;
if self.needed {
return;
}
match stmt {
Stmt::Template(t) => self.block(&t.children),
Stmt::EmitExpr(e) => self.expr(&e.expr),
Stmt::EmitRaw(_) => {}
Stmt::ForLoop(f) => {
self.expr(&f.iter);
self.push();
self.bind_target(&f.target);
self.bind("loop");
if let Some(filter) = &f.filter_expr {
self.expr(filter);
}
self.block(&f.body);
self.pop();
self.block(&f.else_body);
}
Stmt::IfCond(c) => {
self.expr(&c.expr);
self.push();
self.block(&c.true_body);
self.pop();
self.push();
self.block(&c.false_body);
self.pop();
}
Stmt::WithBlock(w) => {
for (_, value) in &w.assignments {
self.expr(value);
}
self.push();
for (target, _) in &w.assignments {
self.bind_target(target);
}
self.block(&w.body);
self.pop();
}
Stmt::Set(s) => {
self.expr(&s.expr);
self.bind_target(&s.target);
}
Stmt::SetBlock(s) => {
if let Some(filter) = &s.filter {
self.expr(filter);
}
self.push();
self.block(&s.body);
self.pop();
self.bind_target(&s.target);
}
Stmt::AutoEscape(a) => {
self.expr(&a.enabled);
self.push();
self.block(&a.body);
self.pop();
}
Stmt::FilterBlock(fb) => {
self.expr(&fb.filter);
self.push();
self.block(&fb.body);
self.pop();
}
Stmt::Macro(m) => self.macro_decl(m),
Stmt::CallBlock(cb) => {
self.call(&cb.call);
self.macro_decl(&cb.macro_decl);
}
Stmt::Continue(_) | Stmt::Break(_) => {}
Stmt::Do(d) => self.call(&d.call),
Stmt::Include(i) => self.expr(&i.name),
Stmt::Block(b) => self.block(&b.body),
Stmt::Import(i) => {
self.expr(&i.expr);
self.bind_target(&i.name);
}
Stmt::FromImport(f) => {
self.expr(&f.expr);
for (name, alias) in &f.names {
self.bind_target(alias.as_ref().unwrap_or(name));
}
}
Stmt::Extends(e) => self.expr(&e.name),
}
}
fn expr(&mut self, expr: &minijinja::machinery::ast::Expr) {
use minijinja::machinery::ast::Expr;
if self.needed {
return;
}
match expr {
Expr::Var(var) => {
let id = var.id;
let sensitive = crate::context::ENVIRONMENT_NAMES.contains(&id) || id == "debug";
if sensitive && !self.bound(id) {
self.needed = true;
}
}
Expr::Const(_) => {}
Expr::Slice(s) => {
self.expr(&s.expr);
for inner in [&s.start, &s.stop, &s.step].into_iter().flatten() {
self.expr(inner);
}
}
Expr::UnaryOp(u) => self.expr(&u.expr),
Expr::BinOp(b) => {
self.expr(&b.left);
self.expr(&b.right);
}
Expr::Compare(c) => {
self.expr(&c.expr);
for op in &c.ops {
self.expr(&op.expr);
}
}
Expr::IfExpr(i) => {
self.expr(&i.test_expr);
self.expr(&i.true_expr);
if let Some(f) = &i.false_expr {
self.expr(f);
}
}
Expr::Filter(f) => {
if let Some(inner) = &f.expr {
self.expr(inner);
}
for arg in &f.args {
self.call_arg(arg);
}
}
Expr::Test(t) => {
self.expr(&t.expr);
for arg in &t.args {
self.call_arg(arg);
}
}
Expr::GetAttr(g) => self.expr(&g.expr),
Expr::GetItem(g) => {
self.expr(&g.expr);
self.expr(&g.subscript_expr);
}
Expr::Call(c) => self.call(c),
Expr::List(l) => {
for item in &l.items {
self.expr(item);
}
}
Expr::Map(m) => {
for key in &m.keys {
self.expr(key);
}
for value in &m.values {
self.expr(value);
}
}
}
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Surface {
Loaderless,
FileBody,
}
struct IncludeSpec {
candidates: Vec<String>,
ignore_missing: bool,
}
enum StatementReject {
Unsupported(&'static str),
DynamicTarget,
}
enum Analysis {
Ok(Vec<IncludeSpec>),
Reject(StatementReject),
}
struct StmtWalk {
surface: Surface,
includes: Vec<IncludeSpec>,
reject: Option<StatementReject>,
}
impl StmtWalk {
fn analyze(source: &str, surface: Surface) -> Result<Analysis, Error> {
let stmt =
minijinja::machinery::parse(source, "value", Default::default(), Default::default())?;
let mut walk = StmtWalk {
surface,
includes: Vec::new(),
reject: None,
};
walk.stmt(&stmt);
Ok(match walk.reject {
Some(reject) => Analysis::Reject(reject),
None => Analysis::Ok(walk.includes),
})
}
fn block(&mut self, stmts: &[minijinja::machinery::ast::Stmt]) {
for stmt in stmts {
if self.reject.is_some() {
return;
}
self.stmt(stmt);
}
}
fn refuse(&mut self, statement: &'static str) {
if self.reject.is_none() {
self.reject = Some(StatementReject::Unsupported(statement));
}
}
fn include(&mut self, inc: &minijinja::machinery::ast::Include) {
if self.surface == Surface::Loaderless {
self.refuse("include");
return;
}
match literal_candidates(&inc.name) {
Some(candidates) => self.includes.push(IncludeSpec {
candidates,
ignore_missing: inc.ignore_missing,
}),
None => {
if self.reject.is_none() {
self.reject = Some(StatementReject::DynamicTarget);
}
}
}
}
fn stmt(&mut self, stmt: &minijinja::machinery::ast::Stmt) {
use minijinja::machinery::ast::Stmt;
if self.reject.is_some() {
return;
}
match stmt {
Stmt::Template(t) => self.block(&t.children),
Stmt::EmitExpr(_) | Stmt::EmitRaw(_) => {}
Stmt::ForLoop(f) => {
self.block(&f.body);
self.block(&f.else_body);
}
Stmt::IfCond(c) => {
self.block(&c.true_body);
self.block(&c.false_body);
}
Stmt::WithBlock(w) => self.block(&w.body),
Stmt::Set(_) => {}
Stmt::SetBlock(s) => self.block(&s.body),
Stmt::AutoEscape(a) => self.block(&a.body),
Stmt::FilterBlock(fb) => self.block(&fb.body),
Stmt::Macro(m) => self.block(&m.body),
Stmt::CallBlock(cb) => self.block(&cb.macro_decl.body),
Stmt::Continue(_) | Stmt::Break(_) | Stmt::Do(_) => {}
Stmt::Include(i) => self.include(i),
Stmt::Block(_) => self.refuse("block"),
Stmt::Import(_) => self.refuse("import"),
Stmt::FromImport(_) => self.refuse("from import"),
Stmt::Extends(_) => self.refuse("extends"),
}
}
}
fn literal_candidates(expr: &minijinja::machinery::ast::Expr) -> Option<Vec<String>> {
use minijinja::machinery::ast::Expr;
fn constant(expr: &Expr) -> Option<String> {
match expr {
Expr::Const(c) => c.value.as_str().map(str::to_owned),
_ => None,
}
}
match expr {
Expr::Const(_) => constant(expr).map(|s| vec![s]),
Expr::List(list) => list.items.iter().map(constant).collect(),
_ => None,
}
}
fn reject_loaderless_statements(source: &str) -> Result<(), Error> {
match StmtWalk::analyze(source, Surface::Loaderless)? {
Analysis::Ok(_) => Ok(()),
Analysis::Reject(StatementReject::Unsupported(statement)) => Err(Error::new(
ErrorKind::SyntaxError,
format!("jinja {statement} is unavailable outside file bodies"),
)),
Analysis::Reject(StatementReject::DynamicTarget) => Err(Error::new(
ErrorKind::SyntaxError,
"jinja include is unavailable outside file bodies".to_owned(),
)),
}
}
#[derive(Debug)]
pub enum IncludeError {
Template(Error),
NotFound { candidates: Vec<String>, by: String },
Escape { name: String, by: String },
Symlink { name: String, by: String },
NotUtf8 { name: String, by: String },
Unreadable {
name: String,
by: String,
source: std::io::Error,
},
Cycle { path: String },
Dynamic { by: String },
UnsupportedStatement {
statement: &'static str,
surface: &'static str,
by: String,
},
}
impl std::fmt::Display for IncludeError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Template(e) => write!(f, "{e}"),
Self::NotFound { candidates, by } if candidates.len() == 1 => {
write!(
f,
"jinja include not found: {}, included by {by}",
candidates[0]
)
}
Self::NotFound { candidates, by } => write!(
f,
"jinja include candidates not found: {}, included by {by}",
candidates.join(", ")
),
Self::Escape { name, by } => {
write!(
f,
"jinja include escapes template root: {name}, included by {by}"
)
}
Self::Symlink { name, by } => {
write!(
f,
"jinja include path is a symlink: {name}, included by {by}"
)
}
Self::NotUtf8 { name, by } => {
write!(f, "jinja include is not utf-8: {name}, included by {by}")
}
Self::Unreadable { name, by, source } => write!(
f,
"jinja include is not readable: {name}, included by {by}: {source}"
),
Self::Cycle { path } => write!(f, "jinja include cycle: {path}"),
Self::Dynamic { by } => write!(
f,
"jinja include target must be a literal string or literal list of strings, in {by}"
),
Self::UnsupportedStatement {
statement,
surface,
by,
} => write!(
f,
"jinja {statement} is unavailable {surface}, found in {by}"
),
}
}
}
impl std::error::Error for IncludeError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Template(e) => Some(e),
Self::Unreadable { source, .. } => Some(source),
_ => None,
}
}
}
#[derive(Clone, Debug)]
pub struct Partials {
root: std::sync::Arc<std::path::PathBuf>,
}
impl Partials {
pub fn rooted(root: &std::path::Path) -> Self {
Self {
root: std::sync::Arc::new(root.to_path_buf()),
}
}
pub fn compile(&self, source: String, label: &str) -> Result<FileTmpl, IncludeError> {
let mut members = BTreeMap::new();
let body_canonical = self
.root
.join(label)
.canonicalize()
.unwrap_or_else(|_| self.root.join(label));
let mut stack = vec![(label.to_owned(), body_canonical)];
self.collect(&source, label, &mut members, &mut stack)?;
FileTmpl::build(source, label, members)
}
fn collect(
&self,
src: &str,
by: &str,
members: &mut BTreeMap<String, String>,
stack: &mut Vec<(String, std::path::PathBuf)>,
) -> Result<(), IncludeError> {
let specs =
match StmtWalk::analyze(src, Surface::FileBody).map_err(IncludeError::Template)? {
Analysis::Ok(specs) => specs,
Analysis::Reject(StatementReject::Unsupported(statement)) => {
return Err(IncludeError::UnsupportedStatement {
statement,
surface: "in file bodies",
by: by.to_owned(),
});
}
Analysis::Reject(StatementReject::DynamicTarget) => {
return Err(IncludeError::Dynamic { by: by.to_owned() });
}
};
for spec in specs {
if spec.candidates.is_empty() {
continue;
}
let mut selected = None;
for candidate in &spec.candidates {
if let Some((canonical, text)) = self.locate(candidate, by)? {
selected = Some((candidate.clone(), canonical, text));
break;
}
}
let Some((name, canonical, text)) = selected else {
if spec.ignore_missing {
continue;
}
return Err(IncludeError::NotFound {
candidates: spec.candidates,
by: by.to_owned(),
});
};
if stack.iter().any(|(_, path)| path == &canonical) {
let mut cycle: Vec<String> = stack.iter().map(|(n, _)| n.clone()).collect();
cycle.push(name);
return Err(IncludeError::Cycle {
path: cycle.join(" -> "),
});
}
if members.contains_key(&name) {
continue;
}
members.insert(name.clone(), text.clone());
stack.push((name.clone(), canonical));
self.collect(&text, &name, members, stack)?;
stack.pop();
}
Ok(())
}
fn locate(
&self,
name: &str,
by: &str,
) -> Result<Option<(std::path::PathBuf, String)>, IncludeError> {
use std::path::Component;
let escape = || IncludeError::Escape {
name: name.to_owned(),
by: by.to_owned(),
};
if name.contains('\\') {
return Err(escape());
}
let relative = std::path::Path::new(name);
if relative.is_absolute() {
return Err(escape());
}
let mut current = self.root.to_path_buf();
for component in relative.components() {
match component {
Component::Normal(part) => {
current.push(part);
match std::fs::symlink_metadata(¤t) {
Ok(meta) if meta.file_type().is_symlink() => {
return Err(IncludeError::Symlink {
name: name.to_owned(),
by: by.to_owned(),
});
}
Ok(_) => {}
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
return Ok(None);
}
Err(source) => {
return Err(IncludeError::Unreadable {
name: name.to_owned(),
by: by.to_owned(),
source,
});
}
}
}
Component::CurDir => {}
_ => return Err(escape()),
}
}
let canonical = match current.canonicalize() {
Ok(path) => path,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(source) => {
return Err(IncludeError::Unreadable {
name: name.to_owned(),
by: by.to_owned(),
source,
});
}
};
if !canonical.starts_with(self.root.as_path()) {
return Err(escape());
}
if !canonical.is_file() {
return Ok(None);
}
match std::fs::read(&canonical) {
Ok(bytes) => match String::from_utf8(bytes) {
Ok(text) => Ok(Some((canonical, text))),
Err(_) => Err(IncludeError::NotUtf8 {
name: name.to_owned(),
by: by.to_owned(),
}),
},
Err(source) => Err(IncludeError::Unreadable {
name: name.to_owned(),
by: by.to_owned(),
source,
}),
}
}
}
pub struct FileTmpl {
label: String,
source: String,
env: Environment<'static>,
referenced_ids: HashSet<String>,
needs_env: bool,
}
impl std::fmt::Debug for FileTmpl {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("FileTmpl")
.field("source", &self.source)
.finish()
}
}
impl FileTmpl {
fn build(
source: String,
label: &str,
members: BTreeMap<String, String>,
) -> Result<Self, IncludeError> {
let mut env = environment();
for (name, text) in &members {
env.add_template_owned(name.clone(), text.clone())
.map_err(IncludeError::Template)?;
}
env.add_template_owned(label.to_owned(), source.clone())
.map_err(IncludeError::Template)?;
let mut referenced_ids = HashSet::new();
referenced_ids.extend(
env.get_template(label)
.map_err(IncludeError::Template)?
.undeclared_variables(false),
);
for name in members.keys() {
referenced_ids.extend(
env.get_template(name)
.map_err(IncludeError::Template)?
.undeclared_variables(false),
);
}
let needs_env = template_needs_environment(&source)
|| members
.values()
.any(|text| template_needs_environment(text));
Ok(Self {
label: label.to_owned(),
source,
env,
referenced_ids,
needs_env,
})
}
pub fn source(&self) -> &str {
&self.source
}
pub fn references(&self) -> &HashSet<String> {
&self.referenced_ids
}
pub fn render<S: Serialize>(&self, ctx: S) -> Result<String, RenderError> {
self.env.get_template(&self.label)?.render(ctx)
}
pub(crate) fn needs_environment(&self) -> bool {
self.needs_env
}
}
pub fn context_from_answers(
answers: &crate::interview::Answers,
data: &indexmap::IndexMap<crate::template::Id, serde_json::Value>,
now: &jiff::Zoned,
) -> BTreeMap<String, serde_json::Value> {
let mut values: BTreeMap<String, serde_json::Value> = data
.iter()
.map(|(id, value)| (id.as_str().to_owned(), value.clone()))
.collect();
for (id, answer) in answers {
values.insert(id.as_str().to_owned(), answer.to_json());
}
values.insert(
"__toha_now".into(),
serde_json::Value::String(now.to_string()),
);
values
}
#[cfg(test)]
mod tests {
use super::Tmpl;
use serde_json::json;
fn render(source: &str, ctx: serde_json::Value) -> String {
Tmpl::compile(source.into())
.unwrap_or_else(|err| panic!("compile {source:?}: {err}"))
.render(ctx)
.unwrap_or_else(|err| panic!("render {source:?}: {err}"))
}
#[test]
fn tojson_serializes_values() {
let ctx = json!({
"flag": true,
"text": "say \"hi\"",
"item": {"b": [1, 2], "a": "x"},
});
assert_eq!(render("{{ flag | tojson }}", ctx.clone()), "true");
assert_eq!(
render("{{ text | tojson }}", ctx.clone()),
r#""say \"hi\"""#
);
assert_eq!(render("{{ item | tojson }}", ctx), r#"{"a":"x","b":[1,2]}"#);
}
#[test]
fn toyaml_serializes_nested_object() {
let ctx = json!({
"item": {
"name": "demo",
"enabled": true,
"ports": [80, 443],
"inner": {"key": "value"},
},
});
assert_eq!(
render("{{ item | toyaml }}", ctx.clone()),
"enabled: true\ninner:\n key: value\nname: demo\nports:\n- 80\n- 443"
);
assert_eq!(
render("root:\n {{ item.inner | toyaml | indent(2) }}\n", ctx),
"root:\n key: value\n"
);
}
#[test]
fn toyaml_round_trips_values() {
let failures = [
json!("hello\n"),
json!("\n"),
json!({"inner": {"k": "v\n"}}),
json!(["a", "b\n"]),
json!({"a": 2, "b": [1, true, null], "c": "x"}),
json!("true"),
json!({}),
json!(null),
]
.into_iter()
.filter_map(|value| {
let yaml = render("{{ value | toyaml }}", json!({ "value": value }));
let parsed: serde_json::Value =
serde_norway::from_str(&yaml).unwrap_or_else(|err| panic!("parse {yaml:?}: {err}"));
(parsed != value).then(|| format!("{value} -> {yaml:?} -> {parsed}"))
})
.collect::<Vec<_>>();
assert!(failures.is_empty(), "{failures:#?}");
}
#[test]
fn macro_is_defined_and_called_in_one_template() {
assert_eq!(
render(
"{% macro greet(who) %}hello {{ who }}{% endmacro %}{{ greet(name) }}",
json!({"name": "world"}),
),
"hello world"
);
}
#[test]
fn analyzer_detects_direct_and_shadowed_environment_reads() {
use super::{expr_needs_environment as expr, template_needs_environment as tmpl};
assert!(tmpl("{{ toha_env_editor }}"));
assert!(!tmpl("{{ project_name }}"));
assert!(!tmpl("{{ toha_target_name }} {{ toha_host_os }}"));
assert!(tmpl(
"{% set toha_env_editor = toha_env_editor %}{{ toha_env_editor }}"
));
assert!(!tmpl(
"{% set toha_env_editor = \"code\" %}{{ toha_env_editor }}"
));
assert!(tmpl("{% set chosen = toha_env_shell %}{{ chosen }}"));
assert!(tmpl("{{ debug() }}"));
assert!(tmpl("{% set d = debug %}{{ d() }}"));
assert!(tmpl("{{ config[toha_env_user] }}"));
assert!(!tmpl("{{ config[\"toha_env_user\"] }}"));
assert!(!tmpl("{{ config.toha_env_user }}"));
assert!(tmpl(
"{% if flag %}a{% else %}{{ toha_env_visual }}{% endif %}"
));
assert!(tmpl(
"{% macro unused() %}{{ toha_env_shell }}{% endmacro %}"
));
assert!(tmpl(
"{% if flag %}{% set toha_env_editor = 1 %}{% endif %}{{ toha_env_editor }}"
));
assert!(!tmpl(
"{% macro m(toha_env_editor) %}{{ toha_env_editor }}{% endmacro %}"
));
assert!(expr("toha_env_user"));
assert!(!expr("answer + 1"));
assert!(expr("config[toha_env_user]"));
assert!(!expr("config[\"toha_env_user\"]"));
}
#[test]
fn loaderless_field_rejects_every_multi_template_statement() {
for (source, statement) in [
("{% include \"x\" %}", "include"),
("{% block x %}y{% endblock %}", "block"),
("{% import \"x\" as m %}", "import"),
("{% from \"x\" import y %}", "from import"),
("{% extends \"x\" %}", "extends"),
] {
let error = Tmpl::compile(source.into()).unwrap_err().to_string();
assert!(
error.contains(&format!(
"jinja {statement} is unavailable outside file bodies"
)),
"{source}: {error}"
);
}
}
#[test]
fn file_body_rejects_a_sibling_statement_nested_in_an_unreachable_branch() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().canonicalize().unwrap();
let partials = super::Partials::rooted(&root);
let error = partials
.compile(
"{% if false %}{% block x %}y{% endblock %}{% endif %}".into(),
"body.txt",
)
.unwrap_err()
.to_string();
assert!(
error.contains("jinja block is unavailable in file bodies"),
"{error}"
);
}
#[test]
fn file_body_admits_only_include_from_the_multi_template_grammar() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("frag.txt"), "fragment").unwrap();
let root = dir.path().canonicalize().unwrap();
let partials = super::Partials::rooted(&root);
let body = partials
.compile("before {% include \"frag.txt\" %} after".into(), "body.txt")
.unwrap();
assert_eq!(
body.render(serde_json::json!({})).unwrap(),
"before fragment after"
);
}
#[test]
fn jinja_include_diagnostics_are_distinct_from_yaml_include_wording() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().canonicalize().unwrap();
let partials = super::Partials::rooted(&root);
let error = partials
.compile("{% include \"missing.txt\" %}".into(), "body.txt")
.unwrap_err()
.to_string();
assert!(error.starts_with("jinja include not found"), "{error}");
assert_ne!(error, "include file not found: missing.txt");
}
#[test]
fn loop_break_stops_iteration() {
assert_eq!(
render(
"{% for n in items %}{% if n > 2 %}{% break %}{% endif %}{{ n }}{% endfor %}",
json!({"items": [1, 2, 3, 4]}),
),
"12"
);
}
}