metrics.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #!/usr/bin/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. import re
  6. def get_file_len(f):
  7. """Get file length of file"""
  8. for i, l in enumerate(f):
  9. pass
  10. return i + 1
  11. def get_include_count(f):
  12. """Get number of #include statements in the file"""
  13. include_count = 0
  14. for line in f:
  15. if re.match(r'\s*#\s*include', line):
  16. include_count += 1
  17. return include_count
  18. def get_function_lines(f):
  19. """
  20. Return iterator which iterates over functions and returns (function name, function lines)
  21. """
  22. # Skip lines that look like they are defining functions with these
  23. # names: they aren't real function definitions.
  24. REGEXP_CONFUSE_TERMS = {"MOCK_IMPL", "MOCK_DECL", "HANDLE_DECL",
  25. "ENABLE_GCC_WARNINGS", "ENABLE_GCC_WARNING",
  26. "DUMMY_TYPECHECK_INSTANCE",
  27. "DISABLE_GCC_WARNING", "DISABLE_GCC_WARNINGS"}
  28. in_function = False
  29. found_openbrace = False
  30. for lineno, line in enumerate(f):
  31. if not in_function:
  32. # find the start of a function
  33. m = re.match(r'^([a-zA-Z_][a-zA-Z_0-9]*),?\(', line)
  34. if m:
  35. func_name = m.group(1)
  36. if func_name in REGEXP_CONFUSE_TERMS:
  37. continue
  38. func_start = lineno
  39. in_function = True
  40. elif not found_openbrace and line.startswith("{"):
  41. found_openbrace = True
  42. func_start = lineno
  43. else:
  44. # Find the end of a function
  45. if line.startswith("}"):
  46. n_lines = lineno - func_start + 1
  47. in_function = False
  48. found_openbrace = False
  49. yield (func_name, n_lines)