1""" 2Functions for adding yaml encoding to the jinja context 3""" 4 5 6import io 7import sys 8 9import yaml # pylint: disable=blacklisted-import 10from salt.utils.decorators.jinja import jinja_filter 11 12 13@jinja_filter() 14def yaml_dquote(text): 15 """ 16 Make text into a double-quoted YAML string with correct escaping 17 for special characters. Includes the opening and closing double 18 quote characters. 19 """ 20 with io.StringIO() as ostream: 21 yemitter = yaml.emitter.Emitter(ostream, width=sys.maxsize) 22 yemitter.write_double_quoted(str(text)) 23 return ostream.getvalue() 24 25 26@jinja_filter() 27def yaml_squote(text): 28 """ 29 Make text into a single-quoted YAML string with correct escaping 30 for special characters. Includes the opening and closing single 31 quote characters. 32 """ 33 with io.StringIO() as ostream: 34 yemitter = yaml.emitter.Emitter(ostream, width=sys.maxsize) 35 yemitter.write_single_quoted(str(text)) 36 return ostream.getvalue() 37 38 39@jinja_filter() 40def yaml_encode(data): 41 """ 42 A simple YAML encode that can take a single-element datatype and return 43 a string representation. 44 """ 45 yrepr = yaml.representer.SafeRepresenter() 46 ynode = yrepr.represent_data(data) 47 if not isinstance(ynode, yaml.ScalarNode): 48 raise TypeError( 49 "yaml_encode() only works with YAML scalar data; failed for {}".format( 50 type(data) 51 ) 52 ) 53 54 tag = ynode.tag.rsplit(":", 1)[-1] 55 ret = ynode.value 56 57 if tag == "str": 58 ret = yaml_dquote(ynode.value) 59 60 return ret 61