fix except case

- when redirect stdout to pipe but not tty, it throw exception.
- when have no content, it throw exception.
- remove reductant newline at end of file
This commit is contained in:
liuyang1 2018-06-13 18:56:54 +08:00 committed by ly
parent aa1e12625e
commit c0fe871b33
2 changed files with 12 additions and 5 deletions

View File

@ -34,6 +34,7 @@ Examples:
cheat -s ssh cheat -s ssh
""" """
from __future__ import print_function
# require the dependencies # require the dependencies
from cheat import sheets, sheet from cheat import sheets, sheet
from cheat.utils import colorize from cheat.utils import colorize
@ -50,7 +51,7 @@ if __name__ == '__main__':
# list cheatsheets # list cheatsheets
elif options['--list']: elif options['--list']:
print(sheets.list()) print(sheets.list(), end="")
# create/edit cheatsheet # create/edit cheatsheet
elif options['--edit']: elif options['--edit']:
@ -58,8 +59,8 @@ if __name__ == '__main__':
# search among the cheatsheets # search among the cheatsheets
elif options['--search']: elif options['--search']:
print(colorize(sheets.search(options['<keyword>']))) print(colorize(sheets.search(options['<keyword>'])), end="")
# print the cheatsheet # print the cheatsheet
else: else:
print(colorize(sheet.read(options['<cheatsheet>']))) print(colorize(sheet.read(options['<cheatsheet>'])), end="")

View File

@ -10,6 +10,9 @@ def colorize(sheet_content):
# only colorize if so configured # only colorize if so configured
if not 'CHEATCOLORS' in os.environ: if not 'CHEATCOLORS' in os.environ:
return sheet_content return sheet_content
# only colorize if stdout is tty
if not sys.stdout.isatty():
return sheet_content
try: try:
from pygments import highlight from pygments import highlight
@ -20,8 +23,11 @@ def colorize(sheet_content):
except ImportError: except ImportError:
return sheet_content return sheet_content
first_line = sheet_content.splitlines()[0] lines = sheet_content.splitlines()
lexer = get_lexer_by_name('bash') if len(lines) == 0:
return ""
first_line = lines[0]
lexer = get_lexer_by_name('bash')
if first_line.startswith('```'): if first_line.startswith('```'):
sheet_content = '\n'.join(sheet_content.split('\n')[1:-2]) sheet_content = '\n'.join(sheet_content.split('\n')[1:-2])
try: try: