xref: /llvm-project/lldb/packages/Python/lldbsuite/support/encoded_file.py (revision 2238dcc39358353cac21df75c3c3286ab20b8f53)
1e5a7990dSZachary Turner"""
22946cd70SChandler CarruthPart of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
32946cd70SChandler CarruthSee https://llvm.org/LICENSE.txt for license information.
42946cd70SChandler CarruthSPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
5e5a7990dSZachary Turner
6e5a7990dSZachary TurnerPrepares language bindings for LLDB build process.  Run with --help
7e5a7990dSZachary Turnerto see a description of the supported command line arguments.
8e5a7990dSZachary Turner"""
9e5a7990dSZachary Turner
10e5a7990dSZachary Turner# Python modules:
11e5a7990dSZachary Turnerimport io
12e5a7990dSZachary Turner
13b9c1b51eSKate Stone
14e5a7990dSZachary Turnerdef _encoded_write(old_write, encoding):
15e5a7990dSZachary Turner    def impl(s):
1656f9cfe3SDave Lee        # If we were asked to write a `bytes` decode it as unicode before
1756f9cfe3SDave Lee        # attempting to write.
1856f9cfe3SDave Lee        if isinstance(s, bytes):
1989d2245aSPavel Labath            s = s.decode(encoding, "replace")
20bd53e768SDavide Italiano        # Filter unreadable characters, Python 3 is stricter than python 2 about them.
21bd53e768SDavide Italiano        import re
22*2238dcc3SJonas Devlieghere
23*2238dcc3SJonas Devlieghere        s = re.sub(r"[^\x00-\x7f]", r" ", s)
24e5a7990dSZachary Turner        return old_write(s)
25*2238dcc3SJonas Devlieghere
26e5a7990dSZachary Turner    return impl
27e5a7990dSZachary Turner
28*2238dcc3SJonas Devlieghere
29*2238dcc3SJonas Devlieghere"""
3056f9cfe3SDave LeeCreate a Text I/O file object that can be written to with either unicode strings
3156f9cfe3SDave Leeor byte strings.
32*2238dcc3SJonas Devlieghere"""
33b9c1b51eSKate Stone
34b9c1b51eSKate Stone
35b9c1b51eSKate Stonedef open(
36*2238dcc3SJonas Devlieghere    file, encoding, mode="r", buffering=-1, errors=None, newline=None, closefd=True
37*2238dcc3SJonas Devlieghere):
38b9c1b51eSKate Stone    wrapped_file = io.open(
39b9c1b51eSKate Stone        file,
40b9c1b51eSKate Stone        mode=mode,
41b9c1b51eSKate Stone        buffering=buffering,
42b9c1b51eSKate Stone        encoding=encoding,
43b9c1b51eSKate Stone        errors=errors,
44b9c1b51eSKate Stone        newline=newline,
45*2238dcc3SJonas Devlieghere        closefd=closefd,
46*2238dcc3SJonas Devlieghere    )
47*2238dcc3SJonas Devlieghere    new_write = _encoded_write(getattr(wrapped_file, "write"), encoding)
48*2238dcc3SJonas Devlieghere    setattr(wrapped_file, "write", new_write)
49e5a7990dSZachary Turner    return wrapped_file
50