patchreview.py 8.3 KB

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