Skip to contentSkip to conversation

scripts/patchreview: rework patch detection

PATCH In review [email protected] 2 participants 4 messages Oct 27, 2023 – Nov 2, 2023

lore
Share & tools
lore
#0 lore raw

PATCH 1/3 scripts/patchreview: rework patch detection

From: Ross Burton <[email protected]>

A previous patch[1] added the ability to allow the search pattern for patches to be changed, so that patchreview can be used across the entire meta-oe repository by changing the patterns.

However, this means the caller needs to write long patterns when calling patchreview.

Instead, we can see if the specified directory contains a layer by checking if conf/layer.conf exists. If it does, then search for patches inside this directory. If it doesn't, assume that the specified directory is a repository that contains sublayers (such as meta-openembedded) and look through each of the directories that match the pattern meta-*.

This means patchreview can both scan either a single layer (eg .../poky/meta) or a repository of sublayers (eg .../meta-openembedded).

[1] oe-core 599046ea9302af0cf856d3fcd827f6a2be75b7e1

---
 scripts/contrib/patchreview.py | 36 +++++++++++++++++++++++++---------
 1 file changed, 27 insertions(+), 9 deletions(-)
scripts/contrib/patchreview.py +27 -9
index 43de105adc2..af66e32e02e 100755
@@ -41,7 +41,7 @@ def blame_patch(patch):
                                     "--format=%s (%aN <%aE>)",
                                     "--", patch)).decode("utf-8").splitlines()
 
-def patchreview(path, patches):
+def patchreview(patches):
     import re, os.path
 
     # General pattern: start of line, optional whitespace, tag with optional
@@ -56,11 +56,10 @@ def patchreview(path, patches):
 
     for patch in patches:
 
-        fullpath = os.path.join(path, patch)
         result = Result()
-        results[fullpath] = result
+        results[patch] = result
 
-        content = open(fullpath, encoding='ascii', errors='ignore').read()
+        content = open(patch, encoding='ascii', errors='ignore').read()
 
         # Find the Signed-off-by tag
         match = sob_re.search(content)
@@ -198,21 +197,40 @@ def histogram(results):
     for k in bars:
         print("%-20s %s (%d)" % (k.capitalize() if k else "No status", bars[k], counts[k]))
 
+def gather_patches(candidate):
+    # candidate can either be the path to a layer directly (eg meta-intel), or a
+    # repository that contains other layers (meta-arm). We can determine what by
+    # looking for a conf/layer.conf file. If that file exists then it's a layer,
+    # otherwise its a repository of layers and we can assume they're called
+    # meta-*.
+
+    if (candidate / "conf" / "layer.conf").exists():
+        print(f"{candidate} is a layer")
+        scan = [candidate]
+    else:
+        print(f"{candidate} is not a layer, checking for sub-layers")
+        scan = [d for d in candidate.iterdir() if d.is_dir() and (d.name == "meta" or d.name.startswith("meta-"))]
+        print(f"Found layers {' '.join((d.name for d in scan))}")
+
+    patches = []
+    for directory in scan:
+        filenames = subprocess.check_output(("git", "-C", directory, "ls-files", "recipes-*/**/*.patch", "recipes-*/**/*.diff"), universal_newlines=True).split()
+        patches += [os.path.join(directory, f) for f in filenames]
+    return patches
 
 if __name__ == "__main__":
-    import argparse, subprocess, os
+    import argparse, subprocess, os, pathlib
 
     args = argparse.ArgumentParser(description="Patch Review Tool")
     args.add_argument("-b", "--blame", action="store_true", help="show blame for malformed patches")
     args.add_argument("-v", "--verbose", action="store_true", help="show per-patch results")
     args.add_argument("-g", "--histogram", action="store_true", help="show patch histogram")
     args.add_argument("-j", "--json", help="update JSON")
-    args.add_argument("-p", "--pattern", nargs=1, action="extend", default=["recipes-*/**/*.patch", "recipes-*/**/*.diff"], help="pattern to search recipes patch")
-    args.add_argument("directory", help="directory to scan")
+    args.add_argument("directory", type=pathlib.Path, metavar="DIRECTORY", help="directory to scan (layer, or repository of layers)")
     args = args.parse_args()
 
-    patches = subprocess.check_output(("git", "-C", args.directory, "ls-files") + tuple(args.pattern)).decode("utf-8").split()
-    results = patchreview(args.directory, patches)
+    patches = gather_patches(args.directory)
+    results = patchreview(patches)
     analyse(results, want_blame=args.blame, verbose=args.verbose)
 
     if args.json:
Signature · 1 line
2.34.1
#1 lore raw

PATCH 2/3 scripts/contrib/patchreview: add commit and recipe count fields to JSON

From: Ross Burton <[email protected]>

The autobuilder scripts post-process the generated JSON to inject recipe and commit counts into the data. We can do this easily in patchreview instead.

---
 scripts/contrib/patchreview.py | 32 ++++++++++++++++++++++----------
 1 file changed, 22 insertions(+), 10 deletions(-)
