ApplicantPortal/scripts/render_templates.py
2025-03-12 20:43:26 -06:00

55 lines
2.8 KiB
Python

#!/usr/bin/env python
import os
import argparse
import traceback
from jinja2 import Environment, FileSystemLoader
def render_template(template_file, out_path, **kwargs):
folder, file = os.path.split(template_file)
template_path = os.path.abspath(folder)
env = Environment(loader=FileSystemLoader(template_path), trim_blocks=True, lstrip_blocks=True)
template = env.get_template(file)
with open(out_path, 'w+') as save:
save.write(template.render(**kwargs))
if __name__ == '__main__':
docker_root_dir = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
def_template_path = os.path.join(docker_root_dir, 'templates')
parser = argparse.ArgumentParser(prog='render_templates.py', description='A script for rendering docker templates', add_help=True)
parser.add_argument('template_path', help='The path to the directory of template files or individual template file to render.')
parser.add_argument('output_path', help='The path to output the rendered template files to.')
parser.add_argument('-k', '--kwargs', required=False, type=str, default='', help='The kwargs to render the template for (format: "Key1=value1,Key2=value2...)')
parser.add_argument('-o', '--overwrite', action='store_true', help='If the existing template renders should be overwritten')
args = parser.parse_args()
args.kwargs = {a.split('=')[0]: a.split('=')[1] for a in args.kwargs.split(',')} if args.kwargs else {}
if os.path.isdir(args.template_path) and not os.path.exists(args.template_path):
print(f'The given path "{args.template_path}" does not exist...')
exit(1)
args.template_path = [os.path.join(args.template_path, p) for p in os.listdir(args.template_path) if p.endswith('.tmpl')] if os.path.isdir(args.template_path) else [args.template_path]
if not args.template_path:
print('No template (.tmpl) files found')
exit(1)
if os.path.isdir(args.output_path) and not os.path.exists(args.output_path):
os.makedirs(args.output_dir)
for tmpl_file in args.template_path:
out_file_name = os.path.split(tmpl_file)[1].replace('.tmpl', '')
out_path = os.path.join(args.output_path, out_file_name) if os.path.isdir(args.output_path) else args.output_path
print(f'Rendering template "{os.path.split(tmpl_file)[1]}" to "{out_path}" with kwargs: {args.kwargs}')
if os.path.exists(out_path) and not args.overwrite:
print(f'Skipping template file because it has already been rendered (use ---overwrite to overwrite the template file).')
continue
try:
render_template(tmpl_file, out_path, **args.kwargs)
print(f'Template rendered successfully')
except Exception as ex:
print(f'Failed to render template (error={str(ex)}).\n{traceback.format_exc()}')