Skip to content

Commit

Permalink
feat: Add jinja2 templating
Browse files Browse the repository at this point in the history
  • Loading branch information
matt2930 committed Sep 19, 2022
1 parent 50f7f9a commit df66231
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 2 deletions.
5 changes: 3 additions & 2 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@
from tmpl8 import __version__

install_requires = [
'pyyaml'
]
'pyyaml',
'jinja2'
]

setup_options = dict(
name='tmpl8',
Expand Down
9 changes: 9 additions & 0 deletions tmpl8/cli.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import argparse
from tempfile import TemporaryDirectory

from tmpl8 import __version__
from tmpl8.extractor import CommandExtractor
from tmpl8.template import templateFile

def main():
parser = argparse.ArgumentParser(prog='tmpl8', description="tmpl8 wrapper for cli commands")
Expand All @@ -17,3 +19,10 @@ def main():
command = CommandExtractor(args.command)

print(command.arg_info)

with TemporaryDirectory() as td:
for arg, info in command.arg_info.items():
for file in info['files']:
out_file = templateFile(file, td, {})
if out_file:
print(out_file)
27 changes: 27 additions & 0 deletions tmpl8/template.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import os
from typing import Optional

from jinja2 import Environment, FileSystemLoader, TemplateNotFound

def templateFile(input_path: str, output_path: str, data={}) -> Optional[str]:

full_input_path = os.path.realpath(os.path.expanduser(input_path))
input_file_dir = os.path.dirname(full_input_path)
input_file_name = os.path.basename(full_input_path)
environment = Environment(loader=FileSystemLoader(input_file_dir))
try:
template = environment.get_template(input_file_name)
except TemplateNotFound:
return

content = template.render(**data)

full_output_path = os.path.realpath(os.path.expanduser(output_path))

if os.path.isdir(full_output_path):
full_output_path = f'{full_output_path}/{input_file_name}'

with open(full_output_path, 'w', encoding='utf-8') as f:
f.write(content)

return full_output_path

0 comments on commit df66231

Please # to comment.