xref: /llvm-project/lldb/packages/Python/lldbsuite/support/seven.py (revision b42d51ba9ad1f85e6b6f3508e6c2c4ab5ee22ac1)
1import binascii
2import six
3import shlex
4
5if six.PY2:
6    import commands
7    get_command_output = commands.getoutput
8    get_command_status_output = commands.getstatusoutput
9
10    cmp_ = cmp
11else:
12    def get_command_status_output(command):
13        try:
14            import subprocess
15            return (
16                0,
17                subprocess.check_output(
18                    command,
19                    shell=True,
20                    universal_newlines=True).rstrip())
21        except subprocess.CalledProcessError as e:
22            return (e.returncode, e.output)
23
24    def get_command_output(command):
25        return get_command_status_output(command)[1]
26
27    cmp_ = lambda x, y: (x > y) - (x < y)
28
29def bitcast_to_string(b):
30    """
31    Take a string(PY2) or a bytes(PY3) object and return a string. The returned
32    string contains the exact same bytes as the input object (latin1 <-> unicode
33    transformation is an identity operation for the first 256 code points).
34    """
35    return b if six.PY2 else b.decode("latin1")
36
37def bitcast_to_bytes(s):
38    """
39    Take a string and return a string(PY2) or a bytes(PY3) object. The returned
40    object contains the exact same bytes as the input string. (latin1 <->
41    unicode transformation is an identity operation for the first 256 code
42    points).
43    """
44    return s if six.PY2 else s.encode("latin1")
45
46def unhexlify(hexstr):
47    """Hex-decode a string. The result is always a string."""
48    return bitcast_to_string(binascii.unhexlify(hexstr))
49
50def hexlify(data):
51    """Hex-encode string data. The result if always a string."""
52    return bitcast_to_string(binascii.hexlify(bitcast_to_bytes(data)))
53
54# TODO: Replace this with `shlex.join` when minimum Python version is >= 3.8
55def join_for_shell(split_command):
56    return " ".join([shlex.quote(part) for part in split_command])
57