1#!/usr/bin/env python 2import sys 3import itertools 4import termcolor 5 6def parse(line): 7 left = line[0:line.find('=')].strip() 8 right = line[line.find('=')+1:].strip('\'"\n ') 9 try: 10 cmd = next(part for part in right.split() if len([char for char in '=<>' if char in part])==0) 11 except StopIteration: 12 cmd = right 13 return (left, right, cmd) 14 15def cheatsheet(lines): 16 exps = [ parse(line) for line in lines ] 17 cheatsheet = {'_default': []} 18 for key, group in itertools.groupby(exps, lambda exp:exp[2]): 19 group_list = [ item for item in group ] 20 if len(group_list)==1: 21 target_aliases = cheatsheet['_default'] 22 else: 23 if key not in cheatsheet: 24 cheatsheet[key] = [] 25 target_aliases = cheatsheet[key] 26 target_aliases.extend(group_list) 27 return cheatsheet 28 29def pretty_print_group(key, aliases, highlight=None): 30 if len(aliases) == 0: 31 return 32 group_hl_formatter = lambda g, hl: termcolor.colored(hl, 'yellow').join([termcolor.colored(part, 'red') for part in ('[%s]' % g).split(hl)]) 33 alias_hl_formatter = lambda alias, hl: termcolor.colored(hl, 'yellow').join([termcolor.colored(part, 'green') for part in ('\t%s = %s' % alias[0:2]).split(hl)]) 34 group_formatter = lambda g: termcolor.colored('[%s]' % g, 'red') 35 alias_formatter = lambda alias: termcolor.colored('\t%s = %s' % alias[0:2], 'green') 36 if highlight and len(highlight)>0: 37 print (group_hl_formatter(key, highlight)) 38 print ('\n'.join([alias_hl_formatter(alias, highlight) for alias in aliases])) 39 else: 40 print (group_formatter(key)) 41 print ('\n'.join([alias_formatter(alias) for alias in aliases])) 42 print ('') 43 44def pretty_print(cheatsheet, wfilter): 45 sorted_key = sorted(cheatsheet.keys()) 46 for key in sorted_key: 47 aliases = cheatsheet.get(key) 48 if not wfilter: 49 pretty_print_group(key, aliases, wfilter) 50 else: 51 pretty_print_group(key, [ alias for alias in aliases if alias[0].find(wfilter)>-1 or alias[1].find(wfilter)>-1], wfilter) 52 53if __name__ == '__main__': 54 lines = sys.stdin.readlines() 55 pretty_print(cheatsheet(lines), sys.argv[1] if len(sys.argv)>1 else None) 56