cheatsheet.py 2.2 KB

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