patchreview.py 9.9 KB

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