| 1 |
|
| 2 |
|
| 3 |
from __future__ import unicode_literals |
| 4 |
|
| 5 |
import six |
| 6 |
from collections import OrderedDict |
| 7 |
|
| 8 |
try: |
| 9 |
from collections.abc import Iterable |
| 10 |
except ImportError: |
| 11 |
from collections import Iterable |
| 12 |
|
| 13 |
from sure.terminal import red, green, yellow |
| 14 |
|
| 15 |
|
| 16 |
if six.PY2: |
| 17 |
def compat_repr(object_repr): |
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
result = '' |
| 22 |
in_quote = False |
| 23 |
curr_quote = None |
| 24 |
for char in object_repr: |
| 25 |
if char in ['"', "'"] and ( |
| 26 |
not curr_quote or char == curr_quote): |
| 27 |
if in_quote: |
| 28 |
|
| 29 |
curr_quote = None |
| 30 |
in_quote = False |
| 31 |
else: |
| 32 |
|
| 33 |
curr_quote = char |
| 34 |
result += 'u' |
| 35 |
in_quote = True |
| 36 |
result += char |
| 37 |
return result |
| 38 |
else: |
| 39 |
def compat_repr(object_repr): |
| 40 |
return object_repr |
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
|
| 47 |
|
| 48 |
class FakeOrderedDict(OrderedDict): |
| 49 |
""" OrderedDict that has the repr of a normal dict |
| 50 |
|
| 51 |
We must return a string whether in py2 or py3. |
| 52 |
""" |
| 53 |
def __unicode__(self): |
| 54 |
if not self: |
| 55 |
return '{}' |
| 56 |
key_values = [] |
| 57 |
for key, value in self.items(): |
| 58 |
key, value = repr(key), repr(value) |
| 59 |
if isinstance(value, six.binary_type) and six.PY2: |
| 60 |
value = value.decode("utf-8") |
| 61 |
key_values.append("{0}: {1}".format(key, value)) |
| 62 |
res = "{{{0}}}".format(", ".join(key_values)) |
| 63 |
return res |
| 64 |
|
| 65 |
if six.PY2: |
| 66 |
def __repr__(self): |
| 67 |
return self.__unicode__().encode('utf-8') |
| 68 |
else: |
| 69 |
def __repr__(self): |
| 70 |
return self.__unicode__() |
| 71 |
|
| 72 |
|
| 73 |
def _obj_with_safe_repr(obj): |
| 74 |
if isinstance(obj, dict): |
| 75 |
ret = FakeOrderedDict() |
| 76 |
try: |
| 77 |
keys = sorted(obj.keys()) |
| 78 |
except TypeError: |
| 79 |
keys = obj.keys() |
| 80 |
for key in keys: |
| 81 |
ret[_obj_with_safe_repr(key)] = _obj_with_safe_repr(obj[key]) |
| 82 |
elif isinstance(obj, list): |
| 83 |
ret = [] |
| 84 |
for x in obj: |
| 85 |
if isinstance(x, dict): |
| 86 |
ret.append(_obj_with_safe_repr(x)) |
| 87 |
else: |
| 88 |
ret.append(x) |
| 89 |
else: |
| 90 |
ret = obj |
| 91 |
return ret |
| 92 |
|
| 93 |
|
| 94 |
def safe_repr(val): |
| 95 |
try: |
| 96 |
if isinstance(val, dict): |
| 97 |
|
| 98 |
|
| 99 |
val = _obj_with_safe_repr(val) |
| 100 |
ret = repr(val) |
| 101 |
if six.PY2: |
| 102 |
ret = ret.decode('utf-8') |
| 103 |
except UnicodeEncodeError: |
| 104 |
ret = red('a %r that cannot be represented' % type(val)) |
| 105 |
else: |
| 106 |
ret = green(ret) |
| 107 |
|
| 108 |
return ret |
| 109 |
|
| 110 |
|
| 111 |
|
| 112 |
text_type_name = six.text_type().__class__.__name__ |