@@ -1,5 +1,4 @@
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import tomllib
|
||||
from pathlib import Path
|
||||
@@ -9,6 +8,7 @@ import dotenv
|
||||
from jinja2 import Environment
|
||||
|
||||
from ..preset.model import Variables
|
||||
from .util import get_environ
|
||||
|
||||
|
||||
def do_bool(data: str | None) -> bool:
|
||||
@@ -19,10 +19,6 @@ def do_bool(data: str | None) -> bool:
|
||||
return data.lower() not in ["false", "null", "none", "0", ""]
|
||||
|
||||
|
||||
def do_env(key: str, default: str | None = None) -> str | None:
|
||||
return os.environ.get(key=key.upper(), default=default)
|
||||
|
||||
|
||||
def do_not(value: Any | None) -> bool:
|
||||
return not do_bool(str(value))
|
||||
|
||||
@@ -31,6 +27,8 @@ def _build_env(basepath: Path) -> Environment:
|
||||
env = Environment()
|
||||
|
||||
def do_file(filename: str) -> Path | None:
|
||||
if not filename:
|
||||
return None
|
||||
result = Path(filename)
|
||||
if not result.is_absolute():
|
||||
result = basepath / result
|
||||
@@ -73,6 +71,11 @@ def _build_env(basepath: Path) -> Environment:
|
||||
keys = list(data.keys())
|
||||
return keys[keyindex]
|
||||
|
||||
env_data = get_environ(basepath)
|
||||
|
||||
def do_env(key: str, default: str | None = None) -> str | None:
|
||||
return env_data.get(key.upper(), default)
|
||||
|
||||
env.filters["file"] = do_file
|
||||
env.filters["read"] = do_read
|
||||
env.filters["get"] = do_get
|
||||
@@ -91,7 +94,13 @@ class PathTemplate:
|
||||
|
||||
def update_variables(self, templates: Variables, variables: Variables):
|
||||
for k, v in templates.items():
|
||||
variables[k] = self._env.from_string(v).render(**variables)
|
||||
if isinstance(v, dict):
|
||||
variables[k] = {
|
||||
kk: self._env.from_string(vv).render(**variables)
|
||||
for kk, vv in v.items()
|
||||
}
|
||||
else:
|
||||
variables[k] = self._env.from_string(v).render(**variables)
|
||||
|
||||
def fill_template(self, template: str, variables: Variables) -> str:
|
||||
return self._env.from_string(template).render(**variables)
|
||||
|
||||
@@ -1,3 +1,9 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import dotenv
|
||||
|
||||
|
||||
def merge_dicts(target: dict, enhancer: dict) -> dict:
|
||||
for key, val in enhancer.items():
|
||||
if key not in target:
|
||||
@@ -9,3 +15,10 @@ def merge_dicts(target: dict, enhancer: dict) -> dict:
|
||||
else:
|
||||
target[key] = val
|
||||
return target
|
||||
|
||||
|
||||
def get_environ(path: Path) -> dict[str, str]:
|
||||
result = os.environ.copy()
|
||||
if (env_file := path / ".env").exists():
|
||||
result.update(dotenv.dotenv_values(env_file))
|
||||
return result
|
||||
|
||||
Reference in New Issue
Block a user