Skip to content
Permalink
Browse files
Colorize help output
  • Loading branch information
hartwork committed Jul 28, 2020
1 parent 9afbcb4 commit 62bd406fba91e831e29663a483bfe7659b4c62f3
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 1 deletion.
@@ -2,6 +2,7 @@
# Licensed under GPL v3 or later

import argparse
import os
import re
import sys
import traceback
@@ -13,6 +14,9 @@
from textwrap import dedent
from typing import List, Set

import colorama

from ._argparse_color import add_color_to_formatter_class
from ._confirm import Confirmation
from ._git import Git
from ._metadata import APP, DESCRIPTION, VERSION
@@ -246,9 +250,15 @@ def _parse_command_line():
Please report bugs at https://github.com/hartwork/{APP}. Thank you!
""")

colorize = 'NO_COLOR' not in os.environ
formatter_class = RawDescriptionHelpFormatter
if colorize:
colorama.init()
formatter_class = add_color_to_formatter_class(formatter_class)

parser = argparse.ArgumentParser(prog='git-delete-merged-branches', add_help=False,
description=DESCRIPTION, epilog=_EPILOG,
formatter_class=RawDescriptionHelpFormatter)
formatter_class=formatter_class)

modes = parser.add_argument_group('modes').add_mutually_exclusive_group()
modes.add_argument('--configure', dest='force_reconfiguration', action='store_true',
@@ -0,0 +1,39 @@
# Copyright (C) 2020 Sebastian Pipping <sebastian@pipping.org>
# Licensed under GPL v3 or later

import re

import colorama

_SECTION_COLOR = colorama.Fore.WHITE + colorama.Style.BRIGHT
_ARGUMENT_COLOR = colorama.Fore.GREEN + colorama.Style.BRIGHT
_PARAMETER_COLOR = colorama.Fore.GREEN
_PROG_COLOR = colorama.Fore.CYAN + colorama.Style.BRIGHT
_URL_COLOR = colorama.Fore.MAGENTA + colorama.Style.BRIGHT
_RESET_COLOR = colorama.Style.RESET_ALL

_SUBSTITUTIONS = (
('^(.+):$', f'{_SECTION_COLOR}\\1{_RESET_COLOR}:'),
('(?<!\\w)(--?[a-z-]+) ([A-Z_]+)',
f'{_ARGUMENT_COLOR}\\1{_RESET_COLOR} {_PARAMETER_COLOR}\\2{_RESET_COLOR}'),
('(?<!\\w)(--?[a-z-]+)', f'{_ARGUMENT_COLOR}\\1{_RESET_COLOR}'),
('^(usage): ([^ ]+)\\b',
f'{_SECTION_COLOR}\\1{_RESET_COLOR}: {_PROG_COLOR}\\2{_RESET_COLOR}'),
('(https://[^ ]+[^ .])', f'{_URL_COLOR}\\1{_RESET_COLOR}'),
)


def add_color_to_formatter_class(formatter_class):
class_name = formatter_class.__name__.replace('Formatter', 'ColorFormatter')

class Class(formatter_class):
def format_help(self):
text = super().format_help()
for pattern, replacement in _SUBSTITUTIONS:
matcher = re.compile(pattern, flags=re.MULTILINE)
text = matcher.sub(replacement, text)
return text

Class.__name__ = class_name

return Class

0 comments on commit 62bd406

Please sign in to comment.