scripts/contrib/patchreview.py +22 -10
index af66e32e02e..36038d06d2e 100755
@@ -197,7 +197,7 @@ def histogram(results):
     for k in bars:
         print("%-20s %s (%d)" % (k.capitalize() if k else "No status", bars[k], counts[k]))
 
-def gather_patches(candidate):
+def find_layers(candidate):
     # candidate can either be the path to a layer directly (eg meta-intel), or a
     # repository that contains other layers (meta-arm). We can determine what by
     # looking for a conf/layer.conf file. If that file exists then it's a layer,
@@ -205,19 +205,26 @@ def gather_patches(candidate):
     # meta-*.
 
     if (candidate / "conf" / "layer.conf").exists():
-        print(f"{candidate} is a layer")
-        scan = [candidate]
+        return [candidate.absolute()]
     else:
-        print(f"{candidate} is not a layer, checking for sub-layers")
-        scan = [d for d in candidate.iterdir() if d.is_dir() and (d.name == "meta" or d.name.startswith("meta-"))]
-        print(f"Found layers {' '.join((d.name for d in scan))}")
+        return [d.absolute() for d in candidate.iterdir() if d.is_dir() and (d.name == "meta" or d.name.startswith("meta-"))]
 
+# TODO these don't actually handle dynamic-layers/
+
+def gather_patches(layers):
     patches = []
-    for directory in scan:
+    for directory in layers:
         filenames = subprocess.check_output(("git", "-C", directory, "ls-files", "recipes-*/**/*.patch", "recipes-*/**/*.diff"), universal_newlines=True).split()
         patches += [os.path.join(directory, f) for f in filenames]
     return patches
 
+def count_recipes(layers):
+    count = 0
+    for directory in layers:
+        output = subprocess.check_output(["git", "-C", directory, "ls-files", "recipes-*/**/*.bb"], universal_newlines=True)
+        count += len(output.splitlines())
+    return count
+
 if __name__ == "__main__":
     import argparse, subprocess, os, pathlib
 
@@ -229,7 +236,9 @@ if __name__ == "__main__":
     args.add_argument("directory", type=pathlib.Path, metavar="DIRECTORY", help="directory to scan (layer, or repository of layers)")
     args = args.parse_args()
 
-    patches = gather_patches(args.directory)
+    layers = find_layers(args.directory)
+    print(f"Found layers {' '.join((d.name for d in layers))}")
+    patches = gather_patches(layers)
     results = patchreview(patches)
     analyse(results, want_blame=args.blame, verbose=args.verbose)
 
@@ -242,8 +251,11 @@ if __name__ == "__main__":
 
         row = collections.Counter()
         row["total"] = len(results)
-        row["date"] = subprocess.check_output(["git", "-C", args.directory, "show", "-s", "--pretty=format:%cd", "--date=format:%s"]).decode("utf-8").strip()
-        row["commit"] = subprocess.check_output(["git", "-C", args.directory, "show", "-s", "--pretty=format:%H"]).decode("utf-8").strip()
+        row["date"] = subprocess.check_output(["git", "-C", args.directory, "show", "-s", "--pretty=format:%cd", "--date=format:%s"], universal_newlines=True).strip()
+        row["commit"] = subprocess.check_output(["git", "-C", args.directory, "show-ref", "--hash", "HEAD"], universal_newlines=True).strip()
+        row['commit_count'] = subprocess.check_output(["git", "-C", args.directory, "rev-list", "--count", "HEAD"], universal_newlines=True).strip()
+        row['recipe_count'] = count_recipes(layers)
+
         for r in results.values():
             if r.upstream_status in status_values:
                 row[r.upstream_status] += 1
Signature · 1 line
2.34.1
#2 lore raw

PATCH 3/3 scripts/contrib/patchreview: consolidate imports

In reply to [email protected]

From: Ross Burton <[email protected]>

Move most imports to the top of the file.

---
 scripts/contrib/patchreview.py | 15 ++++++++++-----
 1 file changed, 10 insertions(+), 5 deletions(-)
scripts/contrib/patchreview.py +10 -5
index 36038d06d2e..f95cadab0c6 100755
@@ -5,6 +5,15 @@
 # SPDX-License-Identifier: GPL-2.0-only
 #
 
+import argparse
+import collections
+import json
+import os
+import os.path
+import pathlib
+import re
+import subprocess
+
 # TODO
 # - option to just list all broken files
 # - test suite
