CheatSheets helpers added to the CheatSheets class, including pretty_print. display_sheet method also added which cleans up the argparse logic.

This commit is contained in:
blackguest 2013-11-01 08:36:17 -05:00
parent e651de5dde
commit 2683ebe99a
1 changed files with 58 additions and 56 deletions

112
cheat
View File

@ -42,25 +42,6 @@ if os.name == 'posix' and 'CHEATCOLORS' in os.environ:
pass pass
def pretty_print(filename):
"""Applies syntax highlighting to a cheatsheet and writes it to stdout"""
try:
if os.path.splitext(filename)[1]:
lexer = get_lexer_for_filename(filename)
else:
# shell is a sensible default when there is no extension
lexer = get_lexer_for_filename(filename + '.sh')
except ClassNotFound:
lexer = TextLexer()
with open(filename) as istream:
code = istream.read()
fmt = TerminalFormatter()
highlight(code, lexer, fmt, sys.stdout)
class CheatSheets(object): class CheatSheets(object):
dirs = None dirs = None
@ -77,7 +58,7 @@ class CheatSheets(object):
def __cheat_directories(self): def __cheat_directories(self):
"""Assembles a list of directories containing cheatsheets.""" """Assembles a list of directories containing cheatsheets."""
default_directories = [DEFAULT_CHEAT_DIR] default_directories = [DEFAULT_CHEAT_DIR, ]
try: try:
import cheatsheets import cheatsheets
default_directories.append(cheatsheets.cheat_dir) default_directories.append(cheatsheets.cheat_dir)
@ -104,7 +85,7 @@ class CheatSheets(object):
return cheats return cheats
def edit(self, cheat): def edit(self, cheat):
"""Creates or edits a cheatsheet""" """Creates or edits a cheatsheet."""
# Assert that the EDITOR environment variable is set and that at least 3 # Assert that the EDITOR environment variable is set and that at least 3
# arguments have been given # arguments have been given
@ -144,42 +125,50 @@ class CheatSheets(object):
exit(1) exit(1)
def list(self): def list(self):
"""Lists the cheatsheets that are currently available""" """Lists the cheatsheets that are currently available."""
max_command = max([len(x) for x in self.sheets.keys()]) + 3 max_command = max([len(x) for x in self.sheets.keys()]) + 3
return ('\n'.join(sorted(['%s [%s]' % (key.ljust(max_command), value) return ('\n'.join(sorted(['%s [%s]' % (key.ljust(max_command), value)
for key, value in self.sheets.items()]))) for key, value in self.sheets.items()])))
def display_sheet(self, sheet):
"""Display a single sheet."""
filepath = os.path.join(self.sheets[sheet], sheet)
if self.is_vim_crypted(filepath):
self.vim_view(filepath)
elif USE_PYGMENTS:
self.pretty_print(filepath)
else:
with open(filepath) as istream:
for l in istream:
sys.stdout.write(l)
# Custom action for argparse def pretty_print(self, filepath):
class ListDirectories(argparse.Action): """Applies syntax highlighting to a cheatsheet and writes it to
"""List cheat directories and exit""" stdout."""
def __call__(self, parser, namespace, values, option_string=None): try:
print('\n'.join(sheets.dirs)) if os.path.splitext(filepath)[1]:
parser.exit() lexer = get_lexer_for_filename(filepath)
else:
# shell is a sensible default when there is no extension
lexer = get_lexer_for_filename(filepath + '.sh')
except ClassNotFound:
lexer = TextLexer()
class ListCheatsheets(argparse.Action): with open(filepath) as istream:
"""List cheatsheets and exit""" code = istream.read()
def __call__(self, parser, namespace, values, option_string=None):
print sheets.list()
parser.exit()
fmt = TerminalFormatter()
highlight(code, lexer, fmt, sys.stdout)
class EditSheet(argparse.Action): def is_vim_crypted(self, filepath):
"""If the user wants to edit a cheatsheet""" """Helper method that returns True if the canonical file path is a Vim
def __call__(self, parser, namespace, values, option_string=None): Encrypted file."""
sheets.edit(values[0])
parser.exit()
def is_vim_crypted(filepath):
"""Returns True if the canonical file path is a Vim Encrypted file."""
canonical_path = os.path.realpath(filepath) canonical_path = os.path.realpath(filepath)
return 'vim encrypted' in magic.from_file(canonical_path).lower() return 'vim encrypted' in magic.from_file(canonical_path).lower()
def vim_view(self, filepath):
def vim_viewer(filepath): """Use Vim to read an Vim Encrypted file."""
"""Use Vim to read an Vim Encrypted cheat file."""
canonical_path = os.path.realpath(filepath) canonical_path = os.path.realpath(filepath)
env_cmd = '/usr/bin/env' env_cmd = '/usr/bin/env'
if not os.path.isfile(env_cmd): if not os.path.isfile(env_cmd):
@ -193,6 +182,28 @@ def vim_viewer(filepath):
exit(1) exit(1)
# Custom action for argparse
class ListDirectories(argparse.Action):
"""List cheat directories and exit."""
def __call__(self, parser, namespace, values, option_string=None):
print('\n'.join(sheets.dirs))
parser.exit()
class ListCheatsheets(argparse.Action):
"""List cheatsheets and exit."""
def __call__(self, parser, namespace, values, option_string=None):
print sheets.list()
parser.exit()
class EditSheet(argparse.Action):
"""If the user wants to edit a cheatsheet."""
def __call__(self, parser, namespace, values, option_string=None):
sheets.edit(values[0])
parser.exit()
def main(): def main():
global sheets global sheets
@ -243,16 +254,7 @@ def main():
if not sheet or sheet in ['help', 'cheat']: if not sheet or sheet in ['help', 'cheat']:
parser.print_help() parser.print_help()
elif sheet in sheets.sheets: elif sheet in sheets.sheets:
filename = os.path.join(sheets.sheets[sheet], sheet) sheets.display_sheet(sheet)
if is_vim_crypted(filename):
vim_viewer(filename)
elif USE_PYGMENTS:
pretty_print(filename)
else:
with open(filename) as istream:
for l in istream:
sys.stdout.write(l)
# if it does not, say so # if it does not, say so
else: else:
print >> sys.stderr, ('No cheatsheet found for %s.' % sheet) print >> sys.stderr, ('No cheatsheet found for %s.' % sheet)