Util logic simplification

- Simplified the logic regarding checking the state of `CHEATCOLORS` in
  `cheat/utils.py`

- Improved the commenting within the same
This commit is contained in:
Chris Lane 2019-01-11 15:54:20 -05:00
parent e1fdca231e
commit 7c7278ac8b

View File

@ -4,38 +4,41 @@ import subprocess
import sys import sys
def highlight(needle, haystack): def highlight(needle, haystack):
""" Highlights a search term matched in a line """ """ Highlights a search term matched within a line """
# only colorize if so configured # if colorization is not configured, exit early
if not 'CHEATCOLORS' in os.environ or os.environ.get('CHEATCOLORS') != 'true': if os.environ.get('CHEATCOLORS') != 'true':
return sheet_content return sheet_content
# otherwise, attempt to import the termcolor library
try: try:
from termcolor import colored from termcolor import colored
# if pygments can't load, just return the uncolorized text # if the import fails, return uncolored text
except ImportError: except ImportError:
return haystack return haystack
# colorize the search term, and replace it within the surrounding line # if the import succeeds, colorize the needle in haystack
return haystack.replace(needle, colored(needle, 'blue')); return haystack.replace(needle, colored(needle, 'blue'));
def colorize(sheet_content): def colorize(sheet_content):
""" Colorizes cheatsheet content if so configured """ """ Colorizes cheatsheet content if so configured """
# only colorize if so configured # if colorization is not configured, exit early
if not 'CHEATCOLORS' in os.environ or os.environ.get('CHEATCOLORS') != 'true': if os.environ.get('CHEATCOLORS') != 'true':
return sheet_content return sheet_content
# otherwise, attempt to import the pygments library
try: try:
from pygments import highlight from pygments import highlight
from pygments.lexers import get_lexer_by_name from pygments.lexers import get_lexer_by_name
from pygments.formatters import TerminalFormatter from pygments.formatters import TerminalFormatter
# if pygments can't load, just return the uncolorized text # if the import fails, return uncolored text
except ImportError: except ImportError:
return sheet_content return sheet_content
# otherwise, attempt to colorize
first_line = sheet_content.splitlines()[0] first_line = sheet_content.splitlines()[0]
lexer = get_lexer_by_name('bash') lexer = get_lexer_by_name('bash')
if first_line.startswith('```'): if first_line.startswith('```'):