| 1 | import io |
| 2 | import os |
| 3 | import sys |
| 4 | |
| 5 | COLORIZE = True |
| 6 | |
| 7 | |
| 8 | class ANSIColors: |
| 9 | BOLD_GREEN = "\x1b[1;32m" |
| 10 | BOLD_MAGENTA = "\x1b[1;35m" |
| 11 | BOLD_RED = "\x1b[1;31m" |
| 12 | GREEN = "\x1b[32m" |
| 13 | GREY = "\x1b[90m" |
| 14 | MAGENTA = "\x1b[35m" |
| 15 | RED = "\x1b[31m" |
| 16 | RESET = "\x1b[0m" |
| 17 | YELLOW = "\x1b[33m" |
| 18 | |
| 19 | |
| 20 | NoColors = ANSIColors() |
| 21 | |
| 22 | for attr in dir(NoColors): |
| 23 | if not attr.startswith("__"): |
| 24 | setattr(NoColors, attr, "") |
| 25 | |
| 26 | |
| 27 | def get_colors(colorize: bool = False) -> ANSIColors: |
| 28 | if colorize or can_colorize(): |
| 29 | return ANSIColors() |
| 30 | else: |
| 31 | return NoColors |
| 32 | |
| 33 | |
| 34 | def can_colorize() -> bool: |
| 35 | if sys.platform == "win32": |
| 36 | try: |
| 37 | import nt |
| 38 | |
| 39 | if not nt._supports_virtual_terminal(): |
| 40 | return False |
| 41 | except (ImportError, AttributeError): |
| 42 | return False |
| 43 | if not sys.flags.ignore_environment: |
| 44 | if os.environ.get("PYTHON_COLORS") == "0": |
| 45 | return False |
| 46 | if os.environ.get("PYTHON_COLORS") == "1": |
| 47 | return True |
| 48 | if "NO_COLOR" in os.environ: |
| 49 | return False |
| 50 | if not COLORIZE: |
| 51 | return False |
| 52 | if not sys.flags.ignore_environment: |
| 53 | if "FORCE_COLOR" in os.environ: |
| 54 | return True |
| 55 | if os.environ.get("TERM") == "dumb": |
| 56 | return False |
| 57 | |
| 58 | if not hasattr(sys.stderr, "fileno"): |
| 59 | return False |
| 60 | |
| 61 | try: |
| 62 | return os.isatty(sys.stderr.fileno()) |
| 63 | except io.UnsupportedOperation: |
| 64 | return sys.stderr.isatty() |