metrics.py 1.9 KB

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