metrics.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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", "ENABLE_GCC_WARNINGS", "ENABLE_GCC_WARNING", "DUMMY_TYPECHECK_INSTANCE",
  25. "DISABLE_GCC_WARNING", "DISABLE_GCC_WARNINGS"}
  26. in_function = False
  27. found_openbrace = False
  28. for lineno, line in enumerate(f):
  29. if not in_function:
  30. # find the start of a function
  31. m = re.match(r'^([a-zA-Z_][a-zA-Z_0-9]*),?\(', line)
  32. if m:
  33. func_name = m.group(1)
  34. if func_name in REGEXP_CONFUSE_TERMS:
  35. continue
  36. func_start = lineno
  37. in_function = True
  38. elif not found_openbrace and line.startswith("{"):
  39. found_openbrace = True
  40. func_start = lineno
  41. else:
  42. # Find the end of a function
  43. if line.startswith("}"):
  44. n_lines = lineno - func_start + 1
  45. in_function = False
  46. found_openbrace = False
  47. yield (func_name, n_lines)