|
| 1 | +# Copyright (C) 2020 Sebastian Pipping <sebastian@pipping.org> |
| 2 | +# Licensed under GPL v3 or later |
| 3 | + |
| 4 | +import re |
| 5 | + |
| 6 | +import colorama |
| 7 | + |
| 8 | +_SECTION_COLOR = colorama.Fore.WHITE + colorama.Style.BRIGHT |
| 9 | +_ARGUMENT_COLOR = colorama.Fore.GREEN + colorama.Style.BRIGHT |
| 10 | +_PARAMETER_COLOR = colorama.Fore.GREEN |
| 11 | +_PROG_COLOR = colorama.Fore.CYAN + colorama.Style.BRIGHT |
| 12 | +_URL_COLOR = colorama.Fore.MAGENTA + colorama.Style.BRIGHT |
| 13 | +_RESET_COLOR = colorama.Style.RESET_ALL |
| 14 | + |
| 15 | +_SUBSTITUTIONS = ( |
| 16 | + ('^(.+):$', f'{_SECTION_COLOR}\\1{_RESET_COLOR}:'), |
| 17 | + ('(?<!\\w)(--?[a-z-]+) ([A-Z_]+)', |
| 18 | + f'{_ARGUMENT_COLOR}\\1{_RESET_COLOR} {_PARAMETER_COLOR}\\2{_RESET_COLOR}'), |
| 19 | + ('(?<!\\w)(--?[a-z-]+)', f'{_ARGUMENT_COLOR}\\1{_RESET_COLOR}'), |
| 20 | + ('^(usage): ([^ ]+)\\b', |
| 21 | + f'{_SECTION_COLOR}\\1{_RESET_COLOR}: {_PROG_COLOR}\\2{_RESET_COLOR}'), |
| 22 | + ('(https://[^ ]+[^ .])', f'{_URL_COLOR}\\1{_RESET_COLOR}'), |
| 23 | +) |
| 24 | + |
| 25 | + |
| 26 | +def add_color_to_formatter_class(formatter_class): |
| 27 | + class_name = formatter_class.__name__.replace('Formatter', 'ColorFormatter') |
| 28 | + |
| 29 | + class Class(formatter_class): |
| 30 | + def format_help(self): |
| 31 | + text = super().format_help() |
| 32 | + for pattern, replacement in _SUBSTITUTIONS: |
| 33 | + matcher = re.compile(pattern, flags=re.MULTILINE) |
| 34 | + text = matcher.sub(replacement, text) |
| 35 | + return text |
| 36 | + |
| 37 | + Class.__name__ = class_name |
| 38 | + |
| 39 | + return Class |
0 commit comments