2013-07-31 04:48:07 +02:00
|
|
|
#!/usr/bin/env python
|
2013-08-11 21:37:11 +02:00
|
|
|
import os
|
2013-07-31 04:48:07 +02:00
|
|
|
import sys
|
2013-08-18 21:53:40 +02:00
|
|
|
import cheatsheets
|
2013-07-31 04:48:07 +02:00
|
|
|
|
2013-08-18 21:53:40 +02:00
|
|
|
def cheat_directories():
|
|
|
|
default = [ default_dir for default_dir in [os.path.expanduser('~/.cheat'), cheatsheets.cheat_dir] if os.path.isdir(default_dir) ]
|
|
|
|
if 'CHEATPATH' in os.environ and os.environ['CHEATPATH']:
|
|
|
|
return [ path for path in os.environ['CHEATPATH'].split(os.pathsep) if os.path.isdir(path) ] + default
|
|
|
|
else:
|
|
|
|
return default
|
2013-08-17 04:16:44 +02:00
|
|
|
|
2013-08-18 21:53:40 +02:00
|
|
|
def cheat_files(cheat_directories):
|
|
|
|
cheats = {}
|
|
|
|
for cheat_dir in reversed(cheat_directories):
|
|
|
|
cheats.update(dict([ (cheat, cheat_dir) for cheat in os.listdir(cheat_dir) if '.' not in cheat ]))
|
|
|
|
return cheats
|
2013-08-10 05:46:34 +02:00
|
|
|
|
2013-07-31 05:25:36 +02:00
|
|
|
# assemble a keyphrase out of all params passed to the script
|
2013-08-16 00:03:58 +02:00
|
|
|
keyphrase = ' '.join(sys.argv[1:])
|
2013-08-18 21:53:40 +02:00
|
|
|
cheat_dirs = cheat_directories()
|
2013-07-31 05:25:36 +02:00
|
|
|
|
2013-08-13 03:59:33 +02:00
|
|
|
# verify that we have at least one cheat directory
|
2013-08-18 21:53:40 +02:00
|
|
|
if not cheat_dirs:
|
2013-08-16 00:03:58 +02:00
|
|
|
print >> sys.stderr, 'The ~/.cheat directory does not exist or the CHEATPATH variable is not set.'
|
|
|
|
exit()
|
2013-08-11 21:37:11 +02:00
|
|
|
|
2013-08-18 21:53:40 +02:00
|
|
|
# list the files in the ~/.cheat directory
|
|
|
|
cheatsheets = cheat_files(cheat_dirs)
|
2013-08-16 04:02:33 +02:00
|
|
|
|
2013-07-31 05:33:31 +02:00
|
|
|
# print help if requested
|
2013-08-16 00:19:02 +02:00
|
|
|
if keyphrase.lower() in ['', 'cheat', 'help', '-h', '-help', '--help']:
|
2013-08-16 10:47:43 +02:00
|
|
|
print "Usage: cheat [keyphrase]\n"
|
|
|
|
print "Available keyphrases:"
|
2013-08-18 21:53:40 +02:00
|
|
|
max_command = max([ len(x) for x in cheatsheets.keys() ]) + 3
|
|
|
|
print '\n'.join(sorted([ '%s [%s]' % (key.ljust(max_command), value) for key, value in cheatsheets.items() ]))
|
2013-08-16 10:47:43 +02:00
|
|
|
exit()
|
2013-07-31 05:25:36 +02:00
|
|
|
|
2013-07-31 05:33:31 +02:00
|
|
|
# print the cheatsheet if it exists
|
2013-08-18 21:53:40 +02:00
|
|
|
if keyphrase in cheatsheets:
|
|
|
|
with open (os.path.join(cheatsheets[keyphrase], keyphrase), 'r') as cheatsheet:
|
|
|
|
print cheatsheet.read()
|
2013-08-11 21:37:11 +02:00
|
|
|
|
2013-08-18 21:53:40 +02:00
|
|
|
# if it does not, say so
|
|
|
|
else:
|
|
|
|
print 'No cheatsheet found for %s.' % keyphrase
|