From 6fb685e84c71a046b87d26efa8473901ece49718 Mon Sep 17 00:00:00 2001 From: the-dipsy Date: Mon, 4 Mar 2024 10:23:10 +0100 Subject: [PATCH] feat: add jinja env with toml finalization This will be used in the standard component library for loading and rendering templated toml files. --- pyromaniac/compiler/code/jinja.py | 32 +++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/pyromaniac/compiler/code/jinja.py b/pyromaniac/compiler/code/jinja.py index 52c1cc9..596cfab 100644 --- a/pyromaniac/compiler/code/jinja.py +++ b/pyromaniac/compiler/code/jinja.py @@ -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 @@ -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)