2014-09-14 00:09:40 +02:00
|
|
|
from __future__ import print_function
|
2014-04-27 05:31:13 +02:00
|
|
|
import os
|
|
|
|
import sys
|
2016-10-12 22:16:26 +02:00
|
|
|
import subprocess
|
2014-04-27 05:31:13 +02:00
|
|
|
|
|
|
|
|
|
|
|
def colorize(sheet_content):
|
|
|
|
""" Colorizes cheatsheet content if so configured """
|
|
|
|
|
|
|
|
# only colorize if so configured
|
|
|
|
if not 'CHEATCOLORS' in os.environ:
|
|
|
|
return sheet_content
|
|
|
|
|
|
|
|
try:
|
|
|
|
from pygments import highlight
|
2015-12-02 13:47:13 +01:00
|
|
|
from pygments.lexers import get_lexer_by_name
|
2014-04-27 05:31:13 +02:00
|
|
|
from pygments.formatters import TerminalFormatter
|
|
|
|
|
|
|
|
# if pygments can't load, just return the uncolorized text
|
|
|
|
except ImportError:
|
|
|
|
return sheet_content
|
|
|
|
|
2018-02-24 17:52:17 +01:00
|
|
|
# GMFTBY add
|
|
|
|
if sheet_content == '' :
|
|
|
|
# can not find the content about the term
|
|
|
|
die('Can not find the content !')
|
|
|
|
return
|
|
|
|
|
2015-12-02 13:47:13 +01:00
|
|
|
first_line = sheet_content.splitlines()[0]
|
2017-03-01 00:59:27 +01:00
|
|
|
lexer = get_lexer_by_name('bash')
|
2015-12-02 13:47:13 +01:00
|
|
|
if first_line.startswith('```'):
|
2017-03-01 00:59:27 +01:00
|
|
|
sheet_content = '\n'.join(sheet_content.split('\n')[1:-2])
|
2015-12-02 13:47:13 +01:00
|
|
|
try:
|
|
|
|
lexer = get_lexer_by_name(first_line[3:])
|
|
|
|
except Exception:
|
|
|
|
pass
|
|
|
|
|
|
|
|
return highlight(sheet_content, lexer, TerminalFormatter())
|
2014-04-27 05:31:13 +02:00
|
|
|
|
|
|
|
|
|
|
|
def die(message):
|
|
|
|
""" Prints a message to stderr and then terminates """
|
2014-05-26 05:05:26 +02:00
|
|
|
warn(message)
|
2014-04-27 05:31:13 +02:00
|
|
|
exit(1)
|
|
|
|
|
|
|
|
|
|
|
|
def editor():
|
|
|
|
""" Determines the user's preferred editor """
|
|
|
|
|
2016-10-01 19:55:50 +02:00
|
|
|
# determine which editor to use
|
|
|
|
editor = os.environ.get('CHEAT_EDITOR') \
|
|
|
|
or os.environ.get('VISUAL') \
|
|
|
|
or os.environ.get('EDITOR') \
|
|
|
|
or False
|
|
|
|
|
|
|
|
# assert that the editor is set
|
|
|
|
if editor == False:
|
2014-04-27 05:31:13 +02:00
|
|
|
die(
|
2016-10-01 19:55:50 +02:00
|
|
|
'You must set a CHEAT_EDITOR, VISUAL, or EDITOR environment '
|
|
|
|
'variable in order to create/edit a cheatsheet.'
|
2014-04-27 05:31:13 +02:00
|
|
|
)
|
|
|
|
|
2016-10-01 19:55:50 +02:00
|
|
|
return editor
|
2014-04-27 05:31:13 +02:00
|
|
|
|
2016-10-12 22:16:26 +02:00
|
|
|
|
|
|
|
def open_with_editor(filepath):
|
|
|
|
""" Open `filepath` using the EDITOR specified by the environment variables """
|
|
|
|
editor_cmd = editor().split()
|
|
|
|
try:
|
|
|
|
subprocess.call(editor_cmd + [filepath])
|
|
|
|
except OSError:
|
|
|
|
die('Could not launch ' + editor())
|
|
|
|
|
|
|
|
|
2014-04-27 05:31:13 +02:00
|
|
|
def warn(message):
|
|
|
|
""" Prints a message to stderr """
|
2014-09-14 00:09:40 +02:00
|
|
|
print((message), file=sys.stderr)
|