Created
September 28, 2016 16:03
-
-
Save lewismarshall/3c801782caf50942975d2d44b5370430 to your computer and use it in GitHub Desktop.
Minimal Python Template
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# Taken from: | |
# string as file: http://stackoverflow.com/a/142251 | |
# yaml !include: http://stackoverflow.com/a/9577670 | |
import sys | |
import os.path | |
import yaml | |
import jinja2 | |
import io | |
from os import path | |
class Loader(yaml.Loader): | |
def __init__(self, stream, fname=''): | |
if fname == '': | |
self._root = os.path.split(stream.name)[0] | |
else: | |
self._root = fname | |
super(Loader, self).__init__(stream) | |
def include(self, node): | |
filename = os.path.join(self._root, self.construct_scalar(node)) | |
extension = os.path.splitext(filename)[1].lstrip('.') | |
with open(filename, 'r') as f: | |
if extension in ('yaml', 'yml'): | |
return yaml.load(f, Loader) | |
else: | |
return ''.join(f.readlines()) | |
def _new_jinja_env(tpl_path): | |
loader = jinja2.loaders.FileSystemLoader(tpl_path) | |
env = jinja2.Environment(loader=loader) | |
return env | |
def main(argv): | |
tpl_file_path = argv[0] | |
tpl_path, tpl_fname = path.split(tpl_file_path) | |
# First load the data and resolve jinja2 from environment | |
env = _new_jinja_env(tpl_path) | |
tpl = env.get_template(tpl_fname) | |
data = tpl.render(env=os.environ) | |
with io.StringIO() as f: | |
f.write(data) | |
f.name = tpl_file_path | |
f.seek(0) | |
# Now load yaml data and parse includes | |
Loader.add_constructor('!include', Loader.include) | |
data = yaml.load(f, Loader) | |
# Now output to stdout | |
output = yaml.safe_dump(data, default_flow_style=False) | |
print(output) | |
if __name__ == "__main__": | |
main(sys.argv[1:]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment