practracker.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. #!/usr/bin/python
  2. """
  3. Best-practices tracker for Tor source code.
  4. Go through the various .c files and collect metrics about them. If the metrics
  5. violate some of our best practices and they are not found in the optional
  6. exceptions file, then log a problem about them.
  7. We currently do metrics about file size, function size and number of includes.
  8. practracker.py should be run with its second argument pointing to the Tor
  9. top-level source directory like this:
  10. $ python3 ./scripts/maint/practracker/practracker.py .
  11. To regenerate the exceptions file so that it allows all current
  12. problems in the Tor source, use the --regen flag:
  13. $ python3 --regen ./scripts/maint/practracker/practracker.py .
  14. """
  15. from __future__ import print_function
  16. import os, sys
  17. import metrics
  18. import util
  19. import problem
  20. # The filename of the exceptions file (it should be placed in the practracker directory)
  21. EXCEPTIONS_FNAME = "./exceptions.txt"
  22. # Recommended file size
  23. MAX_FILE_SIZE = 3000 # lines
  24. # Recommended function size
  25. MAX_FUNCTION_SIZE = 100 # lines
  26. # Recommended number of #includes
  27. MAX_INCLUDE_COUNT = 50
  28. # Map from problem type to functions that adjust for tolerance
  29. TOLERANCE_FNS = {
  30. 'include-count': lambda n: int(n*1.1),
  31. 'function-size': lambda n: int(n*1.1),
  32. 'file-size': lambda n: int(n*1.02)
  33. }
  34. #######################################################
  35. # The Tor source code topdir
  36. TOR_TOPDIR = None
  37. #######################################################
  38. if sys.version_info[0] <= 2:
  39. def open_file(fname):
  40. return open(fname, 'r')
  41. else:
  42. def open_file(fname):
  43. return open(fname, 'r', encoding='utf-8')
  44. def consider_file_size(fname, f):
  45. """Consider the size of 'f' and yield an FileSizeItem for it.
  46. """
  47. file_size = metrics.get_file_len(f)
  48. yield problem.FileSizeItem(fname, file_size)
  49. def consider_includes(fname, f):
  50. """Consider the #include count in for 'f' and yield an IncludeCountItem
  51. for it.
  52. """
  53. include_count = metrics.get_include_count(f)
  54. yield problem.IncludeCountItem(fname, include_count)
  55. def consider_function_size(fname, f):
  56. """yield a FunctionSizeItem for every function in f.
  57. """
  58. for name, lines in metrics.get_function_lines(f):
  59. canonical_function_name = "%s:%s()" % (fname, name)
  60. yield problem.FunctionSizeItem(canonical_function_name, lines)
  61. #######################################################
  62. def consider_all_metrics(files_list):
  63. """Consider metrics for all files, and yield a sequence of problem.Item
  64. object for those issues."""
  65. for fname in files_list:
  66. with open_file(fname) as f:
  67. for item in consider_metrics_for_file(fname, f):
  68. yield item
  69. def consider_metrics_for_file(fname, f):
  70. """
  71. Yield a sequence of problem.Item objects for all of the metrics in
  72. 'f'.
  73. """
  74. # Strip the useless part of the path
  75. if fname.startswith(TOR_TOPDIR):
  76. fname = fname[len(TOR_TOPDIR):]
  77. # Get file length
  78. for item in consider_file_size(fname, f):
  79. yield item
  80. # Consider number of #includes
  81. f.seek(0)
  82. for item in consider_includes(fname, f):
  83. yield item
  84. # Get function length
  85. f.seek(0)
  86. for item in consider_function_size(fname, f):
  87. yield item
  88. HEADER="""\
  89. # Welcome to the exceptions file for Tor's best-practices tracker!
  90. #
  91. # Each line of this file represents a single violation of Tor's best
  92. # practices -- typically, a violation that we had before practracker.py
  93. # first existed.
  94. #
  95. # There are three kinds of problems that we recognize right now:
  96. # function-size -- a function of more than {MAX_FUNCTION_SIZE} lines.
  97. # file-size -- a file of more than {MAX_FILE_SIZE} lines.
  98. # include-count -- a file with more than {MAX_INCLUDE_COUNT} #includes.
  99. #
  100. # Each line below represents a single exception that practracker should
  101. # _ignore_. Each line has four parts:
  102. # 1. The word "problem".
  103. # 2. The kind of problem.
  104. # 3. The location of the problem: either a filename, or a
  105. # filename:functionname pair.
  106. # 4. The magnitude of the problem to ignore.
  107. #
  108. # So for example, consider this line:
  109. # problem file-size /src/core/or/connection_or.c 3200
  110. #
  111. # It tells practracker to allow the mentioned file to be up to 3200 lines
  112. # long, even though ordinarily it would warn about any file with more than
  113. # {MAX_FILE_SIZE} lines.
  114. #
  115. # You can either edit this file by hand, or regenerate it completely by
  116. # running `make practracker-regen`.
  117. #
  118. # Remember: It is better to fix the problem than to add a new exception!
  119. """.format(**globals())
  120. def main(argv):
  121. import argparse
  122. progname = argv[0]
  123. parser = argparse.ArgumentParser(prog=progname)
  124. parser.add_argument("--regen", action="store_true",
  125. help="Regenerate the exceptions file")
  126. parser.add_argument("--list-overbroad", action="store_true",
  127. help="List over-strict exceptions")
  128. parser.add_argument("--exceptions",
  129. help="Override the location for the exceptions file")
  130. parser.add_argument("--strict", action="store_true",
  131. help="Make all warnings into errors")
  132. parser.add_argument("--terse", action="store_true",
  133. help="Do not emit helpful instructions.")
  134. parser.add_argument("--max-file-size", default=MAX_FILE_SIZE,
  135. help="Maximum lines per C file size")
  136. parser.add_argument("--max-include-count", default=MAX_INCLUDE_COUNT,
  137. help="Maximum includes per C file")
  138. parser.add_argument("--max-function-size", default=MAX_FUNCTION_SIZE,
  139. help="Maximum lines per function")
  140. parser.add_argument("topdir", default=".", nargs="?",
  141. help="Top-level directory for the tor source")
  142. args = parser.parse_args(argv[1:])
  143. global TOR_TOPDIR
  144. TOR_TOPDIR = args.topdir
  145. if args.exceptions:
  146. exceptions_file = args.exceptions
  147. else:
  148. exceptions_file = os.path.join(TOR_TOPDIR, "scripts/maint/practracker", EXCEPTIONS_FNAME)
  149. # 0) Configure our thresholds of "what is a problem actually"
  150. filt = problem.ProblemFilter()
  151. filt.addThreshold(problem.FileSizeItem("*", int(args.max_file_size)))
  152. filt.addThreshold(problem.IncludeCountItem("*", int(args.max_include_count)))
  153. filt.addThreshold(problem.FunctionSizeItem("*", int(args.max_function_size)))
  154. # 1) Get all the .c files we care about
  155. files_list = util.get_tor_c_files(TOR_TOPDIR)
  156. # 2) Initialize problem vault and load an optional exceptions file so that
  157. # we don't warn about the past
  158. if args.regen:
  159. tmpname = exceptions_file + ".tmp"
  160. tmpfile = open(tmpname, "w")
  161. problem_file = tmpfile
  162. ProblemVault = problem.ProblemVault()
  163. else:
  164. ProblemVault = problem.ProblemVault(exceptions_file)
  165. problem_file = sys.stdout
  166. # 2.1) Adjust the exceptions so that we warn only about small problems,
  167. # and produce errors on big ones.
  168. if not (args.regen or args.list_overbroad or args.strict):
  169. ProblemVault.set_tolerances(TOLERANCE_FNS)
  170. # 3) Go through all the files and report problems if they are not exceptions
  171. found_new_issues = 0
  172. for item in filt.filter(consider_all_metrics(files_list)):
  173. status = ProblemVault.register_problem(item)
  174. if status == problem.STATUS_ERR:
  175. print(item, file=problem_file)
  176. found_new_issues += 1
  177. elif status == problem.STATUS_WARN:
  178. # warnings always go to stdout.
  179. print("(warning) {}".format(item))
  180. if args.regen:
  181. tmpfile.close()
  182. os.rename(tmpname, exceptions_file)
  183. sys.exit(0)
  184. # If new issues were found, try to give out some advice to the developer on how to resolve it.
  185. if found_new_issues and not args.regen and not args.terse:
  186. new_issues_str = """\
  187. FAILURE: practracker found {} new problem(s) in the code: see warnings above.
  188. Please fix the problems if you can, and update the exceptions file
  189. ({}) if you can't.
  190. See doc/HACKING/HelpfulTools.md for more information on using practracker.\
  191. You can disable this message by setting the TOR_DISABLE_PRACTRACKER environment
  192. variable.
  193. """.format(found_new_issues, exceptions_file)
  194. print(new_issues_str)
  195. if args.list_overbroad:
  196. def k_fn(tup):
  197. return tup[0].key()
  198. for (ex,p) in sorted(ProblemVault.list_overbroad_exceptions(), key=k_fn):
  199. if p is None:
  200. print(ex, "->", 0)
  201. else:
  202. print(ex, "->", p.metric_value)
  203. sys.exit(found_new_issues)
  204. if __name__ == '__main__':
  205. if os.environ.get("TOR_DISABLE_PRACTRACKER"):
  206. sys.exit(0)
  207. main(sys.argv)