Created
September 7, 2023 09:17
-
-
Save dkraczkowski/50262cc505c8047d041a0593dbfe1f49 to your computer and use it in GitHub Desktop.
Style your output in cli with this class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from __future__ import annotations | |
| from enum import Enum | |
| from typing import List, Union | |
| class TextStyles(Enum): | |
| OK = "\033[92m" | |
| WARNING = "\033[93m" | |
| FAIL = "\033[91m" | |
| OFF = "\033[0m" | |
| BOLD = "\033[1m" | |
| UNDERLINE = "\033[4m" | |
| ITALIC = "\033[3m" | |
| RED = "\033[31m" | |
| def __str__(self) -> str: | |
| return self.value | |
| class StyledText: | |
| italic: StyledText | |
| bold: StyledText | |
| underline: StyledText | |
| ok: StyledText | |
| warning: StyledText | |
| fail: StyledText | |
| red: StyledText | |
| def __init__(self, value: str = "", decorations: List[TextStyles] = None) -> None: | |
| self.decorations = decorations or [] | |
| self.value = value | |
| def __getattr__(self, decoration: str) -> StyledText: | |
| if decoration.upper() in TextStyles.__members__.keys(): | |
| return StyledText(decorations=[TextStyles[decoration.upper()]]) | |
| return StyledText() | |
| def style_text(self, text: str) -> str: | |
| result = "" | |
| for decoration in self.decorations: | |
| result += str(decoration) | |
| result += text | |
| result += str(TextStyles.OFF) | |
| return result | |
| def __matmul__(self, other: str) -> StyledText: | |
| if isinstance(other, str): | |
| return StyledText(self.value + other, self.decorations) | |
| raise ValueError | |
| def __rmatmul__(self, other: Union[str, StyledText]): | |
| if isinstance(other, str): | |
| return StyledText(self.value + other, self.decorations) | |
| raise ValueError | |
| def __add__(self, other: Union[str, StyledText]): | |
| if isinstance(other, str): | |
| return str(self) + other | |
| if other.value and self.value: | |
| return str(self) + str(other) | |
| return StyledText(self.value, self.decorations + other.decorations) | |
| def __radd__(self, other): | |
| if isinstance(other, str): | |
| return other + str(self) | |
| if other.value and self.value: | |
| return str(other) + str(self) | |
| return StyledText(self.value, self.decorations + other.decorations) | |
| def __str__(self) -> str: | |
| return self.style_text(self.value) | |
| Style = StyledText() | |
| # Example usage | |
| # "Hello World" @ Style.red + Style.bold |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment