Skip to content
This repository has been archived by the owner on Dec 17, 2024. It is now read-only.

Commit

Permalink
feat: Implement load_base64 function
Browse files Browse the repository at this point in the history
  • Loading branch information
codablock committed Jun 18, 2024
1 parent f1b2e42 commit daf18f4
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
23 changes: 23 additions & 0 deletions python_src/go_jinja2/ext/kluctl_ext.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
import hashlib
import json
import os
import textwrap

import sys

import jinja2
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down
6 changes: 5 additions & 1 deletion python_src/go_jinja2/jinja2_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"""
Expand All @@ -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)
Expand Down

0 comments on commit daf18f4

Please sign in to comment.