Mercurial > hg
comparison mercurial/templatefilters.py @ 26856:baa77652be68 stable
templatefilters: try round-trip utf-8 conversion by json filter (issue4933)
As JSON string is known to be a unicode, we should try round-trip conversion
for localstr type. This patch tests localstr type explicitly because
encoding.fromlocal() may raise Abort for undecodable str, which is probably
not what we want. Maybe we can refactor json filter to use encoding module
more later.
Still "{desc|json}" can't round-trip because showdescription() modifies a
localstr object.
author | Yuya Nishihara <yuya@tcha.org> |
---|---|
date | Wed, 04 Nov 2015 23:48:15 +0900 |
parents | 7012be5ab5bd |
children | f9984f76fd90 |
comparison
equal
deleted
inserted
replaced
26855:9350f00a7b23 | 26856:baa77652be68 |
---|---|
195 def json(obj): | 195 def json(obj): |
196 if obj is None or obj is False or obj is True: | 196 if obj is None or obj is False or obj is True: |
197 return {None: 'null', False: 'false', True: 'true'}[obj] | 197 return {None: 'null', False: 'false', True: 'true'}[obj] |
198 elif isinstance(obj, int) or isinstance(obj, float): | 198 elif isinstance(obj, int) or isinstance(obj, float): |
199 return str(obj) | 199 return str(obj) |
200 elif isinstance(obj, encoding.localstr): | |
201 u = encoding.fromlocal(obj).decode('utf-8') # can round-trip | |
202 return '"%s"' % jsonescape(u) | |
200 elif isinstance(obj, str): | 203 elif isinstance(obj, str): |
204 # no encoding.fromlocal() because it may abort if obj can't be decoded | |
201 u = unicode(obj, encoding.encoding, 'replace') | 205 u = unicode(obj, encoding.encoding, 'replace') |
202 return '"%s"' % jsonescape(u) | 206 return '"%s"' % jsonescape(u) |
203 elif isinstance(obj, unicode): | 207 elif isinstance(obj, unicode): |
204 return '"%s"' % jsonescape(obj) | 208 return '"%s"' % jsonescape(obj) |
205 elif util.safehasattr(obj, 'keys'): | 209 elif util.safehasattr(obj, 'keys'): |