1
# Copyright 2016 Canonical Limited.
3
# This file is part of charm-helpers.
5
# charm-helpers is free software: you can redistribute it and/or modify
6
# it under the terms of the GNU Lesser General Public License version 3 as
7
# published by the Free Software Foundation.
9
# charm-helpers is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
# GNU Lesser General Public License for more details.
14
# You should have received a copy of the GNU Lesser General Public License
15
# along with charm-helpers. If not, see <http://www.gnu.org/licenses/>.
19
from charmhelpers.core.hookenv import (
26
from jinja2 import FileSystemLoader, Environment
28
from charmhelpers.fetch import apt_install
29
from charmhelpers.fetch import apt_update
30
apt_update(fatal=True)
31
apt_install('python-jinja2', fatal=True)
32
from jinja2 import FileSystemLoader, Environment
35
# NOTE: function separated from main rendering code to facilitate easier
36
# mocking in unit tests.
37
def write(path, data):
38
with open(path, 'wb') as out:
42
def get_template_path(template_dir, path):
43
"""Returns the template file which would be used to render the path.
45
The path to the template file is returned.
46
:param template_dir: the directory the templates are located in
47
:param path: the file path to be written to.
48
:returns: path to the template file
50
return os.path.join(template_dir, os.path.basename(path))
53
def render_and_write(template_dir, path, context):
54
"""Renders the specified template into the file.
56
:param template_dir: the directory to load the template from
57
:param path: the path to write the templated contents to
58
:param context: the parameters to pass to the rendering engine
60
env = Environment(loader=FileSystemLoader(template_dir))
61
template_file = os.path.basename(path)
62
template = env.get_template(template_file)
63
log('Rendering from template: %s' % template.name, level=DEBUG)
64
rendered_content = template.render(context)
65
if not rendered_content:
66
log("Render returned None - skipping '%s'" % path,
70
write(path, rendered_content.encode('utf-8').strip())
71
log('Wrote template %s' % path, level=DEBUG)