Skip to contentSkip to conversation

scripts/layer-overview: improve layer detection

PATCH Applied Ross Burton 2 participants 7 messages Jan 19, 2022 – Jan 20, 2022

lore
Share & tools
lore
#0 lore raw

PATCH 1/6 scripts/layer-overview: improve layer detection

Refactor the script somewhat, and detect whether the starting directory is a single layer, or a collection of layers.

---
 scripts/layer-overview.py | 60 ++++++++++++++++++++++++++-------------
 1 file changed, 41 insertions(+), 19 deletions(-)
scripts/layer-overview.py +41 -19
index 24a9a5b6..326470e6 100755
@@ -6,31 +6,24 @@ Print an overview of the layer to help writing release notes.
 Output includes sublayers, machines, recipes.
 """
 
+import argparse
+import sys
+
 # TODO:
 # - More human-readable output
 # - Diff mode, give two revisions and list the changes
-# - Support finding no sublayers, meaning the path is a single layer
-
-import argparse
-parser = argparse.ArgumentParser()
-parser.add_argument("repository")
-parser.add_argument("revision", nargs="?")
-args = parser.parse_args()
 
-if args.revision:
-    import gitpathlib
-    base = gitpathlib.GitPath(args.repository, args.revision)
-else:
-    import pathlib
-    base = pathlib.Path(args.repository)
+def is_layer(path):
+    """
+    Determine if this path looks like a layer (is a directory and contains conf/layer.conf).
+    """
+    return path.is_dir() and (path / "conf" / "layer.conf").exists()
 
-print("Sub-Layers")
-sublayers = sorted(p for p in base.glob("meta-*") if p.is_dir())
-for l in sublayers:
-    print(f" {l.name}")
-print()
 
-for layer in sublayers:
+def print_layer(layer):
+    """
+    Print a summary of the layer.
+    """
     print(layer.name)
 
     machines = sorted(p for p in layer.glob("conf/machine/*.conf"))
@@ -50,3 +43,32 @@ for layer in sublayers:
             else:
                 print(f"  {r.stem}")
         print()
+
+
+parser = argparse.ArgumentParser()
+parser.add_argument("repository")
+parser.add_argument("revision", nargs="?")
+args = parser.parse_args()
+
+if args.revision:
+    import gitpathlib
+    base = gitpathlib.GitPath(args.repository, args.revision)
+else:
+    import pathlib
+    base = pathlib.Path(args.repository)
+
+if is_layer(base):
+    print_layer(base)
+else:
+    sublayers = sorted(p for p in base.glob("meta-*") if is_layer(p))
+    if sublayers:
+        print("Sub-Layers")
+        for l in sublayers:
+            print(f" {l.name}")
+        print()
+
+        for layer in sublayers:
+            print_layer(layer)
+    else:
+        print(f"No layers found in {base}", file=sys.stderr)
+        sys.exit(1)
Signature · 1 line
2.25.1
#1 lore raw

PATCH 2/6 scripts/machine-summary: harvest more patch data

Instead of just putting whether there are patches or not into the context, store the list of patches, the layer they came from, and the upstream status.

---
 scripts/machine-summary.py | 30 ++++++++++++++++++++++++++----
 1 file changed, 26 insertions(+), 4 deletions(-)
scripts/machine-summary.py +26 -4
index 7d2eb53f..e0c7870d 100755
@@ -1,9 +1,10 @@
 #! /usr/bin/env python3
 
-import os
-import sys
 import argparse
 import datetime
+import os
+import re
+import sys
 
 import jinja2
 
@@ -42,8 +43,28 @@ def layer_path(layername, d):
             return path
     return None
 
+def extract_patch_info(src_uri, d):
+    """
+    Parse the specified patch entry from a SRC_URI and return (base name, layer name, status) tuple
+    """
+    import bb.fetch, bb.utils
+
+    info = {}
+    localpath = bb.fetch.decodeurl(src_uri)[2]
+    info["name"] = os.path.basename(localpath)
+    info["layer"] = bb.utils.get_file_layer(localpath, d)
+
+    status = "Unknown"
+    with open(localpath, errors="ignore") as f:
+        m = re.search(r"^[\t ]*Upstream[-_ ]Status:?[\t ]*(\w*)", f.read(), re.IGNORECASE | re.MULTILINE)
+        if m:
+            # TODO: validate
+            status = m.group(1)
+    info["status"] = status
+    return info
+
 def harvest_data(machines, recipes):
-    import bb.tinfoil, bb.utils
+    import bb.tinfoil
     with bb.tinfoil.Tinfoil() as tinfoil:
         tinfoil.prepare(config_only=True)
         corepath = layer_path("core", tinfoil.config_data)
@@ -83,7 +104,8 @@ def harvest_data(machines, recipes):
                 details = versions[machine][recipe] = {}
                 details["recipe"] = d.getVar("PN")
                 details["version"] = trim_pv(d.getVar("PV"))
-                details["patched"] = bool(oe.patch.src_patches(d))
+                details["patches"] = [extract_patch_info(p, d) for p in oe.patch.src_patches(d)]
+                details["patched"] = bool(details["patches"])
 
     # Now backfill the upstream versions
     for machine in versions:
Signature · 1 line
2.25.1
#2 lore raw

PATCH 3/6 scripts/machine-summary: refactor output to classes

In reply to Ross Burton

To prepare for future expansion, refactor the output code to be delegated to Format subclasses.

---
 scripts/machine-summary.py | 75 +++++++++++++++++++++++++++-----------
 1 file changed, 53 insertions(+), 22 deletions(-)
scripts/machine-summary.py +53 -22
index e0c7870d..e5161440 100755
@@ -3,28 +3,12 @@
 import argparse
 import datetime
 import os
+import pathlib
 import re
 import sys
 
 import jinja2
 
-def get_template(name):
-    template_dir = os.path.dirname(os.path.abspath(__file__))
-    env = jinja2.Environment(
-        loader=jinja2.FileSystemLoader(template_dir),
-        autoescape=jinja2.select_autoescape(),
-        trim_blocks=True,
-        lstrip_blocks=True
-    )
-    def is_old(version, upstream):
-        if "+git" in version:
-            # strip +git and see if this is a post-release snapshot
-            version = version.replace("+git", "")
-        return version != upstream
-    env.tests["old"] = is_old
-
-    return env.get_template(f"machine-summary-{name}.jinja")
-
 def trim_pv(pv):
     """
     Strip anything after +git from the PV
@@ -126,19 +110,66 @@ recipes = ("virtual/kernel",
            "gcc-aarch64-none-elf-native",
            "gcc-arm-none-eabi-native")
 
+
+class Format:
+    """
+    The name of this format
+    """
+    name = None
+    """
+    Registry of names to classes
+    """
+    registry = {}
+
+    def __init_subclass__(cls, **kwargs):
+        super().__init_subclass__(**kwargs)
+        assert cls.name
+        cls.registry[cls.name] = cls
+
+    @classmethod
+    def get_format(cls, name):
+        return cls.registry[name]()
+
+    def render(self, context, output: pathlib.Path):
+        # Default implementation for convenience
+        with open(output, "wt") as f:
+            f.write(self.get_template(f"machine-summary-{self.name}.jinja").render(context))
+
+    def get_template(self, name):
+        template_dir = os.path.dirname(os.path.abspath(__file__))
+        env = jinja2.Environment(
+            loader=jinja2.FileSystemLoader(template_dir),
+            autoescape=jinja2.select_autoescape(),
+            trim_blocks=True,
+            lstrip_blocks=True
+        )
+        def is_old(version, upstream):
+            if "+git" in version:
+                # strip +git and see if this is a post-release snapshot
+                version = version.replace("+git", "")
+            return version != upstream
+        env.tests["old"] = is_old
+
+        return env.get_template(name)
+
+class TextOverview(Format):
+    name = "overview.txt"
+
+class HtmlUpdates(Format):
+    name = "updates.html"
+
 if __name__ == "__main__":
     parser = argparse.ArgumentParser(description="machine-summary")
     parser.add_argument("machines", nargs="+", help="machine names", metavar="MACHINE")
-    parser.add_argument("-t", "--template", required=True)
-    parser.add_argument("-o", "--output", required=True, type=argparse.FileType('w', encoding='UTF-8'))
+    parser.add_argument("-t", "--type", required=True, choices=Format.registry.keys())
+    parser.add_argument("-o", "--output", type=pathlib.Path, required=True)
     args = parser.parse_args()
 
-    template = get_template(args.template)
-
     context = {}
     # TODO: include git describe for meta-arm
     context["timestamp"] = str(datetime.datetime.now().strftime("%c"))
     context["recipes"] = sorted(recipes)
     context["releases"], context["data"] = harvest_data(args.machines, recipes)
 
-    args.output.write(template.render(context))
+    formatter = Format.get_format(args.type)
+    formatter.render(context, args.output)
Signature · 1 line
2.25.1
#3 lore raw

