| 1 |
"""Summary formatter with custom conversions for con-duct output.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
from datetime import datetime |
| 5 |
import logging |
| 6 |
import string |
| 7 |
from typing import Any |
| 8 |
|
| 9 |
lgr = logging.getLogger("con-duct") |
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
FILESIZE_UNITS: list[tuple[str, int]] = [ |
| 18 |
("B", 1), |
| 19 |
("kB", 1000**1), |
| 20 |
("MB", 1000**2), |
| 21 |
("GB", 1000**3), |
| 22 |
("TB", 1000**4), |
| 23 |
("PB", 1000**5), |
| 24 |
("EB", 1000**6), |
| 25 |
("ZB", 1000**7), |
| 26 |
("YB", 1000**8), |
| 27 |
] |
| 28 |
|
| 29 |
|
| 30 |
class SummaryFormatter(string.Formatter): |
| 31 |
OK = "OK" |
| 32 |
NOK = "X" |
| 33 |
NONE = "-" |
| 34 |
BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(30, 38) |
| 35 |
RESET_SEQ = "\033[0m" |
| 36 |
COLOR_SEQ = "\033[1;%dm" |
| 37 |
|
| 38 |
def __init__(self, enable_colors: bool = False) -> None: |
| 39 |
self.enable_colors = enable_colors |
| 40 |
|
| 41 |
def naturalsize( |
| 42 |
self, |
| 43 |
value: float | str, |
| 44 |
format: str = "%.1f", |
| 45 |
) -> str: |
| 46 |
"""Format a number of bytes like a human readable decimal filesize (e.g. 10 kB). |
| 47 |
|
| 48 |
Examples: |
| 49 |
```pycon |
| 50 |
>>> formatter = SummaryFormatter() |
| 51 |
>>> formatter.naturalsize(3000000) |
| 52 |
'3.0 MB' |
| 53 |
>>> formatter.naturalsize(3000, "%.3f") |
| 54 |
'3.000 kB' |
| 55 |
>>> formatter.naturalsize(10**28) |
| 56 |
'10000.0 YB' |
| 57 |
``` |
| 58 |
|
| 59 |
Args: |
| 60 |
value (int, float, str): Integer to convert. |
| 61 |
format (str): Custom formatter. |
| 62 |
|
| 63 |
Returns: |
| 64 |
str: Human readable representation of a filesize. |
| 65 |
""" |
| 66 |
bytes_ = float(value) |
| 67 |
abs_bytes = abs(bytes_) |
| 68 |
|
| 69 |
if abs_bytes == 1: |
| 70 |
return "%d Byte" % bytes_ |
| 71 |
|
| 72 |
if abs_bytes < 1000: |
| 73 |
return "%d Bytes" % bytes_ |
| 74 |
|
| 75 |
|
| 76 |
|
| 77 |
|
| 78 |
name, divisor = FILESIZE_UNITS[1] |
| 79 |
for n, d in FILESIZE_UNITS[1:]: |
| 80 |
if abs_bytes / d >= 1: |
| 81 |
name, divisor = n, d |
| 82 |
return f"{format % (bytes_ / divisor)} {name}" |
| 83 |
|
| 84 |
def color_word(self, s: str, color: int) -> str: |
| 85 |
"""Color `s` with `color`. |
| 86 |
|
| 87 |
Parameters |
| 88 |
---------- |
| 89 |
s : string |
| 90 |
color : int |
| 91 |
Code for color. If the value evaluates to false, the string will not be |
| 92 |
colored. |
| 93 |
enable_colors: boolean, optional |
| 94 |
|
| 95 |
Returns |
| 96 |
------- |
| 97 |
str |
| 98 |
""" |
| 99 |
if color and self.enable_colors: |
| 100 |
return "%s%s%s" % (self.COLOR_SEQ % color, s, self.RESET_SEQ) |
| 101 |
return s |
| 102 |
|
| 103 |
def _format_duration(self, value: float) -> str: |
| 104 |
"""Format a duration in seconds to human-readable format.""" |
| 105 |
if value >= 3600: |
| 106 |
hours = int(value // 3600) |
| 107 |
minutes = int((value % 3600) // 60) |
| 108 |
seconds = value % 60 |
| 109 |
return f"{hours}h {minutes}m {seconds:.1f}s" |
| 110 |
elif value >= 60: |
| 111 |
minutes = int(value // 60) |
| 112 |
seconds = value % 60 |
| 113 |
return f"{minutes}m {seconds:.1f}s" |
| 114 |
else: |
| 115 |
return f"{value:.2f}s" |
| 116 |
|
| 117 |
def convert_field(self, value: str | None, conversion: str | None) -> Any: |
| 118 |
if conversion == "S": |
| 119 |
if value is not None: |
| 120 |
return self.color_word(self.naturalsize(value), self.GREEN) |
| 121 |
else: |
| 122 |
return self.color_word(self.NONE, self.RED) |
| 123 |
elif conversion == "E": |
| 124 |
return self.color_word( |
| 125 |
value if value is not None else self.NONE, |
| 126 |
self.RED if value or value is None else self.GREEN, |
| 127 |
) |
| 128 |
elif conversion == "X": |
| 129 |
col = self.GREEN if value else self.RED |
| 130 |
return self.color_word(value if value is not None else self.NONE, col) |
| 131 |
elif conversion == "N": |
| 132 |
if value is None: |
| 133 |
return self.color_word(self.NONE, self.RED) |
| 134 |
else: |
| 135 |
return self.color_word(value, self.GREEN) |
| 136 |
elif conversion == "P": |
| 137 |
if value is not None: |
| 138 |
return f"{float(value):.2f}%" |
| 139 |
else: |
| 140 |
return self.color_word(self.NONE, self.RED) |
| 141 |
elif conversion == "T": |
| 142 |
if value is not None: |
| 143 |
return self._format_duration(float(value)) |
| 144 |
else: |
| 145 |
return self.color_word(self.NONE, self.RED) |
| 146 |
elif conversion == "D": |
| 147 |
if value is not None: |
| 148 |
try: |
| 149 |
dt = datetime.fromtimestamp(float(value)) |
| 150 |
return dt.strftime("%b %d, %Y %I:%M %p") |
| 151 |
except (ValueError, OSError): |
| 152 |
return str(value) |
| 153 |
else: |
| 154 |
return self.color_word(self.NONE, self.RED) |
| 155 |
|
| 156 |
return super().convert_field(value, conversion) |
| 157 |
|
| 158 |
def format_field(self, value: Any, format_spec: str) -> Any: |
| 159 |
|
| 160 |
|
| 161 |
|
| 162 |
if value is None: |
| 163 |
|
| 164 |
return self.NONE |
| 165 |
|
| 166 |
if "!" in format_spec and format_spec.index("!") > 1: |
| 167 |
format_spec, conversion = format_spec.split("!", 1) |
| 168 |
else: |
| 169 |
conversion = None |
| 170 |
try: |
| 171 |
value_ = super().format_field(value, format_spec) |
| 172 |
except ValueError as exc: |
| 173 |
lgr.warning( |
| 174 |
"Falling back to `str` formatting for %r due to exception: %s", |
| 175 |
value, |
| 176 |
exc, |
| 177 |
) |
| 178 |
return str(value) |
| 179 |
if conversion: |
| 180 |
return self.convert_field(value_, conversion) |
| 181 |
return value_ |