xref: /openbsd-src/gnu/llvm/lldb/packages/Python/lldbsuite/support/encoded_file.py (revision f6aab3d83b51b91c24247ad2c2573574de475a82)
1061da546Spatrick"""
2061da546SpatrickPart of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
3061da546SpatrickSee https://llvm.org/LICENSE.txt for license information.
4061da546SpatrickSPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
5061da546Spatrick
6061da546SpatrickPrepares language bindings for LLDB build process.  Run with --help
7061da546Spatrickto see a description of the supported command line arguments.
8061da546Spatrick"""
9061da546Spatrick
10061da546Spatrick# Python modules:
11061da546Spatrickimport io
12061da546Spatrick
13061da546Spatrick
14061da546Spatrickdef _encoded_write(old_write, encoding):
15061da546Spatrick    def impl(s):
16*f6aab3d8Srobert        # If we were asked to write a `bytes` decode it as unicode before
17*f6aab3d8Srobert        # attempting to write.
18*f6aab3d8Srobert        if isinstance(s, bytes):
19061da546Spatrick            s = s.decode(encoding, "replace")
20061da546Spatrick        # Filter unreadable characters, Python 3 is stricter than python 2 about them.
21061da546Spatrick        import re
22061da546Spatrick        s = re.sub(r'[^\x00-\x7f]',r' ',s)
23061da546Spatrick        return old_write(s)
24061da546Spatrick    return impl
25061da546Spatrick
26061da546Spatrick'''
27*f6aab3d8SrobertCreate a Text I/O file object that can be written to with either unicode strings
28*f6aab3d8Srobertor byte strings.
29061da546Spatrick'''
30061da546Spatrick
31061da546Spatrick
32061da546Spatrickdef open(
33061da546Spatrick        file,
34061da546Spatrick        encoding,
35061da546Spatrick        mode='r',
36061da546Spatrick        buffering=-1,
37061da546Spatrick        errors=None,
38061da546Spatrick        newline=None,
39061da546Spatrick        closefd=True):
40061da546Spatrick    wrapped_file = io.open(
41061da546Spatrick        file,
42061da546Spatrick        mode=mode,
43061da546Spatrick        buffering=buffering,
44061da546Spatrick        encoding=encoding,
45061da546Spatrick        errors=errors,
46061da546Spatrick        newline=newline,
47061da546Spatrick        closefd=closefd)
48061da546Spatrick    new_write = _encoded_write(getattr(wrapped_file, 'write'), encoding)
49061da546Spatrick    setattr(wrapped_file, 'write', new_write)
50061da546Spatrick    return wrapped_file
51