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
14def _encoded_write(old_write, encoding):
15    def impl(s):
16        # If we were asked to write a `bytes` decode it as unicode before
17        # attempting to write.
18        if isinstance(s, bytes):
19            s = s.decode(encoding, "replace")
20        # Filter unreadable characters, Python 3 is stricter than python 2 about them.
21        import re
22        s = re.sub(r'[^\x00-\x7f]',r' ',s)
23        return old_write(s)
24    return impl
25
26'''
27Create a Text I/O file object that can be written to with either unicode strings
28or byte strings.
29'''
30
31
32def open(
33        file,
34        encoding,
35        mode='r',
36        buffering=-1,
37        errors=None,
38        newline=None,
39        closefd=True):
40    wrapped_file = io.open(
41        file,
42        mode=mode,
43        buffering=buffering,
44        encoding=encoding,
45        errors=errors,
46        newline=newline,
47        closefd=closefd)
48    new_write = _encoded_write(getattr(wrapped_file, 'write'), encoding)
49    setattr(wrapped_file, 'write', new_write)
50    return wrapped_file
51