patchreview.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. #! /usr/bin/env python3
  2. # TODO
  3. # - option to just list all broken files
  4. # - test suite
  5. # - validate signed-off-by
  6. class Result:
  7. # Whether the patch has an Upstream-Status or not
  8. missing_upstream_status = False
  9. # If the Upstream-Status tag is malformed in some way (string for bad bit)
  10. malformed_upstream_status = None
  11. # If the Upstream-Status value is unknown (boolean)
  12. unknown_upstream_status = False
  13. # The upstream status value (Pending, etc)
  14. upstream_status = None
  15. # Whether the patch has a Signed-off-by or not
  16. missing_sob = False
  17. # Whether the Signed-off-by tag is malformed in some way
  18. malformed_sob = False
  19. # The Signed-off-by tag value
  20. sob = None
  21. # Whether a patch looks like a CVE but doesn't have a CVE tag
  22. missing_cve = False
  23. def blame_patch(patch):
  24. """
  25. From a patch filename, return a list of "commit summary (author name <author
  26. email>)" strings representing the history.
  27. """
  28. import subprocess
  29. return subprocess.check_output(("git", "log",
  30. "--follow", "--find-renames", "--diff-filter=A",
  31. "--format=%s (%aN <%aE>)",
  32. "--", patch)).decode("utf-8").splitlines()
  33. def patchreview(patches):
  34. import re
  35. # General pattern: start of line, optional whitespace, tag with optional
  36. # hyphen or spaces, maybe a colon, some whitespace, then the value, all case
  37. # insensitive.
  38. sob_re = re.compile(r"^[\t ]*(Signed[-_ ]off[-_ ]by:?)[\t ]*(.+)", re.IGNORECASE | re.MULTILINE)
  39. status_re = re.compile(r"^[\t ]*(Upstream[-_ ]Status:?)[\t ]*(\w*)", re.IGNORECASE | re.MULTILINE)
  40. status_values = ("accepted", "pending", "inappropriate", "backport", "submitted", "denied")
  41. cve_tag_re = re.compile(r"^[\t ]*(CVE:)[\t ]*(.*)", re.IGNORECASE | re.MULTILINE)
  42. cve_re = re.compile(r"cve-[0-9]{4}-[0-9]{4,6}", re.IGNORECASE)
  43. results = {}
  44. for patch in patches:
  45. result = Result()
  46. results[patch] = result
  47. content = open(patch, encoding='ascii', errors='ignore').read()
  48. # Find the Signed-off-by tag
  49. match = sob_re.search(content)
  50. if match:
  51. value = match.group(1)
  52. if value != "Signed-off-by:":
  53. result.malformed_sob = value
  54. result.sob = match.group(2)
  55. else:
  56. result.missing_sob = True
  57. # Find the Upstream-Status tag
  58. match = status_re.search(content)
  59. if match:
  60. value = match.group(1)
  61. if value != "Upstream-Status:":
  62. result.malformed_upstream_status = value
  63. value = match.group(2).lower()
  64. # TODO: check case
  65. if value not in status_values:
  66. result.unknown_upstream_status = True
  67. result.upstream_status = value
  68. else:
  69. result.missing_upstream_status = True
  70. # Check that patches which looks like CVEs have CVE tags
  71. if cve_re.search(patch) or cve_re.search(content):
  72. if not cve_tag_re.search(content):
  73. result.missing_cve = True
  74. # TODO: extract CVE list
  75. return results
  76. def analyse(results, want_blame=False, verbose=True):
  77. """
  78. want_blame: display blame data for each malformed patch
  79. verbose: display per-file results instead of just summary
  80. """
  81. # want_blame requires verbose, so disable blame if we're not verbose
  82. if want_blame and not verbose:
  83. want_blame = False
  84. total_patches = 0
  85. missing_sob = 0
  86. malformed_sob = 0
  87. missing_status = 0
  88. malformed_status = 0
  89. missing_cve = 0
  90. pending_patches = 0
  91. for patch in sorted(results):
  92. r = results[patch]
  93. total_patches += 1
  94. need_blame = False
  95. # Build statistics
  96. if r.missing_sob:
  97. missing_sob += 1
  98. if r.malformed_sob:
  99. malformed_sob += 1
  100. if r.missing_upstream_status:
  101. missing_status += 1
  102. if r.malformed_upstream_status or r.unknown_upstream_status:
  103. malformed_status += 1
  104. if r.missing_cve:
  105. missing_cve += 1
  106. if r.upstream_status == "pending":
  107. pending_patches += 1
  108. # Output warnings
  109. if r.missing_sob:
  110. need_blame = True
  111. if verbose:
  112. print("Missing Signed-off-by tag (%s)" % patch)
  113. if r.malformed_sob:
  114. need_blame = True
  115. if verbose:
  116. print("Malformed Signed-off-by '%s' (%s)" % (r.malformed_sob, patch))
  117. if r.missing_cve:
  118. need_blame = True
  119. if verbose:
  120. print("Missing CVE tag (%s)" % patch)
  121. if r.missing_upstream_status:
  122. need_blame = True
  123. if verbose:
  124. print("Missing Upstream-Status tag (%s)" % patch)
  125. if r.malformed_upstream_status:
  126. need_blame = True
  127. if verbose:
  128. print("Malformed Upstream-Status '%s' (%s)" % (r.malformed_upstream_status, patch))
  129. if r.unknown_upstream_status:
  130. need_blame = True
  131. if verbose:
  132. print("Unknown Upstream-Status value '%s' (%s)" % (r.upstream_status, patch))
  133. if want_blame and need_blame:
  134. print("\n".join(blame_patch(patch)) + "\n")
  135. def percent(num):
  136. try:
  137. return "%d (%d%%)" % (num, round(num * 100.0 / total_patches))
  138. except ZeroDivisionError:
  139. return "N/A"
  140. if verbose:
  141. print()
  142. print("""Total patches found: %d
  143. Patches missing Signed-off-by: %s
  144. Patches with malformed Signed-off-by: %s
  145. Patches missing CVE: %s
  146. Patches missing Upstream-Status: %s
  147. Patches with malformed Upstream-Status: %s
  148. Patches in Pending state: %s""" % (total_patches,
  149. percent(missing_sob),
  150. percent(malformed_sob),
  151. percent(missing_cve),
  152. percent(missing_status),
  153. percent(malformed_status),
  154. percent(pending_patches)))
  155. def histogram(results):
  156. from toolz import recipes, dicttoolz
  157. import math
  158. counts = recipes.countby(lambda r: r.upstream_status, results.values())
  159. bars = dicttoolz.valmap(lambda v: "#" * int(math.ceil(float(v) / len(results) * 100)), counts)
  160. for k in bars:
  161. print("%-20s %s (%d)" % (k.capitalize() if k else "No status", bars[k], counts[k]))
  162. if __name__ == "__main__":
  163. import argparse, subprocess, os
  164. args = argparse.ArgumentParser(description="Patch Review Tool")
  165. args.add_argument("-b", "--blame", action="store_true", help="show blame for malformed patches")
  166. args.add_argument("-v", "--verbose", action="store_true", help="show per-patch results")
  167. args.add_argument("-g", "--histogram", action="store_true", help="show patch histogram")
  168. args.add_argument("directory", nargs="?", help="directory to scan")
  169. args = args.parse_args()
  170. if args.directory:
  171. os.chdir(args.directory)
  172. patches = subprocess.check_output(("git", "ls-files", "recipes-*/**/*.patch", "recipes-*/**/*.diff")).decode("utf-8").split()
  173. results = patchreview(patches)
  174. analyse(results, want_blame=args.blame, verbose=args.verbose)
  175. if args.histogram:
  176. print()
  177. histogram(results)