From daf18f497cf34775e7736b3b9389f6c82e8f497d Mon Sep 17 00:00:00 2001 From: Alexander Block Date: Tue, 18 Jun 2024 23:41:36 +0200 Subject: [PATCH] feat: Implement load_base64 function --- python_src/go_jinja2/ext/kluctl_ext.py | 23 +++++++++++++++++++++++ python_src/go_jinja2/jinja2_utils.py | 6 +++++- 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/python_src/go_jinja2/ext/kluctl_ext.py b/python_src/go_jinja2/ext/kluctl_ext.py index 1efb3bb..6758d6b 100644 --- a/python_src/go_jinja2/ext/kluctl_ext.py +++ b/python_src/go_jinja2/ext/kluctl_ext.py @@ -2,6 +2,8 @@ import hashlib import json import os +import textwrap + import sys import jinja2 @@ -68,6 +70,26 @@ def load_template(ctx, path, **kwargs): return t.render(vars) +@jinja2.pass_context +def load_base64(ctx, path, width=None): + ctx.environment.print_debug("load_base64(%s)" % path) + path = path.replace(os.path.sep, '/') + if ctx.name: + path = ctx.environment.join_path(path, ctx.name) + + ctx.environment.binary_read = True + try: + contents, _, _ = ctx.environment.loader.get_source(ctx.environment, path) + finally: + ctx.environment.binary_read = False + + b = base64.b64encode(contents).decode() + if width: + b = textwrap.fill(b, width=width) + + return b + + class VarNotFoundException(Exception): pass @@ -123,6 +145,7 @@ def add_jinja2_filters(jinja2_env): jinja2_env.filters['sha256'] = sha256 jinja2_env.filters['slugify'] = slugify jinja2_env.globals['load_template'] = load_template + jinja2_env.globals['load_base64'] = load_base64 jinja2_env.globals['get_var'] = get_var jinja2_env.globals['merge_dict'] = merge_dict jinja2_env.globals['update_dict'] = update_dict diff --git a/python_src/go_jinja2/jinja2_utils.py b/python_src/go_jinja2/jinja2_utils.py index 2470cc7..7985a4d 100644 --- a/python_src/go_jinja2/jinja2_utils.py +++ b/python_src/go_jinja2/jinja2_utils.py @@ -13,6 +13,7 @@ class MyEnvironment(Environment): def __init__(self, debug_enabled, *args, **kwargs): super().__init__(*args, **kwargs) self.debug_enabled = debug_enabled + self.binary_read = False """Override join_path() to enable relative template paths.""" """See https://stackoverflow.com/a/3655911/7132642""" @@ -37,7 +38,10 @@ def print_debug(self, s): def read_template_helper(self, template): self.print_debug("_read_template_helper %s" % template) try: - with open(template) as f: + mode = "r" + if self.binary_read: + mode += "b" + with open(template, mode) as f: contents = f.read() except OSError: raise TemplateNotFound(template)