comparison mercurial/pycompat.py @ 30032:2219f4f82ede

pycompat: extract function that converts attribute or encoding name to str This will be used to convert encoding.encoding to a str acceptable by Python 3 functions. The source encoding is changed to "latin-1" because encoding.encoding can have arbitrary bytes. Since valid names should consist of ASCII characters, we don't care about the mapping of non-ASCII characters so long as invalid names are distinct from valid names.
author Yuya Nishihara <yuya@tcha.org>
date Wed, 28 Sep 2016 22:32:09 +0900
parents 0f6d6fdd3c2a
children f3a1089654e3
comparison
equal deleted inserted replaced
30030:0f6d6fdd3c2a 30032:2219f4f82ede
33 33
34 if ispy3: 34 if ispy3:
35 import builtins 35 import builtins
36 import functools 36 import functools
37 37
38 def sysstr(s):
39 """Return a keyword str to be passed to Python functions such as
40 getattr() and str.encode()
41
42 This never raises UnicodeDecodeError. Non-ascii characters are
43 considered invalid and mapped to arbitrary but unique code points
44 such that 'sysstr(a) != sysstr(b)' for all 'a != b'.
45 """
46 if isinstance(s, builtins.str):
47 return s
48 return s.decode(u'latin-1')
49
38 def _wrapattrfunc(f): 50 def _wrapattrfunc(f):
39 @functools.wraps(f) 51 @functools.wraps(f)
40 def w(object, name, *args): 52 def w(object, name, *args):
41 if isinstance(name, bytes): 53 return f(object, sysstr(name), *args)
42 name = name.decode(u'utf-8')
43 return f(object, name, *args)
44 return w 54 return w
45 55
46 # these wrappers are automagically imported by hgloader 56 # these wrappers are automagically imported by hgloader
47 delattr = _wrapattrfunc(builtins.delattr) 57 delattr = _wrapattrfunc(builtins.delattr)
48 getattr = _wrapattrfunc(builtins.getattr) 58 getattr = _wrapattrfunc(builtins.getattr)
49 hasattr = _wrapattrfunc(builtins.hasattr) 59 hasattr = _wrapattrfunc(builtins.hasattr)
50 setattr = _wrapattrfunc(builtins.setattr) 60 setattr = _wrapattrfunc(builtins.setattr)
51 xrange = builtins.range 61 xrange = builtins.range
62
63 else:
64 def sysstr(s):
65 return s
52 66
53 stringio = io.StringIO 67 stringio = io.StringIO
54 empty = _queue.Empty 68 empty = _queue.Empty
55 queue = _queue.Queue 69 queue = _queue.Queue
56 70