check-events 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  1. #!/usr/bin/env python3
  2. from pprint import pprint
  3. import argparse
  4. import ast
  5. import os
  6. import sys
  7. SOMETHING = '<something>'
  8. parser = argparse.ArgumentParser()
  9. parser.add_argument('--never-handled',
  10. action='store_true', dest='never_handled',
  11. help='mark never handled events')
  12. parser.add_argument('--no-never-handled',
  13. action='store_false', dest='never_handled',
  14. help='do not mark never handled events')
  15. parser.add_argument('directory', metavar='DIRECTORY',
  16. help='directory to search for .py files')
  17. class Event(object):
  18. def __init__(self, events, name):
  19. self.events = events
  20. self.name = name
  21. self.fired = []
  22. self.handled = []
  23. def fire(self, filename, lineno):
  24. self.fired.append((filename, lineno))
  25. def handle(self, filename, lineno):
  26. self.handled.append((filename, lineno))
  27. def print_summary_one(self, stream, attr, colour, never=True):
  28. lines = getattr(self, attr)
  29. if lines:
  30. for filename, lineno in lines:
  31. stream.write(' \033[{}m{}\033[0m {} +{}\n'.format(
  32. colour, attr[0], filename, lineno))
  33. elif never:
  34. stream.write(' \033[1;33mnever {}\033[0m\n'.format(attr))
  35. def print_summary(self, stream, never_handled):
  36. stream.write('\033[1m{}\033[0m\n'.format(self.name))
  37. self.print_summary_one(stream, 'fired', '1;31')
  38. self.print_summary_one(stream, 'handled', '1;32', never=never_handled)
  39. class Events(dict):
  40. def __missing__(self, key):
  41. self[key] = Event(self, key)
  42. return self[key]
  43. class EventVisitor(ast.NodeVisitor):
  44. def __init__(self, events, filename, *args, **kwargs):
  45. super(EventVisitor, self).__init__(*args, **kwargs)
  46. self.events = events
  47. self.filename = filename
  48. def resolve_attr(self, node):
  49. if isinstance(node, ast.Name):
  50. return node.id
  51. if isinstance(node, ast.Attribute):
  52. return '{}.{}'.format(self.resolve_attr(node.value), node.attr)
  53. raise TypeError('resolve_attr() does not support {!r}'.format(node))
  54. def visit_Call(self, node):
  55. try:
  56. name = self.resolve_attr(node.func)
  57. except TypeError:
  58. # name got something else than identifier in the attribute path;
  59. # this may have been 'str'.format() for example; we can't call
  60. # events this way
  61. return
  62. if name.endswith('.fire_event') or name.endswith('.fire_event_async'):
  63. # here we throw events; event name is the first argument; sometimes
  64. # it is expressed as 'event-stem:' + some_variable
  65. eventnode = node.args[0]
  66. if isinstance(eventnode, ast.Str):
  67. event = eventnode.s
  68. elif isinstance(eventnode, ast.BinOp) \
  69. and isinstance(eventnode.left, ast.Str):
  70. event = eventnode.left.s
  71. else:
  72. raise AssertionError('fishy event {!r} in {} +{}'.format(
  73. eventnode, self.filename, node.lineno))
  74. if ':' in event:
  75. event = ':'.join((event.split(':', 1)[0], SOMETHING))
  76. self.events[event].fire(self.filename, node.lineno)
  77. return
  78. if name in ('qubes.events.handler', 'qubes.ext.handler'):
  79. # here we handle; event names (there may be more than one) are all
  80. # positional arguments
  81. if any(isinstance(arg, ast.Starred) for arg in node.args):
  82. raise AssertionError(
  83. 'event handler with *args in {} +{}'.format(
  84. self.filename, node.lineno))
  85. for arg in node.args:
  86. if not isinstance(arg, ast.Str):
  87. raise AssertionError(
  88. 'event handler with non-string arg in {} +{}'.format(
  89. self.filename, node.lineno))
  90. event = arg.s
  91. if ':' in event:
  92. event = ':'.join((event.split(':', 1)[0], SOMETHING))
  93. self.events[event].handle(self.filename, node.lineno)
  94. return
  95. self.generic_visit(node)
  96. return
  97. def main():
  98. args = parser.parse_args()
  99. events = Events()
  100. for dirpath, dirnames, filenames in os.walk(args.directory):
  101. for filename in filenames:
  102. if not filename.endswith('.py'):
  103. continue
  104. filepath = os.path.join(dirpath, filename)
  105. EventVisitor(events, filepath).visit(
  106. ast.parse(open(filepath).read(), filepath))
  107. for event in sorted(events):
  108. events[event].print_summary(
  109. sys.stdout, never_handled=args.never_handled)
  110. if __name__ == '__main__':
  111. main()