diff --git a/os_config_applier/os_config_applier.py b/os_config_applier/os_config_applier.py index ec03112..8e2b737 100755 --- a/os_config_applier/os_config_applier.py +++ b/os_config_applier/os_config_applier.py @@ -2,7 +2,6 @@ import json import logging import os -import pystache import sys from argparse import ArgumentParser from pystache.context import KeyNotFoundError @@ -10,6 +9,7 @@ from subprocess import Popen, PIPE from tempfile import NamedTemporaryFile from value_types import ensure_type from config_exception import ConfigException +from renderers import JsonRenderer TEMPLATES_DIR = os.environ.get('OS_CONFIG_APPLIER_TEMPLATES', '/opt/stack/os-config-applier/templates') @@ -76,7 +76,7 @@ def is_executable(path): def render_moustache(text, config): - r = pystache.Renderer(missing_tags='strict') + r = JsonRenderer(missing_tags='strict') return r.render(text, config) diff --git a/os_config_applier/renderers.py b/os_config_applier/renderers.py new file mode 100644 index 0000000..16e980a --- /dev/null +++ b/os_config_applier/renderers.py @@ -0,0 +1,26 @@ +import json + +from pystache import Renderer + + +class JsonRenderer(Renderer): + def __init__(self, + file_encoding=None, + string_encoding=None, + decode_errors=None, + search_dirs=None, + file_extension=None, + escape=None, + partials=None, + missing_tags=None): + # json would be html escaped otherwise + if escape is None: + escape = lambda u: u + return super(JsonRenderer, self).__init__(file_encoding, + string_encoding, + decode_errors, search_dirs, + file_extension, escape, + partials, missing_tags) + + def str_coerce(self, val): + return json.dumps(val) diff --git a/tests/json_renderer_tests.py b/tests/json_renderer_tests.py new file mode 100644 index 0000000..e096a5d --- /dev/null +++ b/tests/json_renderer_tests.py @@ -0,0 +1,19 @@ +import json + +from nose.tools import assert_equals +from os_config_applier.renderers import JsonRenderer + +TEST_JSON = '{"a":{"b":[1,2,3,"foo"],"c": "the quick brown fox"}}' + + +def test_json_renderer(): + context = json.loads(TEST_JSON) + x = JsonRenderer() + result = x.render('{{a.b}}', context) + print result + result_structure = json.loads(result) + desire_structure = json.loads('[1,2,3,"foo"]') + assert_equals(desire_structure, result_structure) + result = x.render('{{a.c}}', context) + print result + assert_equals(u'the quick brown fox', result)