2016-07-05 22:11:32 +00:00
|
|
|
import re
|
2016-06-02 00:31:41 +00:00
|
|
|
import codecs
|
|
|
|
|
|
|
|
import six
|
|
|
|
|
|
|
|
|
|
|
|
def always_bytes(unicode_or_bytes, *encode_args):
|
|
|
|
if isinstance(unicode_or_bytes, six.text_type):
|
|
|
|
return unicode_or_bytes.encode(*encode_args)
|
|
|
|
return unicode_or_bytes
|
|
|
|
|
|
|
|
|
|
|
|
def native(s, *encoding_opts):
|
|
|
|
"""
|
|
|
|
Convert :py:class:`bytes` or :py:class:`unicode` to the native
|
|
|
|
:py:class:`str` type, using latin1 encoding if conversion is necessary.
|
|
|
|
|
|
|
|
https://www.python.org/dev/peps/pep-3333/#a-note-on-string-types
|
|
|
|
"""
|
|
|
|
if not isinstance(s, (six.binary_type, six.text_type)):
|
|
|
|
raise TypeError("%r is neither bytes nor unicode" % s)
|
2016-06-28 12:05:56 +00:00
|
|
|
if six.PY2:
|
2016-06-02 00:31:41 +00:00
|
|
|
if isinstance(s, six.text_type):
|
|
|
|
return s.encode(*encoding_opts)
|
2016-06-28 12:05:56 +00:00
|
|
|
else:
|
|
|
|
if isinstance(s, six.binary_type):
|
|
|
|
return s.decode(*encoding_opts)
|
2016-06-02 00:31:41 +00:00
|
|
|
return s
|
|
|
|
|
|
|
|
|
2016-07-05 22:11:32 +00:00
|
|
|
# Translate control characters to "safe" characters. This implementation initially
|
|
|
|
# replaced them with the matching control pictures (http://unicode.org/charts/PDF/U2400.pdf),
|
|
|
|
# but that turned out to render badly with monospace fonts. We are back to "." therefore.
|
|
|
|
_control_char_trans = {
|
|
|
|
x: ord(".") # x + 0x2400 for unicode control group pictures
|
|
|
|
for x in range(32)
|
|
|
|
}
|
|
|
|
_control_char_trans[127] = ord(".") # 0x2421
|
|
|
|
_control_char_trans_newline = _control_char_trans.copy()
|
|
|
|
for x in ("\r", "\n", "\t"):
|
|
|
|
del _control_char_trans_newline[ord(x)]
|
|
|
|
|
|
|
|
|
|
|
|
if six.PY2:
|
|
|
|
pass
|
|
|
|
else:
|
|
|
|
_control_char_trans = str.maketrans(_control_char_trans)
|
|
|
|
_control_char_trans_newline = str.maketrans(_control_char_trans_newline)
|
|
|
|
|
|
|
|
|
|
|
|
def escape_control_characters(text, keep_spacing=True):
|
2016-06-02 00:31:41 +00:00
|
|
|
"""
|
2016-07-05 22:11:32 +00:00
|
|
|
Replace all unicode C1 control characters from the given text with their respective control pictures.
|
|
|
|
For example, a null byte is replaced with the unicode character "\u2400".
|
2016-06-02 00:31:41 +00:00
|
|
|
|
2016-07-05 22:11:32 +00:00
|
|
|
Args:
|
|
|
|
keep_spacing: If True, tabs and newlines will not be replaced.
|
2016-06-02 00:31:41 +00:00
|
|
|
"""
|
2016-07-05 22:11:32 +00:00
|
|
|
# type: (six.text_type) -> six.text_type
|
|
|
|
if not isinstance(text, six.text_type):
|
|
|
|
raise ValueError("text type must be unicode but is {}".format(type(text).__name__))
|
|
|
|
|
|
|
|
trans = _control_char_trans_newline if keep_spacing else _control_char_trans
|
|
|
|
if six.PY2:
|
2016-06-02 00:31:41 +00:00
|
|
|
return u"".join(
|
2016-07-05 22:11:32 +00:00
|
|
|
six.unichr(trans.get(ord(ch), ord(ch)))
|
|
|
|
for ch in text
|
2016-06-02 00:31:41 +00:00
|
|
|
)
|
2016-07-05 22:11:32 +00:00
|
|
|
return text.translate(trans)
|
2016-06-02 00:31:41 +00:00
|
|
|
|
|
|
|
|
2016-07-05 22:11:32 +00:00
|
|
|
def bytes_to_escaped_str(data, keep_spacing=False):
|
2016-06-02 00:31:41 +00:00
|
|
|
"""
|
|
|
|
Take bytes and return a safe string that can be displayed to the user.
|
|
|
|
|
|
|
|
Single quotes are always escaped, double quotes are never escaped:
|
|
|
|
"'" + bytes_to_escaped_str(...) + "'"
|
|
|
|
gives a valid Python string.
|
2016-07-05 22:11:32 +00:00
|
|
|
|
|
|
|
Args:
|
|
|
|
keep_spacing: If True, tabs and newlines will not be escaped.
|
2016-06-02 00:31:41 +00:00
|
|
|
"""
|
|
|
|
|
|
|
|
if not isinstance(data, bytes):
|
|
|
|
raise ValueError("data must be bytes, but is {}".format(data.__class__.__name__))
|
|
|
|
# We always insert a double-quote here so that we get a single-quoted string back
|
|
|
|
# https://stackoverflow.com/questions/29019340/why-does-python-use-different-quotes-for-representing-strings-depending-on-their
|
2016-07-05 22:11:32 +00:00
|
|
|
ret = repr(b'"' + data).lstrip("b")[2:-1]
|
|
|
|
if keep_spacing:
|
|
|
|
ret = re.sub(
|
|
|
|
r"(?<!\\)(\\\\)*\\([nrt])",
|
|
|
|
lambda m: (m.group(1) or "") + dict(n="\n", r="\r", t="\t")[m.group(2)],
|
|
|
|
ret
|
|
|
|
)
|
|
|
|
return ret
|
2016-06-02 00:31:41 +00:00
|
|
|
|
|
|
|
|
|
|
|
def escaped_str_to_bytes(data):
|
|
|
|
"""
|
|
|
|
Take an escaped string and return the unescaped bytes equivalent.
|
|
|
|
"""
|
|
|
|
if not isinstance(data, six.string_types):
|
|
|
|
if six.PY2:
|
|
|
|
raise ValueError("data must be str or unicode, but is {}".format(data.__class__.__name__))
|
|
|
|
raise ValueError("data must be str, but is {}".format(data.__class__.__name__))
|
|
|
|
|
|
|
|
if six.PY2:
|
|
|
|
if isinstance(data, unicode):
|
|
|
|
data = data.encode("utf8")
|
|
|
|
return data.decode("string-escape")
|
|
|
|
|
|
|
|
# This one is difficult - we use an undocumented Python API here
|
|
|
|
# as per http://stackoverflow.com/a/23151714/934719
|
|
|
|
return codecs.escape_decode(data)[0]
|
2016-06-02 01:03:37 +00:00
|
|
|
|
|
|
|
|
|
|
|
def isBin(s):
|
|
|
|
"""
|
|
|
|
Does this string have any non-ASCII characters?
|
|
|
|
"""
|
|
|
|
for i in s:
|
|
|
|
i = ord(i)
|
|
|
|
if i < 9 or 13 < i < 32 or 126 < i:
|
|
|
|
return True
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
|
|
|
def isMostlyBin(s):
|
|
|
|
s = s[:100]
|
|
|
|
return sum(isBin(ch) for ch in s) / len(s) > 0.3
|
|
|
|
|
|
|
|
|
|
|
|
def isXML(s):
|
2016-06-07 07:23:07 +00:00
|
|
|
return s.strip().startswith("<")
|
2016-06-02 01:03:37 +00:00
|
|
|
|
|
|
|
|
|
|
|
def clean_hanging_newline(t):
|
|
|
|
"""
|
|
|
|
Many editors will silently add a newline to the final line of a
|
|
|
|
document (I'm looking at you, Vim). This function fixes this common
|
|
|
|
problem at the risk of removing a hanging newline in the rare cases
|
|
|
|
where the user actually intends it.
|
|
|
|
"""
|
|
|
|
if t and t[-1] == "\n":
|
|
|
|
return t[:-1]
|
|
|
|
return t
|
|
|
|
|
|
|
|
|
|
|
|
def hexdump(s):
|
|
|
|
"""
|
|
|
|
Returns:
|
|
|
|
A generator of (offset, hex, str) tuples
|
|
|
|
"""
|
|
|
|
for i in range(0, len(s), 16):
|
|
|
|
offset = "{:0=10x}".format(i).encode()
|
|
|
|
part = s[i:i + 16]
|
2016-07-02 00:17:16 +00:00
|
|
|
x = " ".join("{:0=2x}".format(i) for i in six.iterbytes(part))
|
2016-06-02 01:03:37 +00:00
|
|
|
x = x.ljust(47) # 16*2 + 15
|
2016-07-05 22:11:32 +00:00
|
|
|
part_repr = escape_control_characters(
|
|
|
|
part.decode("ascii", "replace").replace(u"\ufffd", u"."),
|
|
|
|
False
|
|
|
|
)
|
|
|
|
yield (offset, x, part_repr)
|