PATCH 4/6 scripts/machine-summary: put more version information into the context

In reply to Ross Burton

As well as storing the truncated PV, also store the original PV and whether the recipe needs updating, to avoid the templates needing to do that logic.

---
 scripts/machine-summary.py | 15 +++++++++++++--
 1 file changed, 13 insertions(+), 2 deletions(-)
scripts/machine-summary.py +13 -2
index e5161440..2fef8491 100755
@@ -15,6 +15,15 @@ def trim_pv(pv):
     """
     return "".join(pv.partition("+git")[:2])
 
+def needs_update(version, upstream):
+    """
+    Do a dumb comparison to determine if the version needs to be updated.
+    """
+    if "+git" in version:
+        # strip +git and see if this is a post-release snapshot
+        version = version.replace("+git", "")
+    return version != upstream
+
 def layer_path(layername, d):
     """
     Return the path to the specified layer, or None if the layer isn't present.
@@ -88,14 +97,16 @@ def harvest_data(machines, recipes):
                 details = versions[machine][recipe] = {}
                 details["recipe"] = d.getVar("PN")
                 details["version"] = trim_pv(d.getVar("PV"))
+                details["fullversion"] = d.getVar("PV")
                 details["patches"] = [extract_patch_info(p, d) for p in oe.patch.src_patches(d)]
                 details["patched"] = bool(details["patches"])
 
     # Now backfill the upstream versions
     for machine in versions:
         for recipe in versions[machine]:
-            versions[machine][recipe]["upstream"] = upstreams[recipe]
-
+            data = versions[machine][recipe]
+            data["upstream"] = upstreams[recipe]
+            data["needs_update"] = needs_update(data["version"], data["upstream"])
     return upstreams, versions
 
 # TODO can this be inferred from the list of recipes in the layer
Signature · 1 line
2.25.1
#4 lore raw

PATCH 5/6 scripts/machine-summary: write per-machine reports with more details

In reply to Ross Burton

Rename the updates.html format to just 'report'.

This report has the existing overview as the index.html, and then per-machine files are written with the patch breakdown.

---
 scripts/machine-summary-updates.html.jinja | 47 -----------------
 scripts/machine-summary.py                 | 21 +++++++-
 scripts/report-base.html.jinja             | 35 +++++++++++++
 scripts/report-details.html.jinja          | 61 ++++++++++++++++++++++
 scripts/report-index.html.jinja            | 44 ++++++++++++++++
 5 files changed, 160 insertions(+), 48 deletions(-)
 delete mode 100644 scripts/machine-summary-updates.html.jinja
 create mode 100644 scripts/report-base.html.jinja
 create mode 100644 scripts/report-details.html.jinja
 create mode 100644 scripts/report-index.html.jinja
scripts/machine-summary-updates.html.jinja deleted +0 -47
deleted file mode 100644
index d3ac2ff6..00000000
@@ -1,47 +0,0 @@
-<!DOCTYPE html>
-<html>
-  <head>
-    <title>Pending Machine Upgrades Report</title>
-    <meta name="viewport" content="width=device-width, initial-scale=1">
-    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/css/bulma.min.css">
-  </head>
-  <body>
-    <section class="section">
-      <div class="content">
-        <h1 class="title">Pending Machine Upgrades Report</h1>
-        <p>Generated at {{ timestamp }}.</p>
-      </div>
-
-      <table class="table is-striped">
-        <thead>
-          <tr>
-            <th>Machine</th>
-            {% for recipe in recipes|sort %}
-            <th>{{ recipe }} ({{releases[recipe]|default("?")}})</th>
-            {% endfor %}
-          </tr>
-        </thead>
-        <tbody>
-          {% for machine, data in data|dictsort %}
-          <tr>
-            <th>{{ machine }}</th>
-            {% for recipe in recipes|sort %}
-              {% if recipe in data %}
-                {% set details = data[recipe] %}
-                {% set is_old = details.version is old(details.upstream) %}
-                <td class="{% if is_old %}has-text-weight-bold{% endif %}">
-                {{ details.recipe if details.recipe != recipe}}
-                {{ details.version }}
-                {{ "(patched)" if details.patched }}
-                </td>
-              {% else %}
-                <td>-</td>
-              {% endif %}
-            {% endfor %}
-          </tr>
-          {% endfor %}
-        </tbody>
-      </table>
-    </section>
-  </body>
-</html>
scripts/machine-summary.py +20 -1
index 2fef8491..1f98f247 100755
@@ -167,7 +167,26 @@ class TextOverview(Format):
     name = "overview.txt"
 
 class HtmlUpdates(Format):
