except jinja2.exceptions.TemplateNotFound, e: # Throw an exception which includes a more user friendly error message # This likely will happen for included sub-template. Not that besides # pure "file not found" it may happen due to Jinja2's "security" # checks on path. values = {'name': realpath, 'subname': str(e)} msg = 'file: %(name)s, error: Cannot find/not allowed to load (include) template %(subname)s' % \ values error = errors.AnsibleError(msg) raise error # The low level calls above do not preserve the newline # characters at the end of the input data, so we use the # calculate the difference in newlines and append them # to the resulting output for parity res_newlines = count_newlines_from_end(res) data_newlines = count_newlines_from_end(data) if data_newlines > res_newlines: res += '\n' * (data_newlines - res_newlines) if isinstance(res, unicode): # do not try to re-template a unicode string result = res else: result = template(basedir, res, vars) return result def template_from_string(basedir, data, vars, fail_on_undefined=False): ''' run a string through the (Jinja2) templating engine '''
def test_count_newlines_from_end(self): self.assertEqual( string_functions.count_newlines_from_end('foo\n\n\n\n'), 4) self.assertEqual(string_functions.count_newlines_from_end('\nfoo'), 0)
except jinja2.exceptions.TemplateNotFound, e: # Throw an exception which includes a more user friendly error message # This likely will happen for included sub-template. Not that besides # pure "file not found" it may happen due to Jinja2's "security" # checks on path. values = {'name': realpath, 'subname': str(e)} msg = 'file: %(name)s, error: Cannot find/not allowed to load (include) template %(subname)s' % \ values error = errors.AnsibleError(msg) raise error # The low level calls above do not preserve the newline # characters at the end of the input data, so we use the # calculate the difference in newlines and append them # to the resulting output for parity res_newlines = count_newlines_from_end(res) data_newlines = count_newlines_from_end(data) if data_newlines > res_newlines: res += '\n' * (data_newlines - res_newlines) if isinstance(res, unicode): # do not try to re-template a unicode string result = res else: result = template(basedir, res, vars) return result def template_from_string(basedir, data, vars, fail_on_undefined=False): ''' run a string through the (Jinja2) templating engine ''' try:
def test_count_newlines_from_end(self): self.assertEqual(string_functions.count_newlines_from_end('foo\n\n\n\n'), 4) self.assertEqual(string_functions.count_newlines_from_end('\nfoo'), 0)