Skip to content

Commit

Permalink
feat: add jinja env with toml finalization
Browse files Browse the repository at this point in the history
This will be used in the standard component library for loading
and rendering templated toml files.
  • Loading branch information
the-dipsy committed Mar 4, 2024
1 parent 5837c8f commit 6fb685e
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions pyromaniac/compiler/code/jinja.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from typing import Any
from datetime import date, datetime, time
from pathlib import PosixPath as Path
from json import dumps as json_dumps, JSONEncoder as JSONEncoderBase
from jinja2 import Environment
Expand Down Expand Up @@ -30,3 +31,34 @@ def json_finalize(obj: Any) -> str:

json_env = Environment(finalize=json_finalize)
json_env.filters['raw'] = lambda c: Raw(c)


def toml(obj: Any) -> str:
match obj:
case dict():
pairs = []
for key, value in obj.items():
if not isinstance(key, str):
raise ValueError(f"{repr(key)} is not a valid toml key")
pairs.append(f"{toml(key)} = {toml(value)}")
return "{ " + ", ".join(pairs) + " }"
case list():
return "[ " + ", ".join(toml(v) for v in obj) + " ]"
case date() | datetime() | time():
return obj.isoformat()
case str() | int() | float() | bool():
return json_dumps(obj)
case Path() | URL():
return toml(str(obj))
case _:
raise ValueError(f"{repr(obj)} is not toml serializable")


def toml_finalize(obj: Any) -> str:
match obj:
case Raw(content): return str(content)
case _: return toml(obj)


toml_env = Environment(finalize=toml_finalize)
toml_env.filters['raw'] = lambda c: Raw(c)

0 comments on commit 6fb685e

Please sign in to comment.