xfstestsdb/xfstestsdb/colors.py

103 lines
3.3 KiB
Python

# Copyright 2023 (c) Anna Schumaker.
"""Color handling functions."""
import os
import termcolor
class ColorScheme:
"""Base class for color scheme handling."""
def __init__(self, name: str) -> None:
"""Initialize a ColorScheme."""
self.name = name
def __getitem__(self, key: str | bool | None) -> None:
"""Get the color for the specific situation."""
return None
def format(self, text: str, color: str | None = None,
bgcolor: str | None = None, bold: bool = False,
dark: bool | str = False) -> str:
"""Format the given text based on the provided attributes."""
on_color = self[bgcolor]
on_color = f"on_{on_color}" if on_color else None
attrs = []
if bold:
attrs.append("bold")
if dark is True or self[dark]:
attrs.append("dark")
return termcolor.colored(text, color=self[color], on_color=on_color,
attrs=attrs)
class DarkScheme(ColorScheme):
"""Dark mode color scheme."""
def __getitem__(self, key: str) -> str | bool | None:
"""Get dark mode colors."""
match key:
case "diff-+": return "green"
case "diff--": return "red"
case "diff-@": return "magenta"
case "diff- ": return "light_grey"
case "fg" | "fg-odd": return "light_grey"
case "fg-even": return "cyan"
case "fg-dark": return False
case "fg-header": return "yellow"
case "fg-passed": return "green"
case "fg-failure": return "red"
case "fg-skipped": return "dark_grey"
case "fg-testcase": return "cyan"
case "table-bg": return "black"
case "table-border": return "dark_grey"
return None
class LightScheme(ColorScheme):
"""Light mode color scheme."""
def __getitem__(self, key: str) -> str | bool | None:
"""Get light mode colors."""
match key:
case "diff-+": return "green"
case "diff--": return "red"
case "diff-@": return "magenta"
case "diff- ": return "light_grey"
case "fg" | "fg-odd": return "dark_grey"
case "fg-even": return "green"
case "fg-dark": return True
case "fg-header": return "blue"
case "fg-passed": return "green"
case "fg-failure": return "red"
case "fg-skipped": return "light_grey"
case "fg-testcase": return "cyan"
case "table-bg": return "white"
case "table-border": return "light_grey"
return None
class NoneScheme(ColorScheme):
"""Color scheme for no colors."""
def format(self, text, *args, **kwargs) -> str:
"""Simply return the text with no formatting."""
return text
def get_default_colors() -> str:
"""Check the environment to determine the default color scheme."""
match os.getenv("XFSTESTSDB_COLORS"):
case "light": return "light"
case "none": return "none"
case _: return "dark"
def get_colors(color_scheme: str) -> ColorScheme:
"""Get the current color scheme."""
match color_scheme:
case "dark": return DarkScheme("dark")
case "light": return LightScheme("light")
case _: return NoneScheme("none")