|
| 1 | +# log21.helper_types.py |
| 2 | +# CodeWriter21 |
| 3 | +"""A collection of useful types meant for using with argument parser to parse CLI |
| 4 | +arguments to more usable formats. |
| 5 | +
|
| 6 | ++ FileSize: Can take `str` and `int` values. Will convert human inputs such as "121 KB", |
| 7 | + "21MiB", or "4.56 GB" to bytes. Can also be used to represent bytes value in more |
| 8 | + human-readable formats. |
| 9 | +""" |
| 10 | + |
| 11 | +# yapf: disable |
| 12 | + |
| 13 | +import re as _re |
| 14 | +from math import log as _log |
| 15 | +from typing import Union as _Union, SupportsInt as _SupportsInt |
| 16 | + |
| 17 | +# yapf: enable |
| 18 | + |
| 19 | +__all__ = ["FileSize"] |
| 20 | + |
| 21 | +POWERS = "KMGTPEZYRQ" |
| 22 | +FILE_SIZE_PATTERN = _re.compile(rf"^([+-]?[0-9]+(?:\.[0-9]+)?)\s*(|[{POWERS}])(i?)B$") |
| 23 | + |
| 24 | + |
| 25 | +class FileSize: |
| 26 | + |
| 27 | + def __init__(self, value: _Union[int, str]) -> None: |
| 28 | + """An interface for converting different inputs to file-size (bytes). |
| 29 | +
|
| 30 | + :param value: int value in bytes or a string such as "100 KB", "20MiB", or "1.23 |
| 31 | + GB" |
| 32 | + :raises TypeError: If the value is not of type int or str |
| 33 | + :raises ValueError: If the str value does not match the file-size pattern: |
| 34 | + ^([+-]?[0-9]+(?:\\.[0-9]+)?)\\s*(|[KMGTPEZYRQ])(i?)B$ |
| 35 | + """ |
| 36 | + if isinstance(value, int): |
| 37 | + self.bytes = value |
| 38 | + elif isinstance(value, str): |
| 39 | + match = FILE_SIZE_PATTERN.match(value) |
| 40 | + if not match: |
| 41 | + raise ValueError(f"Input does not match the file-size pattern: {value}") |
| 42 | + val, prefix, binary = match.groups() |
| 43 | + power = POWERS.index(prefix) + 1 |
| 44 | + assert power is not None |
| 45 | + self.bytes = int(float(val) * (1024 if binary else 1000)**power) |
| 46 | + else: |
| 47 | + raise TypeError(f"Input to FileSize() can be int or str, not {type(value)}") |
| 48 | + |
| 49 | + def humanize( |
| 50 | + self, |
| 51 | + binary: bool = False, |
| 52 | + gnu: bool = False, |
| 53 | + fmt: str = "%.2f", |
| 54 | + ) -> str: |
| 55 | + """Returns the size in a human readable way.""" |
| 56 | + base = 1024 if (gnu or binary) else 1000 |
| 57 | + abs_bytes = abs(self.bytes) |
| 58 | + |
| 59 | + if abs_bytes == 1 and not gnu: |
| 60 | + return f"{self.bytes} Byte" |
| 61 | + |
| 62 | + if abs_bytes < base: |
| 63 | + return f"{self.bytes}B" if gnu else f"{self.bytes} Bytes" |
| 64 | + |
| 65 | + power = int(min(_log(abs_bytes, base), len(POWERS))) |
| 66 | + result: str = fmt % (self.bytes / (base**power)) |
| 67 | + if gnu: |
| 68 | + return result + POWERS[power - 1] |
| 69 | + result += " " + POWERS[power - 1] |
| 70 | + if binary: |
| 71 | + result += "i" |
| 72 | + result += "B" |
| 73 | + return result |
| 74 | + |
| 75 | + @property |
| 76 | + def KB(self) -> float: |
| 77 | + return self.bytes / 1000 |
| 78 | + |
| 79 | + @property |
| 80 | + def MB(self) -> float: |
| 81 | + return self.bytes / 1000_000 |
| 82 | + |
| 83 | + @property |
| 84 | + def GB(self) -> float: |
| 85 | + return self.bytes / 1000_000_000 |
| 86 | + |
| 87 | + @property |
| 88 | + def KiB(self) -> float: |
| 89 | + return self.bytes / 1024 |
| 90 | + |
| 91 | + @property |
| 92 | + def MiB(self) -> float: |
| 93 | + return self.bytes / 1048576 |
| 94 | + |
| 95 | + @property |
| 96 | + def GiB(self) -> float: |
| 97 | + return self.bytes / 1073741824 |
| 98 | + |
| 99 | + def __int__(self) -> int: |
| 100 | + return self.bytes |
| 101 | + |
| 102 | + def __eq__(self, value: object) -> bool: |
| 103 | + if not isinstance(value, _SupportsInt): |
| 104 | + return False |
| 105 | + return self.bytes == int(value) |
| 106 | + |
| 107 | + def __lt__(self, value: _SupportsInt) -> bool: |
| 108 | + return self.bytes < int(value) |
| 109 | + |
| 110 | + def __le__(self, value: _SupportsInt) -> bool: |
| 111 | + return self.bytes <= int(value) |
| 112 | + |
| 113 | + def __gt__(self, value: _SupportsInt) -> bool: |
| 114 | + return int(value) < self.bytes |
| 115 | + |
| 116 | + def __ge__(self, value: _SupportsInt) -> bool: |
| 117 | + return int(value) <= self.bytes |
| 118 | + |
| 119 | + def __add__(self, value: _SupportsInt) -> "FileSize": |
| 120 | + return FileSize(self.bytes + int(value)) |
| 121 | + |
| 122 | + def __str__(self) -> str: |
| 123 | + return self.humanize(binary=True) |
| 124 | + |
| 125 | + def __repr__(self) -> str: |
| 126 | + return f"<{self.__class__.__name__}: '{self!s}'>" |
0 commit comments