@@ -35,14 +44,12 @@ def blame_patch(patch):
     From a patch filename, return a list of "commit summary (author name <author
     email>)" strings representing the history.
     """
-    import subprocess
     return subprocess.check_output(("git", "log",
                                     "--follow", "--find-renames", "--diff-filter=A",
                                     "--format=%s (%aN <%aE>)",
                                     "--", patch)).decode("utf-8").splitlines()
 
 def patchreview(patches):
-    import re, os.path
 
     # General pattern: start of line, optional whitespace, tag with optional
     # hyphen or spaces, maybe a colon, some whitespace, then the value, all case
@@ -192,6 +199,7 @@ Patches in Pending state: %s""" % (total_patches,
 def histogram(results):
     from toolz import recipes, dicttoolz
     import math
+
     counts = recipes.countby(lambda r: r.upstream_status, results.values())
     bars = dicttoolz.valmap(lambda v: "#" * int(math.ceil(float(v) / len(results) * 100)), counts)
     for k in bars:
@@ -226,8 +234,6 @@ def count_recipes(layers):
     return count
 
 if __name__ == "__main__":
-    import argparse, subprocess, os, pathlib
-
     args = argparse.ArgumentParser(description="Patch Review Tool")
     args.add_argument("-b", "--blame", action="store_true", help="show blame for malformed patches")
     args.add_argument("-v", "--verbose", action="store_true", help="show per-patch results")
@@ -243,7 +249,6 @@ if __name__ == "__main__":
     analyse(results, want_blame=args.blame, verbose=args.verbose)
 
     if args.json:
-        import json, os.path, collections
         if os.path.isfile(args.json):
             data = json.load(open(args.json))
         else:
Signature · 1 line
2.34.1
#3 lore raw
In reply to [email protected]

Hi Ross,

Quoted 54 lines · Ross Burton via lists.openembedded.org

From: Ross Burton <[email protected]>

A previous patch[1] added the ability to allow the search pattern for patches to be changed, so that patchreview can be used across the entire meta-oe repository by changing the patterns.

However, this means the caller needs to write long patterns when calling patchreview.

Instead, we can see if the specified directory contains a layer by checking if conf/layer.conf exists. If it does, then search for patches inside this directory. If it doesn't, assume that the specified directory is a repository that contains sublayers (such as meta-openembedded) and look through each of the directories that match the pattern meta-*.

This means patchreview can both scan either a single layer (eg .../poky/meta) or a repository of sublayers (eg .../meta-openembedded).

[1] oe-core 599046ea9302af0cf856d3fcd827f6a2be75b7e1

---
  scripts/contrib/patchreview.py | 36 +++++++++++++++++++++++++---------
  1 file changed, 27 insertions(+), 9 deletions(-)
scripts/contrib/patchreview.py +3 -4
index 43de105adc2..af66e32e02e 100755
@@ -41,7 +41,7 @@ def blame_patch(patch):
                                      "--format=%s (%aN <%aE>)",
                                      "--", patch)).decode("utf-8").splitlines()
 
-def patchreview(path, patches):
+def patchreview(patches):
      import re, os.path
 
      # General pattern: start of line, optional whitespace, tag with optional
@@ -56,11 +56,10 @@ def patchreview(path, patches):
 
      for patch in patches:
 
-        fullpath = os.path.join(path, patch)
          result = Result()
-        results[fullpath] = result
+        results[patch] = result
 
-        content = open(fullpath, encoding='ascii', errors='ignore').read()
+        content = open(patch, encoding='ascii', errors='ignore').read()
 
          # Find the Signed-off-by tag
          match = sob_re.search(content)

scripts/contrib/patchreview.py def histogram(results): · line 206

Quoted 10 lines
scripts/contrib/patchreview.py +7 -0
@@ -198,21 +197,40 @@ def histogram(results):
      for k in bars:
          print("%-20s %s (%d)" % (k.capitalize() if k else "No status", bars[k], counts[k]))
 
+def gather_patches(candidate):
+    # candidate can either be the path to a layer directly (eg meta-intel), or a
+    # repository that contains other layers (meta-arm). We can determine what by
+    # looking for a conf/layer.conf file. If that file exists then it's a layer,
+    # otherwise its a repository of layers and we can assume they're called
+    # meta-*.
+

Maybe mention that this expects a pathlib.Path object?

scripts/contrib/patchreview.py def histogram(results): · line 214

Quoted 8 lines
scripts/contrib/patchreview.py +8 -0
+    if (candidate / "conf" / "layer.conf").exists():
+        print(f"{candidate} is a layer")
+        scan = [candidate]
+    else:
+        print(f"{candidate} is not a layer, checking for sub-layers")
+        scan = [d for d in candidate.iterdir() if d.is_dir() and (d.name == "meta" or d.name.startswith("meta-"))]
+        print(f"Found layers {' '.join((d.name for d in scan))}")
+

What about just looking for all layer.conf files recursively instead?

e.g.:

scan = [l.parents[1].name for l in candidate.glob('**/conf/layer.conf')

This assumes a layer root directory is the parent of conf directory in which a layer.conf file is, which I think is a good assumption.

But this does not make any assumption that the layer should be prefixed with meta- or be meta, as opposed to the current implementation.

scripts/contrib/patchreview.py def histogram(results): · line 217

Quoted 3 lines
scripts/contrib/patchreview.py +3 -0
+    patches = []
+    for directory in scan:
+        filenames = subprocess.check_output(("git", "-C", directory, "ls-files", "recipes-*/**/*.patch", "recipes-*/**/*.diff"), universal_newlines=True).split()

FWIW, recipes- prefix is NOT enforced, it is derived from BBFILES variable in each layer.conf. (I have used layers where a typo was there, with recipe- or sometimes just recipes/). I am not saying we need to support those, but just merely raising this as a potential shortcoming.

Cheers,
Quentin