blob: c00bdc85dd4128ea7d20208162b8609f0bfa2ad8 [file] [log] [blame]
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +02001# osmo_gsm_tester: automated cellular network hardware tests
2# Proxy to templating engine to handle files
3#
4# Copyright (C) 2016-2017 by sysmocom - s.f.m.c. GmbH
5#
6# Author: Neels Hofmeyr <neels@hofmeyr.de>
7#
8# This program is free software: you can redistribute it and/or modify
9# it under the terms of the GNU Affero General Public License as
10# published by the Free Software Foundation, either version 3 of the
11# License, or (at your option) any later version.
12#
13# This program is distributed in the hope that it will be useful,
14# but WITHOUT ANY WARRANTY; without even the implied warranty of
15# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16# GNU Affero General Public License for more details.
17#
18# You should have received a copy of the GNU Affero General Public License
19# along with this program. If not, see <http://www.gnu.org/licenses/>.
20
21import os, sys
22from mako.template import Template
23from mako.lookup import TemplateLookup
24
25from . import log
Neels Hofmeyr3531a192017-03-28 14:30:28 +020026from .util import dict2obj
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +020027
28_lookup = None
29_logger = log.Origin('no templates dir set')
30
31def set_templates_dir(*templates_dirs):
32 global _lookup
33 global _logger
34 if not templates_dirs:
35 # default templates dir is relative to this source file
36 templates_dirs = [os.path.join(os.path.dirname(__file__), 'templates')]
37 for d in templates_dirs:
38 if not os.path.isdir(d):
39 raise RuntimeError('templates dir is not a dir: %r'
40 % os.path.abspath(d))
41 _lookup = TemplateLookup(directories=templates_dirs)
42 _logger = log.Origin('Templates', category=log.C_CNF)
43
44def render(name, values):
45 '''feed values dict into template and return rendered result.
46 ".tmpl" is added to the name to look it up in the templates dir.'''
47 global _lookup
48 if _lookup is None:
49 set_templates_dir()
Neels Hofmeyr3531a192017-03-28 14:30:28 +020050 tmpl_name = name + '.tmpl'
51 with log.Origin(tmpl_name):
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +020052 template = _lookup.get_template(tmpl_name)
53 _logger.dbg('rendering', tmpl_name)
Neels Hofmeyr3531a192017-03-28 14:30:28 +020054
55 line_info_name = tmpl_name.replace('-', '_').replace('.', '_')
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +020056 return template.render(**dict2obj(values))
57
58# vim: expandtab tabstop=4 shiftwidth=4