metrics.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #!/usr/bin/env python
  2. # Implementation of various source code metrics.
  3. # These are currently ad-hoc string operations and regexps.
  4. # We might want to use a proper static analysis library in the future, if we want to get more advanced metrics.
  5. # Future imports for Python 2.7, mandatory in 3.0
  6. from __future__ import division
  7. from __future__ import print_function
  8. from __future__ import unicode_literals
  9. import re
  10. def get_file_len(f):
  11. """Get file length of file"""
  12. i = -1
  13. for i, l in enumerate(f):
  14. pass
  15. return i + 1
  16. def get_include_count(f):
  17. """Get number of #include statements in the file"""
  18. include_count = 0
  19. for line in f:
  20. if re.match(r'\s*#\s*include', line):
  21. include_count += 1
  22. return include_count
  23. def get_function_lines(f):
  24. """
  25. Return iterator which iterates over functions and returns (function name, function lines)
  26. """
  27. # Skip lines that look like they are defining functions with these
  28. # names: they aren't real function definitions.
  29. REGEXP_CONFUSE_TERMS = {"MOCK_IMPL", "MOCK_DECL", "HANDLE_DECL",
  30. "ENABLE_GCC_WARNINGS", "ENABLE_GCC_WARNING",
  31. "DUMMY_TYPECHECK_INSTANCE",
  32. "DISABLE_GCC_WARNING", "DISABLE_GCC_WARNINGS"}
  33. in_function = False
  34. found_openbrace = False
  35. for lineno, line in enumerate(f):
  36. if not in_function:
  37. # find the start of a function
  38. m = re.match(r'^([a-zA-Z_][a-zA-Z_0-9]*),?\(', line)
  39. if m:
  40. func_name = m.group(1)
  41. if func_name in REGEXP_CONFUSE_TERMS:
  42. continue
  43. func_start = lineno
  44. in_function = True
  45. elif not found_openbrace and line.startswith("{"):
  46. found_openbrace = True
  47. func_start = lineno
  48. else:
  49. # Find the end of a function
  50. if line.startswith("}"):
  51. n_lines = lineno - func_start + 1
  52. in_function = False
  53. found_openbrace = False
  54. yield (func_name, n_lines)