| 1 |
# -*- coding: utf-8 -*- |
| 2 |
"""Various utility functions and helpers.""" |
| 3 |
|
| 4 |
import binascii |
| 5 |
import os |
| 6 |
import re |
| 7 |
from functools import lru_cache |
| 8 |
from typing import Dict, Tuple, Union |
| 9 |
|
| 10 |
from typing import TYPE_CHECKING |
| 11 |
|
| 12 |
if TYPE_CHECKING: |
| 13 |
from pygments.style import StyleMeta |
| 14 |
|
| 15 |
from cli_helpers.compat import ( |
| 16 |
binary_type, |
| 17 |
text_type, |
| 18 |
Terminal256Formatter, |
| 19 |
TerminalTrueColorFormatter, |
| 20 |
StringIO, |
| 21 |
) |
| 22 |
|
| 23 |
|
| 24 |
def bytes_to_string(b): |
| 25 |
"""Convert bytes *b* to a string. |
| 26 |
|
| 27 |
Hexlify bytes that can't be decoded. |
| 28 |
|
| 29 |
""" |
| 30 |
if isinstance(b, binary_type): |
| 31 |
needs_hex = False |
| 32 |
try: |
| 33 |
result = b.decode("utf8") |
| 34 |
needs_hex = not result.isprintable() |
| 35 |
except UnicodeDecodeError: |
| 36 |
needs_hex = True |
| 37 |
if needs_hex: |
| 38 |
return "0x" + binascii.hexlify(b).decode("ascii") |
| 39 |
else: |
| 40 |
return result |
| 41 |
return b |
| 42 |
|
| 43 |
|
| 44 |
def to_hex_if_bin(b): |
| 45 |
"""Convert bytes *b* to a string. |
| 46 |
|
| 47 |
Pass b through if not bytes. |
| 48 |
|
| 49 |
""" |
| 50 |
if isinstance(b, binary_type): |
| 51 |
return "0x" + binascii.hexlify(b).decode("ascii") |
| 52 |
return b |
| 53 |
|
| 54 |
|
| 55 |
def to_string(value): |
| 56 |
"""Convert *value* to a string.""" |
| 57 |
if isinstance(value, binary_type): |
| 58 |
return bytes_to_string(value) |
| 59 |
else: |
| 60 |
return text_type(value) |
| 61 |
|
| 62 |
|
| 63 |
def to_undecoded_string(value): |
| 64 |
"""Convert *value* to an undecoded string, respecting Nones.""" |
| 65 |
# preserve Nones so that |
| 66 |
# * this can run before override_missing_value when stringifying |
| 67 |
# * Nones are preserved in formats such as CSV |
| 68 |
if value is None: |
| 69 |
return None |
| 70 |
elif isinstance(value, binary_type): |
| 71 |
return to_hex_if_bin(value) |
| 72 |
else: |
| 73 |
return text_type(value) |
| 74 |
|
| 75 |
|
| 76 |
def truncate_string(value, max_width=None, skip_multiline_string=True): |
| 77 |
"""Truncate string values.""" |
| 78 |
if skip_multiline_string and isinstance(value, text_type) and "\n" in value: |
| 79 |
return value |
| 80 |
elif ( |
| 81 |
isinstance(value, text_type) |
| 82 |
and max_width is not None |
| 83 |
and len(value) > max_width |
| 84 |
): |
| 85 |
return value[: max_width - 3] + "..." |
| 86 |
return value |
| 87 |
|
| 88 |
|
| 89 |
def intlen(n): |
| 90 |
"""Find the length of the integer part of a number *n*.""" |
| 91 |
pos = n.find(".") |
| 92 |
return len(n) if pos < 0 else pos |
| 93 |
|
| 94 |
|
| 95 |
def filter_dict_by_key(d, keys): |
| 96 |
"""Filter the dict *d* to remove keys not in *keys*.""" |
| 97 |
return {k: v for k, v in d.items() if k in keys} |
| 98 |
|
| 99 |
|
| 100 |
def unique_items(seq): |
| 101 |
"""Return the unique items from iterable *seq* (in order).""" |
| 102 |
seen = set() |
| 103 |
return [x for x in seq if not (x in seen or seen.add(x))] |
| 104 |
|
| 105 |
|
| 106 |
_ansi_re = re.compile("\033\\[((?:\\d|;)*)([a-zA-Z])") |
| 107 |
|
| 108 |
|
| 109 |
def strip_ansi(value): |
| 110 |
"""Strip the ANSI escape sequences from a string.""" |
| 111 |
return _ansi_re.sub("", value) |
| 112 |
|
| 113 |
|
| 114 |
def replace(s, replace): |
| 115 |
"""Replace multiple values in a string""" |
| 116 |
for r in replace: |
| 117 |
s = s.replace(*r) |
| 118 |
return s |
| 119 |
|
| 120 |
|
| 121 |
@lru_cache() |
| 122 |
def _get_formatter(style) -> Union[Terminal256Formatter, TerminalTrueColorFormatter]: |
| 123 |
if "truecolor" in os.getenv("COLORTERM", "").lower(): |
| 124 |
return TerminalTrueColorFormatter(style=style) |
| 125 |
else: |
| 126 |
return Terminal256Formatter(style=style) |
| 127 |
|
| 128 |
|
| 129 |
def style_field(token, field, style): |
| 130 |
"""Get the styled text for a *field* using *token* type.""" |
| 131 |
formatter = _get_formatter(style) |
| 132 |
s = StringIO() |
| 133 |
formatter.format(((token, field),), s) |
| 134 |
return s.getvalue() |
| 135 |
|
| 136 |
|
| 137 |
def filter_style_table(style: "StyleMeta", *relevant_styles: str) -> Dict: |
| 138 |
""" |
| 139 |
get a dictionary of styles for given tokens. Typical usage: |
| 140 |
|
| 141 |
filter_style_table(style, Token.Output.EvenRow, Token.Output.OddRow) == { |
| 142 |
Token.Output.EvenRow: "", |
| 143 |
Token.Output.OddRow: "", |
| 144 |
} |
| 145 |
""" |
| 146 |
_styles_iter = ((key, val) for key, val in getattr(style, "styles", {}).items()) |
| 147 |
_relevant_styles_iter = filter(lambda tpl: tpl[0] in relevant_styles, _styles_iter) |
| 148 |
return {key: val for key, val in _relevant_styles_iter} |
| 149 |
|
| 150 |
|
| 151 |
@lru_cache() |
| 152 |
def version_as_tuple(version: str) -> Tuple: |
| 153 |
try: |
| 154 |
list_s = [re.sub(r'(rc|alpha|beta|test|dev|post).*$', '', x) for x in version.split('.')] |
| 155 |
list_s = [re.sub(r'[^\d]', '', x) for x in list_s] |
| 156 |
list_i = [int(x) for x in list_s if x] |
| 157 |
list_i.extend([0, 0, 0]) |
| 158 |
return tuple(list_i[:3]) |
| 159 |
except ValueError: |
| 160 |
return (0, 0, 0) |