8 left = line[0:line.find('=')].strip()
9 right = line[line.find('=')+1:].strip('\'"\n ')
11 cmd = next(part for part in right.split() if len([char for char in '=<>' if char in part])==0)
14 return (left, right, cmd)
16 def cheatsheet(lines):
17 exps = [ parse(line) for line in lines ]
18 cheatsheet = {'_default': []}
19 for key, group in itertools.groupby(exps, lambda exp:exp[2]):
20 group_list = [ item for item in group ]
21 if len(group_list)==1:
22 target_aliases = cheatsheet['_default']
24 if key not in cheatsheet:
26 target_aliases = cheatsheet[key]
27 target_aliases.extend(group_list)
30 def pretty_print_group(key, aliases, highlight=None, only_groupname=False):
33 group_hl_formatter = lambda g, hl: termcolor.colored(hl, 'yellow').join([termcolor.colored(part, 'red') for part in ('[%s]' % g).split(hl)])
34 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)])
35 group_formatter = lambda g: termcolor.colored('[%s]' % g, 'red')
36 alias_formatter = lambda alias: termcolor.colored('\t%s = %s' % alias[0:2], 'green')
37 if highlight and len(highlight)>0:
38 print (group_hl_formatter(key, highlight))
39 if not only_groupname:
40 print ('\n'.join([alias_hl_formatter(alias, highlight) for alias in aliases]))
42 print (group_formatter(key))
43 if not only_groupname:
44 print ('\n'.join([alias_formatter(alias) for alias in aliases]))
47 def pretty_print(cheatsheet, wfilter, group_list=None, groups_only=False):
48 sorted_key = sorted(cheatsheet.keys())
49 for key in sorted_key:
50 if group_list and key not in group_list:
52 aliases = cheatsheet.get(key)
54 pretty_print_group(key, aliases, wfilter, groups_only)
56 pretty_print_group(key, [ alias for alias in aliases if alias[0].find(wfilter)>-1 or alias[1].find(wfilter)>-1], wfilter)
58 if __name__ == '__main__':
59 parser = argparse.ArgumentParser(description="Pretty print aliases.")
60 parser.add_argument('filter', nargs="*", help="search aliases matching string")
61 parser.add_argument('-g', '--group', dest="group_list", action='append', help="only print aliases in given groups")
62 parser.add_argument('--groups', dest='groups_only', action='store_true', help="only print alias groups")
63 args = parser.parse_args()
65 lines = sys.stdin.readlines()
66 group_list = args.group_list or None
67 wfilter = " ".join(args.filter) or None
68 pretty_print(cheatsheet(lines), wfilter, group_list, args.groups_only)