codekingpro/portable-devtools
114k
1"""Handle chained inputs."""2 3from typing import TextIO4 5_TEXT_COLOR_MAPPING = {6 "blue": "36;1",7 "yellow": "33;1",8 "pink": "38;5;200",9 "green": "32;1",10 "red": "31;1",11}12 13 14def get_color_mapping(15 items: list[str], excluded_colors: list | None = None16) -> dict[str, str]:17 """Get mapping for items to a support color.18 19 Args:20 items: The items to map to colors.21 excluded_colors: The colors to exclude.22 23 Returns:24 The mapping of items to colors.25 26 Raises:27 ValueError: If no colors are available after applying exclusions.28 """29 colors = list(_TEXT_COLOR_MAPPING.keys())30 if excluded_colors is not None:31 colors = [c for c in colors if c not in excluded_colors]32 if not colors:33 msg = "No colors available after applying exclusions."34 raise ValueError(msg)35 return {item: colors[i % len(colors)] for i, item in enumerate(items)}36 37 38def get_colored_text(text: str, color: str) -> str:39 """Get colored text.40 41 Args:42 text: The text to color.43 color: The color to use.44 45 Returns:46 The colored text.47 """48 color_str = _TEXT_COLOR_MAPPING[color]49 return f"\u001b[{color_str}m\033[1;3m{text}\u001b[0m"50 51 52def get_bolded_text(text: str) -> str:53 """Get bolded text.54 55 Args:56 text: The text to bold.57 58 Returns:59 The bolded text.60 """61 return f"\033[1m{text}\033[0m"62 63 64def print_text(65 text: str, color: str | None = None, end: str = "", file: TextIO | None = None66) -> None:67 """Print text with highlighting and no end characters.68 69 If a color is provided, the text will be printed in that color.70 71 If a file is provided, the text will be written to that file.72 73 Args:74 text: The text to print.75 color: The color to use.76 end: The end character to use.77 file: The file to write to.78 """79 text_to_print = get_colored_text(text, color) if color else text80 print(text_to_print, end=end, file=file)81 if file:82 file.flush() # ensure all printed content are written to file83 