-    name = "updates.html"
+    name = "report"
+
+    def render(self, context, output: pathlib.Path):
+        if output.exists() and not output.is_dir():
+            print(f"{output} is not a directory", file=sys.stderr)
+            sys.exit(1)
+
+        if not output.exists():
+            output.mkdir(parents=True)
+
+        with open(output / "index.html", "wt") as f:
+            f.write(self.get_template(f"report-index.html.jinja").render(context))
+
+        subcontext = context.copy()
+        del subcontext["data"]
+        for machine, subdata in context["data"].items():
+            subcontext["machine"] = machine
+            subcontext["data"] = subdata
+            with open(output / f"{machine}.html", "wt") as f:
+                f.write(self.get_template(f"report-details.html.jinja").render(subcontext))
 
 if __name__ == "__main__":
     parser = argparse.ArgumentParser(description="machine-summary")
scripts/report-base.html.jinja new file +35 -0
new file mode 100644
index 00000000..be081251
@@ -0,0 +1,35 @@
+<!DOCTYPE html>
+<html>
+  <head>
+    <title>{% block title %}{% endblock %}</title>
+    <meta name="viewport" content="width=device-width, initial-scale=1">
+    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/css/bulma.min.css">
+  </head>
+  <body>
+    <section class="section">
+      {# TODO use position: sticky to glue this to the top #}
+      <nav class="breadcrumb is-large">
+        <ul>
+          <li class="{{ "is-active" if machine is undefined }}">
+            <a href="index.html">Recipe Report</a>
+          </li>
+          {% if machine is defined %}
+          <li class="is-active">
+            <a href="#">{{machine}}</a>
+          </li>
+          {% endif %}
+        </ul>
+      </nav>
+
+      <div class="content">
+        {% block content %}{% endblock %}
+      </div>
+    </section>
+
+    <footer class="footer">
+      <div class="content has-text-centered">
+        Generated by <code>machine-summary</code> at {{ timestamp }}.
+      </div>
+    </footer>
+  </body>
+</html>
scripts/report-details.html.jinja new file +61 -0

61 lines not on this page · raw message

scripts/report-index.html.jinja new file +44 -0

44 lines not on this page · raw message

Signature · 1 line
2.25.1
#5 lore raw

PATCH 6/6 CI: update for changes to machine-summary

In reply to Ross Burton
---
 .gitlab-ci.yml | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)
.gitlab-ci.yml +4 -2
index bec61400..266e0868 100644
@@ -86,9 +86,11 @@ pending-updates:
   extends: .setup
   artifacts:
     paths:
-      - update-report.html
+      - update-report
   script:
-    - kas shell ci/qemuarm64.yml:ci/meta-openembedded.yml -c "$CI_PROJECT_DIR/scripts/machine-summary.py -t updates.html -o $CI_PROJECT_DIR/update-report.html $($CI_PROJECT_DIR/ci/listmachines.py meta-arm meta-arm-bsp)"
+    - rm -fr update-report
+    - kas shell ci/qemuarm64.yml:ci/meta-openembedded.yml --command \
+      "$CI_PROJECT_DIR/scripts/machine-summary.py -t report -o $CI_PROJECT_DIR/update-report $($CI_PROJECT_DIR/ci/listmachines.py meta-arm meta-arm-bsp)"
   # Do this on x86 whilst the compilers are x86-only
   tags:
     - x86_64
Signature · 1 line
2.25.1
Applied
#6 lore raw
In reply to Ross Burton
Quoted 2 lines · Ross Burton

Refactor the script somewhat, and detect whether the starting directory is a single layer, or a collection of layers.

Applied, thanks!

[1/6] scripts/layer-overview: improve layer detection

      commit: 02350369574cdcea2091048a04468ee515c7d711
[2/6] scripts/machine-summary: harvest more patch data
      commit: cb29175ab4c9a68e26b66aceb97463b32b3639c9
[3/6] scripts/machine-summary: refactor output to classes
      commit: 0d2d0fd69102cadb4e699fa41402227f60e56b69
[4/6] scripts/machine-summary: put more version information into the context
      commit: b1b0f37da7f4c670216de4225af024560e97248e
[5/6] scripts/machine-summary: write per-machine reports with more details
      commit: c4b34740cfc78485d22453d9bc284adc12216dcd
[6/6] CI: update for changes to machine-summary
      commit: aaac0541658b6d6e655662d53dcd27e5cd1bf018

Best regards,

Signature · 1 line
Jon Mason <[email protected]>