• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1"""
2Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
3See https://llvm.org/LICENSE.txt for license information.
4SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
5
6Prepares language bindings for LLDB build process.  Run with --help
7to see a description of the supported command line arguments.
8"""
9
10# Python modules:
11import io
12
13# Third party modules
14import six
15
16
17def _encoded_read(old_read, encoding):
18    def impl(size):
19        result = old_read(size)
20        # If this is Python 2 then we need to convert the resulting `unicode` back
21        # into a `str` before returning
22        if six.PY2:
23            result = result.encode(encoding)
24        return result
25    return impl
26
27
28def _encoded_write(old_write, encoding):
29    def impl(s):
30        # If we were asked to write a `str` (in Py2) or a `bytes` (in Py3) decode it
31        # as unicode before attempting to write.
32        if isinstance(s, six.binary_type):
33            s = s.decode(encoding, "replace")
34        # Filter unreadable characters, Python 3 is stricter than python 2 about them.
35        import re
36        s = re.sub(r'[^\x00-\x7f]',r' ',s)
37        return old_write(s)
38    return impl
39
40'''
41Create a Text I/O file object that can be written to with either unicode strings or byte strings
42under Python 2 and Python 3, and automatically encodes and decodes as necessary to return the
43native string type for the current Python version
44'''
45
46
47def open(
48        file,
49        encoding,
50        mode='r',
51        buffering=-1,
52        errors=None,
53        newline=None,
54        closefd=True):
55    wrapped_file = io.open(
56        file,
57        mode=mode,
58        buffering=buffering,
59        encoding=encoding,
60        errors=errors,
61        newline=newline,
62        closefd=closefd)
63    new_read = _encoded_read(getattr(wrapped_file, 'read'), encoding)
64    new_write = _encoded_write(getattr(wrapped_file, 'write'), encoding)
65    setattr(wrapped_file, 'read', new_read)
66    setattr(wrapped_file, 'write', new_write)
67    return wrapped_file
68