Skip to contentSkip to conversation

upgrade_helper: scarthgap compatibility, stable updates and changelog extraction

PATCH Superseded [email protected] 2 participants 30 messages Apr 24 – Apr 28 1 message not in the archive

v2 of 3 Superseded Latest is v3 →

lore
Share & tools
lore
#0 lore raw

v2 cover upgrade_helper: scarthgap compatibility, stable updates and changelog extraction

From: Daniel Turull <[email protected]>

This patch series allow to run upgrade-helper both in master and scarthgap.

This allows to be able to automatically generate patches for updating patched or minor versions, which can help on the security work fixing vulnerabilities.

It adds also the option to extract the changelog with different strategies

It can also prebuild the recipe to be able to compare before and after the update, so it could be connected with ABI changes with meta-binaryaudit [1], so if there are incompatible changes the upgrade fails.

Example with OE-core scarthgap, there are 156 potential updates

vte: no suitable version available, skipping
########### The list of recipes to be upgraded #############
, libubootenv, 0.3.5, 0.3.7, Stefano Babic <[email protected]>, 1e3511ed77f794ee5decc0974d54c8e5af26f64c
, bind, 9.18.44, 9.18.48, Unassigned <[email protected]>, N/A
, dhcpcd, 10.0.6, 10.0.10, Unassigned <[email protected]>, N/A
, libpcap, 1.10.4, 1.10.6, Anuj Mittal <[email protected]>, N/A
, ppp, 2.5.0, 2.5.2, Hongxu Jia <[email protected]>, N/A
, socat, 1.8.0.0, 1.8.0.3, Hongxu Jia <[email protected]>, N/A
, base-passwd, 3.6.3, 3.6.8, Anuj Mittal <[email protected]>, N/A
, ifupdown, 0.8.41, 0.8.45, Anuj Mittal <[email protected]>, N/A
, libxcrypt-compat, 4.4.36, 4.4.38, Khem Raj <[email protected]>, N/A
, libxcrypt, 4.4.36, 4.4.38, Khem Raj <[email protected]>, N/A
, ovmf, edk2-stable202402, edk2-stable202602, Unassigned <[email protected]>, b7a715f7c03c45c6b4575bf88596bfd79658b8ce , util-linux-libuuid, 2.39.3, 2.39.4, Chen Qi <[email protected]>, N/A
, util-linux, 2.39.3, 2.39.4, Chen Qi <[email protected]>, N/A
...
, numactl, 2.0.18, 2.0.19, Richard Purdie <[email protected]>, 3bc85e37d5a30da6790cb7e8bb488bb8f679170f , taglib, 2.0.1, 2.0.2, Anuj Mittal <[email protected]>, N/A
, utfcpp, 4.0.5, 4.0.9, Anuj Mittal <[email protected]>, 63d64de49fd6b829f7c8694df5ab2ee625cb7134
, xxhash, 0.8.2, 0.8.3, Alexander Kanavin <[email protected]>, e626a72bc2321cd320e953a0ccf1584cad60f363

[...]
############################################################
Building gcc runtimes ...
building gcc runtime for qemux86-64
building gcc runtime for qemuarm_musl
ATTEMPT PACKAGE GROUP 1/156
[...]

Tested with on openembedded-core with latest scarthgap version (2026-04-07) ../auto-upgrade-helper/upgrade-helper.py all --layer-dir ../openembedded-core --changelog --stable --prebuild

    TOTAL: attempted=135 succeeded=81(60.00%) failed=54(40.00%)

Examples of the patches in my contrib branch [2]

[1] https://github.com/Nordix/meta-binaryaudit
[2] https://git.openembedded.org/openembedded-core-contrib/log/?h=dturull/scarthgap-auh

Changes in v2:
- Split scarthgap compat into two commits: compatibility [1/9] and fetch error handling [2/9]
- Fix iterator exhaustion: materialise executor.map() results into a list so a single fetch error no longer silently truncates the scan [2/9]
- Split --stable into its own commit (was squashed into changelog) [5/9]
- Fix --minor help text and docstring to accurately describe behavior (any same-major upgrade); drop version length equality constraint [6/9]
- Fix --prebuild to pass space-separated targets to bitbake instead of comma-joined group name [7/9]
- Fix --resume to match individual recipe names against the skip set instead of the comma-joined group name [8/9]
- Add scan_workers rate limiting to avoid overwhelming upstream servers during version checks (configurable via scan_workers in config) [9/9]
- Reorder commits so each feature is independently functional:
scarthgap compat, layer-dir, changelog, stable, minor, prebuild, resume, scan_workers

Daniel Turull (9):
upgrade-helper.py: Add compatibility with Yocto scarthgap upgrade-helper.py: Handle fetch errors gracefully during version scan upgrade-helper.py: allow to set the git directory from layer-dir upgrade-helper.py: add changelog flag
upgrade-helper.py: Add stable option for patch-only upgrades upgrade-helper.py: Add minor option for minor version upgrades upgrade-helper.py: Add prebuild option
upgrade-helper.py: Add resume option to skip already attempted recipes upgrade-helper.py: Limit number of requests to remote servers

 modules/changelog.py     | 256 +++++++++++++++++++++++++++++++++++++++
 modules/steps.py         |  22 +++-
 modules/utils/bitbake.py |   8 +-
 modules/utils/version.py | 175 ++++++++++++++++++++++++++
 upgrade-helper.py        | 152 ++++++++++++++++++++++-
 5 files changed, 609 insertions(+), 4 deletions(-)
 create mode 100644 modules/changelog.py
 create mode 100644 modules/utils/version.py
Signature · 1 line
2.34.1
#1 lore raw

PATCH v2 1/9 upgrade-helper.py: Add compatibility with Yocto scarthgap

From: Daniel Turull <[email protected]>

- Handle flat tuple format from get_recipe_upgrade_status (scarthgap) in addition to the list-of-dicts format (master)
- Fallback to MACHINE env var when bitbake-config-build is not available
- Resolve symlinks in recipe_dir with os.path.realpath()

Assisted-by Claude, Anthropic
---
 modules/steps.py         | 2 +-
 modules/utils/bitbake.py | 8 ++++++--
 upgrade-helper.py        | 9 +++++++++
 3 files changed, 16 insertions(+), 3 deletions(-)
modules/steps.py +1 -1
index a6ec341..b3ec61c 100644
@@ -36,7 +36,7 @@ def load_env(devtool, bb, git, opts, group):
     os.mkdir(group['workdir'])
     for pkg_ctx in group['pkgs']:
         pkg_ctx['env'] = bb.env(pkg_ctx['PN'])
-        pkg_ctx['recipe_dir'] = os.path.dirname(pkg_ctx['env']['FILE'])
+        pkg_ctx['recipe_dir'] = os.path.realpath(os.path.dirname(pkg_ctx['env']['FILE']))
 
 def buildhistory_init(devtool, bb, git, opts, group):
     if not opts['buildhistory']:
modules/utils/bitbake.py +6 -2
index 5514c98..f6821bc 100644
@@ -123,8 +123,12 @@ class Bitbake(object):
             env = "TCLIBC={}".format(libc)
         else:
             env = ""
-        bb.process.run("bitbake-config-build enable-fragment machine/{}".format(machine))
-        return self._cmd(recipe, env_var=env)
+        try:
+            bb.process.run("bitbake-config-build enable-fragment machine/{}".format(machine))
+        except bb.process.ExecutionError:
+            # bitbake-config-build not available (e.g. scarthgap), use MACHINE env var
+            env = "MACHINE={} {}".format(machine, env).strip()
+        return self._cmd(recipe, env_var=env if env else None)
 
     def dependency_graph(self, package_list):
         return self._cmd(package_list, "-g")
upgrade-helper.py +9 -0
index 40f31c4..aef7ed1 100755
@@ -714,6 +714,15 @@ class UniverseUpdater(Updater):
             pkggroups = oe.recipeutils.get_recipe_upgrade_status(layer_recipes)
 
             for group in pkggroups:
+
+                # Scarthgap returns flat tuples; normalize to list-of-dicts
+                # so the existing loop handles both formats.
+                if not isinstance(group, (list, tuple)) or not group or not isinstance(group[0], dict):
+                    pn, status, cur_ver, next_ver, maintainer, revision, no_upgrade_reason = group
+                    group = [{'pn': pn, 'status': status, 'cur_ver': cur_ver,
+                              'next_ver': next_ver, 'maintainer': maintainer,
+                              'revision': revision, 'no_upgrade_reason': no_upgrade_reason}]
+
                 upgrade_group = []
                 for pkg in group:
                     maintainer = pkg['maintainer']
Signature · 1 line
2.34.1
#2 lore raw

Re: [AUH][PATCH v2 1/9] upgrade-helper.py: Add compatibility with Yocto scarthgap

modules/steps.py def load_env(devtool, bb, git, opts, group): · line 39

Quoted 2 lines · On Fri, 24 Apr 2026 at 13:46, <[email protected]> wrote:
modules/steps.py +1 -1
-        pkg_ctx['recipe_dir'] = os.path.dirname(pkg_ctx['env']['FILE'])
+        pkg_ctx['recipe_dir'] = os.path.realpath(os.path.dirname(pkg_ctx['env']['FILE']))

This needs to be further explained.

modules/utils/bitbake.py class Bitbake(object): · line 131

Quoted 8 lines
modules/utils/bitbake.py +6 -2
-        bb.process.run("bitbake-config-build enable-fragment machine/{}".format(machine))
-        return self._cmd(recipe, env_var=env)
+        try:
+            bb.process.run("bitbake-config-build enable-fragment machine/{}".format(machine))
+        except bb.process.ExecutionError:
+            # bitbake-config-build not available (e.g. scarthgap), use MACHINE env var
+            env = "MACHINE={} {}".format(machine, env).strip()
+        return self._cmd(recipe, env_var=env if env else None)

The condition needs to be 'bitbake-config-build doesn't exist', not that it failed to execute (e.g. returned a non-zero).

upgrade-helper.py class UniverseUpdater(Updater): · line 724

Quoted 9 lines

for group in pkggroups:

upgrade-helper.py +8 -0
+
+                # Scarthgap returns flat tuples; normalize to list-of-dicts
+                # so the existing loop handles both formats.
+                if not isinstance(group, (list, tuple)) or not group or not isinstance(group[0], dict):
+                    pn, status, cur_ver, next_ver, maintainer, revision, no_upgrade_reason = group
+                    group = [{'pn': pn, 'status': status, 'cur_ver': cur_ver,
+                              'next_ver': next_ver, 'maintainer': maintainer,
+                              'revision': revision, 'no_upgrade_reason': no_upgrade_reason}]

Can the condition be inverted, e.g. be checked for the 'old' format? I'm not sure I understand why 'old' format is determined by any of three different conditions being true, especially 'not group' looks incorrect.

Alex

#3 lore raw

RE: [AUH][PATCH v2 1/9] upgrade-helper.py: Add compatibility with Yocto scarthgap

Quoted 10 lines

-----Original Message-----
From: Alexander Kanavin <[email protected]>
Sent: Monday, 27 April 2026 13:02
To: Daniel Turull <[email protected]>
Cc: [email protected]; [email protected]; [email protected]; [email protected]
Subject: Re: [AUH][PATCH v2 1/9] upgrade-helper.py: Add compatibility with Yocto scarthgap

Quoted 6 lines

Review

Quoted 3 lines · On Fri, 24 Apr 2026 at 13:46, <[email protected]> wrote:
(quoted diff) +2 -1
-        pkg_ctx['recipe_dir'] = os.path.dirname(pkg_ctx['env']['FILE'])
+        pkg_ctx['recipe_dir'] =
+ os.path.realpath(os.path.dirname(pkg_ctx['env']['FILE']))

This needs to be further explained.

In our layout, meta is a symlink (meta -> openembedded-core/meta), so pkg_ctx['env']['FILE'] returns a path through the symlink. Later, git add on that path fails because the git repo is at the resolved openembedded-core/ path. I'll expand the commit message to explain this.

Quoted 7 lines
Quoted 2 lines

- bb.process.run("bitbake-config-build enable-fragment

machine/{}".format(machine))

modules/utils/bitbake.py class Bitbake(object):

Quoted 3 lines
modules/utils/bitbake.py +2 -1
-        return self._cmd(recipe, env_var=env)
+        try:
+            bb.process.run("bitbake-config-build enable-fragment

machine/{}".format(machine))

Quoted 8 lines

Review

Quoted 2 lines
(quoted diff) +2 -0
+        except bb.process.ExecutionError:
+            # bitbake-config-build not available (e.g. scarthgap), use MACHINE

env var

modules/utils/bitbake.py class Bitbake(object): · line 131

Quoted 2 lines
modules/utils/bitbake.py +2 -0
+            env = "MACHINE={} {}".format(machine, env).strip()
+        return self._cmd(recipe, env_var=env if env else None)

The condition needs to be 'bitbake-config-build doesn't exist', not that it failed to execute (e.g. returned a non-zero).

I'll change it to check shutil.which('bitbake-config-build') instead of catching ExecutionError.

Quoted 9 lines

upgrade-helper.py class UniverseUpdater(Updater):

Quoted 6 lines

for group in pkggroups:

upgrade-helper.py +4 -0
+
+                # Scarthgap returns flat tuples; normalize to list-of-dicts
+                # so the existing loop handles both formats.
+                if not isinstance(group, (list, tuple)) or not group or not

isinstance(group[0], dict):

Quoted 1 line

+ pn, status, cur_ver, next_ver, maintainer, revision,

no_upgrade_reason = group

Quoted 8 lines

upgrade-helper.py class UniverseUpdater(Updater):

Quoted 4 lines
upgrade-helper.py +4 -0
+                    group = [{'pn': pn, 'status': status, 'cur_ver': cur_ver,
+                              'next_ver': next_ver, 'maintainer': maintainer,
+                              'revision': revision,
+ 'no_upgrade_reason': no_upgrade_reason}]

Can the condition be inverted, e.g. be checked for the 'old' format? I'm not sure I understand why 'old' format is determined by any of three different conditions being true, especially 'not group' looks incorrect.

Sure, Scarthgap's _get_recipe_upgrade_status returns a flat tuple of 7 elements, while master returns a list of dicts. I'll simplify it.

Quoted 2 lines

Alex

Thanks for the feedback. I'll updated in v3

Daniel

#4 lore raw

PATCH v2 2/9 upgrade-helper.py: Handle fetch errors gracefully during version scan

In reply to [email protected]

From: Daniel Turull <[email protected]>

Materialise the iterator from get_recipe_upgrade_status into a list, catching any exception that terminates the iterator early. A single unreachable upstream (e.g. git.savannah.gnu.org down) no longer aborts the entire scan — the recipes collected so far are still processed.

Assisted-by Claude, Anthropic
---
 upgrade-helper.py | 13 ++++++++++++-
 1 file changed, 12 insertions(+), 1 deletion(-)
upgrade-helper.py +12 -1
index aef7ed1..98391f3 100755
@@ -711,7 +711,18 @@ class UniverseUpdater(Updater):
         upgrade_pkggroups = []
 
         for layer_name, layer_recipes in self.recipes:
-            pkggroups = oe.recipeutils.get_recipe_upgrade_status(layer_recipes)
+            pkggroups_iter = oe.recipeutils.get_recipe_upgrade_status(layer_recipes)
+
+            # Collect results, logging any fetch error that terminates
+            # the iterator early (oe-core raises inside executor.map,
+            # which cannot be resumed after an exception).
+            pkggroups = []
+            try:
+                for group in pkggroups_iter:
+                    pkggroups.append(group)
+            except Exception as e:
+                W(" Fetch error terminated recipe scan for layer %s: %s" %
+                  (layer_name, str(e)))
 
             for group in pkggroups:
 
Signature · 1 line
2.34.1
#5 lore raw

Re: [AUH][PATCH v2 2/9] upgrade-helper.py: Handle fetch errors gracefully during version scan

Quoted 5 lines · On Fri, 24 Apr 2026 at 13:46, <[email protected]> wrote:

Materialise the iterator from get_recipe_upgrade_status into a list, catching any exception that terminates the iterator early. A single unreachable upstream (e.g. git.savannah.gnu.org down) no longer aborts the entire scan — the recipes collected so far are still processed.

I'd like to see the particular error that results in this happening and fix it at the source. The get_recipe_upgrade_status() function is not supposed to abort like this, and for any upstream network issues it should be returning UNKNOWN_BROKEN status for that particular recipe.

Alex

#6 lore raw

PATCH v2 3/9 upgrade-helper.py: allow to set the git directory from layer-dir

In reply to [email protected]

From: Daniel Turull <[email protected]>

Replace the assumption that the poky directory is the first PATH entry and reuse --layer-dir to setup directory for git repo.

This is useful when not using poky and each meta-layer is its own git. Without this fix, commit_changes fails in non-poky layouts:

git add .../openembedded-core/meta/recipes-support/gnupg
fatal: '.../openembedded-core/meta/recipes-support/gnupg' is outside repository at '.../yocto-scarthgap'

Assisted-by Claude, Anthropic
---
 upgrade-helper.py | 3 +++
 1 file changed, 3 insertions(+)
upgrade-helper.py +3 -0
index 98391f3..df927d1 100755
@@ -184,6 +184,9 @@ class Updater(object):
                     _layer_settings_error(s)
 
             self.git = Git(self.opts['layer_dir'])
+        elif settings.get('layer_dir'):
+            # allow to set the git repo directory without enabling layer_mode
+            self.git = Git(settings.get('layer_dir'))
         else:
             # use scripts_path to get oe-core directory
             self.git = Git(os.path.dirname(scripts_path))
Signature · 1 line
2.34.1
#7 lore raw

Re: [AUH][PATCH v2 3/9] upgrade-helper.py: allow to set the git directory from layer-dir

upgrade-helper.py class Updater(object): · line 192

Quoted 7 lines · On Fri, 24 Apr 2026 at 13:46, <[email protected]> wrote:
             self.git = Git(self.opts['layer_dir'])
upgrade-helper.py +3 -0
+        elif settings.get('layer_dir'):
+            # allow to set the git repo directory without enabling layer_mode
+            self.git = Git(settings.get('layer_dir'))
         else:
             # use scripts_path to get oe-core directory
             self.git = Git(os.path.dirname(scripts_path))

I don't understand. scripts_path is set thusly:

scripts_path = os.path.realpath(os.path.abspath(os.path.dirname(shutil.which("devtool"))))

What is the layer layout that causes the 'wrong' path to be picked by this? Either you use integrated poky repo without oe-core, or you use oe-core without integrated poky, but you shouldn't be using both.

Alex

Quoted 36 lines · On Fri, 24 Apr 2026 at 13:46, <[email protected]> wrote:

From: Daniel Turull <[email protected]>

Replace the assumption that the poky directory is the first PATH entry and reuse --layer-dir to setup directory for git repo.

This is useful when not using poky and each meta-layer is its own git. Without this fix, commit_changes fails in non-poky layouts:

git add .../openembedded-core/meta/recipes-support/gnupg
fatal: '.../openembedded-core/meta/recipes-support/gnupg' is outside repository at '.../yocto-scarthgap'

Assisted-by Claude, Anthropic
---
 upgrade-helper.py | 3 +++
 1 file changed, 3 insertions(+)
upgrade-helper.py +3 -1
index 98391f3..df927d1 100755
@@ -184,6 +184,9 @@ class Updater(object):
                     _layer_settings_error(s)
 
             self.git = Git(self.opts['layer_dir'])
+        elif settings.get('layer_dir'):
+            # allow to set the git repo directory without enabling layer_mode
+            self.git = Git(settings.get('layer_dir'))
         else:
             # use scripts_path to get oe-core directory
             self.git = Git(os.path.dirname(scripts_path))
--

2.34.1

#8 lore raw

RE: [AUH][PATCH v2 3/9] upgrade-helper.py: allow to set the git directory from layer-dir

Hi Alex,

I went back and checked. scripts_path already uses os.path.realpath, which resolves symlinks correctly. I reverted the patch and I cannot reproduce it.

My layout uses standalone oe-core with symlinks:

yocto-scarthgap/
- scripts -> openembedded-core/scripts/
- oe-init-build-env -> openembedded-core/oe-init-build-env
- openembedded-core/ (git repo)
- meta-openembedded/ (git repo)

The error I described in the commit message must have been caused by something else in my environment at the time. I'll drop this patch in v3.

Thanks,
Daniel

Quoted 67 lines

-----Original Message-----
From: Alexander Kanavin <[email protected]>
Sent: Monday, 27 April 2026 11:52
To: Daniel Turull <[email protected]>
Cc: [email protected]; [email protected]; [email protected]; [email protected]
Subject: Re: [AUH][PATCH v2 3/9] upgrade-helper.py: allow to set the git directory from layer-dir

upgrade-helper.py class Updater(object): · line 192

Quoted 7 lines · On Fri, 24 Apr 2026 at 13:46, <[email protected]> wrote:
             self.git = Git(self.opts['layer_dir'])
upgrade-helper.py +3 -0
+        elif settings.get('layer_dir'):
+            # allow to set the git repo directory without enabling layer_mode
+            self.git = Git(settings.get('layer_dir'))
         else:
             # use scripts_path to get oe-core directory
             self.git = Git(os.path.dirname(scripts_path))

I don't understand. scripts_path is set thusly:

scripts_path = os.path.realpath(os.path.abspath(os.path.dirname(shutil.which("devtool"))))

What is the layer layout that causes the 'wrong' path to be picked by this? Either you use integrated poky repo without oe-core, or you use oe-core without integrated poky, but you shouldn't be using both.

Alex

Quoted 36 lines · On Fri, 24 Apr 2026 at 13:46, <[email protected]> wrote:

From: Daniel Turull <[email protected]>

Replace the assumption that the poky directory is the first PATH entry and reuse --layer-dir to setup directory for git repo.

This is useful when not using poky and each meta-layer is its own git. Without this fix, commit_changes fails in non-poky layouts:

git add .../openembedded-core/meta/recipes-support/gnupg
fatal: '.../openembedded-core/meta/recipes-support/gnupg' is outside repository at '.../yocto-scarthgap'

Assisted-by Claude, Anthropic
---
 upgrade-helper.py | 3 +++
 1 file changed, 3 insertions(+)
upgrade-helper.py index renamed from upgrade-helper.py +0 -0

98391f3..df927d1 100755

upgrade-helper.py +3 -1
@@ -184,6 +184,9 @@ class Updater(object):
                     _layer_settings_error(s)
 
             self.git = Git(self.opts['layer_dir'])
+        elif settings.get('layer_dir'):
+            # allow to set the git repo directory without enabling layer_mode
+            self.git = Git(settings.get('layer_dir'))
         else:
             # use scripts_path to get oe-core directory
             self.git = Git(os.path.dirname(scripts_path))
--

2.34.1

#9 lore raw

PATCH v2 4/9 upgrade-helper.py: add changelog flag

In reply to [email protected]

From: Daniel Turull <[email protected]>

Add --changelog option to extract git log between old and new versions, highlighting CVE references. The changelog summary is appended to the commit message and included in the email notification.

Assisted-by Claude, Anthropic
---
 modules/changelog.py | 256 +++++++++++++++++++++++++++++++++++++++++++
 modules/steps.py     |  20 ++++
 upgrade-helper.py    |  16 +++
 3 files changed, 292 insertions(+)
 create mode 100644 modules/changelog.py
modules/changelog.py new file +256 -0
new file mode 100644
index 0000000..c1cc14b
@@ -0,0 +1,256 @@
+# SPDX-License-Identifier: GPL-2.0-or-later
+
+import os
+import re
+import glob
+import functools
+import subprocess
+
+from logging import info as I
+from logging import debug as D
+
+import bb.utils
+
+CHANGELOG_FILENAMES = [
+    'ChangeLog', 'CHANGELOG', 'CHANGELOG.md', 'CHANGELOG.txt',
+    'Changes', 'CHANGES', 'NEWS', 'NEWS.md', 'NEWS.txt',
+    'RELEASE_NOTES', 'RELEASE_NOTES.md', 'RELEASE-NOTES',
+    'HISTORY', 'HISTORY.md',
+    'debian/changelog',
+]
+
+CVE_PATTERN = re.compile(r'(CVE-\d{4}-\d{4,})', re.IGNORECASE)
+
+
+def _find_changelog_files(srcdir):
+    found = []
+    for name in CHANGELOG_FILENAMES:
+        for f in glob.glob(os.path.join(srcdir, '**', name), recursive=True):
+            if os.path.isfile(f) and f not in found:
+                found.append(f)
+    return found
+
+
+RST_INCLUDE_RE = re.compile(r'^\.\.\s+include::\s+(.+)$')
+RST_COMMENT_RE = re.compile(r'^\.\.\s*$|^\.\.\s')
+
+
+def _strip_rst_comments(text):
+    """Remove RST comment blocks (license headers etc.)."""
+    lines = text.split('\n')
+    result = []
+    in_comment = False
+    for line in lines:
+        if RST_COMMENT_RE.match(line):
+            in_comment = True
+            continue
+        if in_comment:
+            if line.startswith('   ') or line.strip() == '':
+                continue
+            in_comment = False
+        result.append(line)
+    return '\n'.join(result)
+
+
+def _resolve_rst_includes(content, base_dir, srcdir):
+    """Inline RST .. include:: directives."""
+    lines = content.split('\n')
+    result = []
+    for line in lines:
+        m = RST_INCLUDE_RE.match(line.strip())
+        if m:
+            inc_rel = m.group(1).strip()
+            inc_path = os.path.normpath(os.path.join(base_dir, inc_rel))
+            if not os.path.isfile(inc_path):
+                # Search for the filename within the source tree
+                fname = os.path.basename(inc_rel)
+                for f in glob.glob(os.path.join(srcdir, '**', fname),
+                                   recursive=True):
+                    if os.path.isfile(f):
+                        inc_path = f
+                        break
+            if os.path.isfile(inc_path):
+                try:
+                    with open(inc_path, 'r', encoding='utf-8',
+                              errors='replace') as f:
+                        result.append(f.read())
+                    continue
+                except OSError:
+                    pass
+        result.append(line)
+    return '\n'.join(result)
+
+
+GIT_LOG_RE = re.compile(r'^commit [0-9a-f]{7,}', re.MULTILINE)
+
+
+def _condense_git_log(text):
+    """Condense git-log-style content to subject lines only."""
+    if not GIT_LOG_RE.search(text):
+        return text
+    lines = text.split('\n')
+    subjects = []
+    i = 0
+    while i < len(lines):
+        if GIT_LOG_RE.match(lines[i]):
+            short = lines[i].split()[1][:12]
+            # Skip Author/Date, blank line, then grab subject
+            i += 1
+            while i < len(lines) and (lines[i].startswith('Author:') or
+                    lines[i].startswith('Date:') or not lines[i].strip()):
+                i += 1
+            if i < len(lines):
+                subjects.append('%s %s' % (short, lines[i].strip()))
+            continue
+        i += 1
+    return '\n'.join(subjects) if subjects else text
+
+
+def _extract_entries_between_versions(content, old_ver, new_ver):
+    lines = content.split('\n')
+    new_pattern = re.compile(re.escape(new_ver))
+    old_pattern = re.compile(re.escape(old_ver))
+
+    start_idx = None
+    end_idx = None
+
+    for i, line in enumerate(lines):
+        if start_idx is None and new_pattern.search(line):
+            start_idx = i
+        elif start_idx is not None and old_pattern.search(line):
+            end_idx = i
+            break
+
+    if start_idx is not None:
+        return '\n'.join(lines[start_idx:end_idx])
+    return None
+
+
+def _find_per_version_files(srcdir, old_ver, new_ver):
+    """Find individual per-version changelog files (e.g. changelog-1.2.3.rst)."""
+    ver_file_re = re.compile(
+        r'(?:changelog|changes|news|release|relnotes)[-_./\\]?'
+        r'v?(?P<pver>(\d+[\.\-_])*\d+)\.\w+$',
+        re.IGNORECASE)
+
+    candidates = {}
+    for f in glob.glob(os.path.join(srcdir, '**', '*'), recursive=True):
+        if not os.path.isfile(f):
+            continue
+        # Match against last two path components (e.g. RelNotes/v1.47.4.txt)
+        tail = os.sep.join(f.rsplit(os.sep, 2)[-2:])
+        m = ver_file_re.search(tail)
+        if m:
+            ver = m.group('pver').replace('_', '.').replace('-', '.')
+            candidates[ver] = f
+
+    # Select versions > old_ver and <= new_ver
+    selected = []
+    for ver, path in candidates.items():
+        if bb.utils.vercmp_string(ver, old_ver) > 0 and \
+           bb.utils.vercmp_string(ver, new_ver) <= 0:
+            selected.append((ver, path))
+
+    selected.sort(key=lambda x: functools.cmp_to_key(
+        bb.utils.vercmp_string)(x[0]))
+    return [path for _, path in selected]
+
+
+def extract_changelog(srcdir, pn, old_ver, new_ver, workdir):
+    if not srcdir or not os.path.isdir(srcdir):
+        D(" %s: source directory %s not available" % (pn, srcdir))
+        return None
+
+    entries = []
+    cves = []
+
+    # Strategy 1: extract sections between version markers in changelog files
+    changelog_files = _find_changelog_files(srcdir)
+    for fpath in changelog_files:
+        try:
+            with open(fpath, 'r', encoding='utf-8', errors='replace') as f:
+                content = f.read()
+        except OSError:
+            continue
+        content = _resolve_rst_includes(content, os.path.dirname(fpath), srcdir)
+        section = _extract_entries_between_versions(content, old_ver, new_ver)
+        if section:
+            section = _condense_git_log(section)
+            entries.append(section)
+            cves.extend(CVE_PATTERN.findall(section))
+            break
+
+    # Strategy 2: concatenate per-version files (e.g. changelog-9.18.42.rst)
+    if not entries:
+        ver_files = _find_per_version_files(srcdir, old_ver, new_ver)
+        for fpath in ver_files:
+            try:
+                with open(fpath, 'r', encoding='utf-8', errors='replace') as f:
+                    content = f.read()
+            except OSError:
+                continue
+            entries.append(content)
+            cves.extend(CVE_PATTERN.findall(content))
+
+    # Strategy 3: git log between version tags
+    if not entries and os.path.isdir(os.path.join(srcdir, '.git')):
+        tag_prefixes = ['v', '', pn + '-']
+        old_tag = new_tag = None
+        for prefix in tag_prefixes:
+            try:
+                subprocess.check_output(
+                    ['git', 'rev-parse', prefix + old_ver],
+                    cwd=srcdir, stderr=subprocess.DEVNULL)
+                subprocess.check_output(
+                    ['git', 'rev-parse', prefix + new_ver],
+                    cwd=srcdir, stderr=subprocess.DEVNULL)
+                old_tag, new_tag = prefix + old_ver, prefix + new_ver
+                break
+            except (subprocess.CalledProcessError, OSError):
+                continue
+        if old_tag and new_tag:
+            try:
+                out = subprocess.check_output(
+                    ['git', 'log', '--oneline', '%s..%s' % (old_tag, new_tag)],
+                    cwd=srcdir, stderr=subprocess.DEVNULL).decode('utf-8', errors='replace')
+                if out.strip():
+                    entries.append(out.strip())
+                    cves.extend(CVE_PATTERN.findall(out))
+            except (subprocess.CalledProcessError, OSError):
+                pass
+
+    if not entries:
+        D(" %s: no changelog entries found" % pn)
+        return None
+
+    I(" %s: found %d changelog entries" % (pn, len(entries)))
+
+    cves = sorted(set(cves))
+    text = "Changelog for %s: %s -> %s\n" % (pn, old_ver, new_ver)
+    text += "=" * 60 + "\n\n"
+    if cves:
+        text += "SECURITY FIXES / CVEs FOUND:\n"
+        for cve in cves:
+            text += "  - %s\n" % cve
+        text += "\n" + "-" * 60 + "\n\n"
+    text += CVE_PATTERN.sub(r'*** \1 ***', _strip_rst_comments('\n\n'.join(entries)))
+
+    # Collapse multiple blank lines into one
+    text = re.sub(r'\n{3,}', '\n\n', text)
+
+    changelog_path = os.path.join(workdir, "changelog-%s.txt" % pn)
+    with open(changelog_path, 'w', encoding='utf-8') as f:
+        f.write(text)
+
+    I(" %s: changelog saved to %s" % (pn, os.path.basename(changelog_path)))
+    if cves:
+        I(" %s: CVEs found: %s" % (pn, ', '.join(cves)))
+
+    commit_text = text
+    if len(commit_text) > 3000:
+        commit_text = commit_text[:3000] + "\n\n[... changelog truncated ...]\n"
+    # Sanitize for shell-safe git commit -m "..."
+    for ch in '"', '`', '$', '\\':
+        commit_text = commit_text.replace(ch, '')
+
+    return {'text': text, 'commit_text': commit_text, 'cves': cves, 'file': changelog_path}
modules/steps.py +20 -0
index b3ec61c..78fcbbe 100644
@@ -29,6 +29,7 @@ from logging import warning as W
 
 from errors import Error, DevtoolError, CompilationError
 from buildhistory import BuildHistory
+from changelog import extract_changelog
 
 def load_env(devtool, bb, git, opts, group):
     group['workdir'] = os.path.join(group['base_dir'], group['name'])
@@ -150,10 +151,29 @@ def devtool_finish(devtool, bb, git, opts, group):
             pass
         raise e1
 
+def changelog_extract(devtool, bb, git, opts, group):
+    if not opts.get('changelog'):
+        return
+    for p in group['pkgs']:
+        # After devtool_upgrade, source is in workspace/sources/<pn>/
+        srcdir = os.path.join(os.environ.get('BUILDDIR', ''),
+                              'workspace', 'sources', p['PN'])
+        if not os.path.isdir(srcdir):
+            # Fallback: derive from env S, replacing old version
+            srcdir = p['env'].get('S', '')
+            if p['PV'] in srcdir:
+                srcdir = srcdir.replace(p['PV'], p['NPV'])
+        result = extract_changelog(srcdir, p['PN'], p['PV'],
+                                   p['NPV'], group['workdir'])
+        if result:
+            p['changelog'] = result
+            group['commit_msg'] += "\n\n" + result['commit_text']
+
 upgrade_steps = [
     (load_env, "Loading environment ..."),
     (buildhistory_init, None),
     (devtool_upgrade, "Running 'devtool upgrade' ..."),
+    (changelog_extract, "Extracting changelog ..."),
     (devtool_finish, "Running 'devtool finish' ..."),
     (compile, None),
 ]
upgrade-helper.py +16 -0
index df927d1..327bb6d 100755
@@ -95,6 +95,8 @@ def parse_cmdline():
 
     parser.add_argument("-t", "--to_version",
                         help="version to upgrade the recipe to")
+    parser.add_argument("--changelog", action="store_true", default=False,
+                        help="extract changelog between old and new versions, highlighting CVEs")
 
     parser.add_argument("-d", "--debug-level", type=int, default=4, choices=range(1, 6),
                         help="set the debug level: CRITICAL=1, ERROR=2, WARNING=3, INFO=4, DEBUG=5")
@@ -198,6 +200,7 @@ class Updater(object):
         self.opts['skip_compilation'] = self.args.skip_compilation
         self.opts['buildhistory'] = self._buildhistory_is_enabled()
         self.opts['testimage'] = self._testimage_is_enabled()
+        self.opts['changelog'] = self.args.changelog
 
     def _make_dirs(self, build_dir):
         self.uh_dir = os.path.join(build_dir, "upgrade-helper")
@@ -358,6 +361,19 @@ class Updater(object):
         if 'patch_file' in g and g['patch_file'] is not None:
             msg_body += next_steps_info % (os.path.basename(g['patch_file']))
 
+        # Add changelog summary if available
+        for pkg_ctx in g['pkgs']:
+            if 'changelog' in pkg_ctx:
+                cl = pkg_ctx['changelog']
+                msg_body += ("\n--- Changelog Summary for %s ---\n"
+                             % pkg_ctx['PN'])
+                if cl['cves']:
+                    msg_body += "\nSECURITY FIXES / CVEs:\n"
+                    for cve in cl['cves']:
+                        msg_body += "  - %s\n" % cve
+                    msg_body += "\n"
+                msg_body += cl['text'] + "\n"
+
         msg_body += mail_footer
 
         # Add possible attachments to email
Signature · 1 line
2.34.1
#10 lore raw

Re: [AUH][PATCH v2 4/9] upgrade-helper.py: add changelog flag

Can you add examples please? This implements three different 'strategies', all of them are doing 'guessing', so it would be really beneficial to see what they actually produce.

It would also be super nice to have tests for this module, especially if people start tweaking it further. It looks like something that can break super easily. I know AUH has no tests (I inherited it in that condition), but at least this particular part could.

Alex

Quoted 364 lines · On Fri, 24 Apr 2026 at 13:46, <[email protected]> wrote:

From: Daniel Turull <[email protected]>

Add --changelog option to extract git log between old and new versions, highlighting CVE references. The changelog summary is appended to the commit message and included in the email notification.

Assisted-by Claude, Anthropic
---
 modules/changelog.py | 256 +++++++++++++++++++++++++++++++++++++++++++
 modules/steps.py     |  20 ++++
 upgrade-helper.py    |  16 +++
 3 files changed, 292 insertions(+)
 create mode 100644 modules/changelog.py
modules/changelog.py new file +256 -0
new file mode 100644
index 0000000..c1cc14b
@@ -0,0 +1,256 @@
+# SPDX-License-Identifier: GPL-2.0-or-later
+
+import os
+import re
+import glob
+import functools
+import subprocess
+
+from logging import info as I
+from logging import debug as D
+
+import bb.utils
+
+CHANGELOG_FILENAMES = [
+    'ChangeLog', 'CHANGELOG', 'CHANGELOG.md', 'CHANGELOG.txt',
+    'Changes', 'CHANGES', 'NEWS', 'NEWS.md', 'NEWS.txt',
+    'RELEASE_NOTES', 'RELEASE_NOTES.md', 'RELEASE-NOTES',
+    'HISTORY', 'HISTORY.md',
+    'debian/changelog',
+]
+
+CVE_PATTERN = re.compile(r'(CVE-\d{4}-\d{4,})', re.IGNORECASE)
+
+
+def _find_changelog_files(srcdir):
+    found = []
+    for name in CHANGELOG_FILENAMES:
+        for f in glob.glob(os.path.join(srcdir, '**', name), recursive=True):
+            if os.path.isfile(f) and f not in found:
+                found.append(f)
+    return found
+
+
+RST_INCLUDE_RE = re.compile(r'^\.\.\s+include::\s+(.+)$')
+RST_COMMENT_RE = re.compile(r'^\.\.\s*$|^\.\.\s')
+
+
+def _strip_rst_comments(text):
+    """Remove RST comment blocks (license headers etc.)."""
+    lines = text.split('\n')
+    result = []
+    in_comment = False
+    for line in lines:
+        if RST_COMMENT_RE.match(line):
+            in_comment = True
+            continue
+        if in_comment:
+            if line.startswith('   ') or line.strip() == '':
+                continue
+            in_comment = False
+        result.append(line)
+    return '\n'.join(result)
+
+
+def _resolve_rst_includes(content, base_dir, srcdir):
+    """Inline RST .. include:: directives."""
+    lines = content.split('\n')
+    result = []
+    for line in lines:
+        m = RST_INCLUDE_RE.match(line.strip())
+        if m:
+            inc_rel = m.group(1).strip()
+            inc_path = os.path.normpath(os.path.join(base_dir, inc_rel))
+            if not os.path.isfile(inc_path):
+                # Search for the filename within the source tree
+                fname = os.path.basename(inc_rel)
+                for f in glob.glob(os.path.join(srcdir, '**', fname),
+                                   recursive=True):
+                    if os.path.isfile(f):
+                        inc_path = f
+                        break
+            if os.path.isfile(inc_path):
+                try:
+                    with open(inc_path, 'r', encoding='utf-8',
+                              errors='replace') as f:
+                        result.append(f.read())
+                    continue
+                except OSError:
+                    pass
+        result.append(line)
+    return '\n'.join(result)
+
+
+GIT_LOG_RE = re.compile(r'^commit [0-9a-f]{7,}', re.MULTILINE)
+
+
+def _condense_git_log(text):
+    """Condense git-log-style content to subject lines only."""
+    if not GIT_LOG_RE.search(text):
+        return text
+    lines = text.split('\n')
+    subjects = []
+    i = 0
+    while i < len(lines):
+        if GIT_LOG_RE.match(lines[i]):
+            short = lines[i].split()[1][:12]
+            # Skip Author/Date, blank line, then grab subject
+            i += 1
+            while i < len(lines) and (lines[i].startswith('Author:') or
+                    lines[i].startswith('Date:') or not lines[i].strip()):
+                i += 1
+            if i < len(lines):
+                subjects.append('%s %s' % (short, lines[i].strip()))
+            continue
+        i += 1
+    return '\n'.join(subjects) if subjects else text
+
+
+def _extract_entries_between_versions(content, old_ver, new_ver):
+    lines = content.split('\n')
+    new_pattern = re.compile(re.escape(new_ver))
+    old_pattern = re.compile(re.escape(old_ver))
+
+    start_idx = None
+    end_idx = None
+
+    for i, line in enumerate(lines):
+        if start_idx is None and new_pattern.search(line):
+            start_idx = i
+        elif start_idx is not None and old_pattern.search(line):
+            end_idx = i
+            break
+
+    if start_idx is not None:
+        return '\n'.join(lines[start_idx:end_idx])
+    return None
+
+
+def _find_per_version_files(srcdir, old_ver, new_ver):
+    """Find individual per-version changelog files (e.g. changelog-1.2.3.rst)."""
+    ver_file_re = re.compile(
+        r'(?:changelog|changes|news|release|relnotes)[-_./\\]?'
+        r'v?(?P<pver>(\d+[\.\-_])*\d+)\.\w+$',
+        re.IGNORECASE)
+
+    candidates = {}
+    for f in glob.glob(os.path.join(srcdir, '**', '*'), recursive=True):
+        if not os.path.isfile(f):
+            continue
+        # Match against last two path components (e.g. RelNotes/v1.47.4.txt)
+        tail = os.sep.join(f.rsplit(os.sep, 2)[-2:])
+        m = ver_file_re.search(tail)
+        if m:
+            ver = m.group('pver').replace('_', '.').replace('-', '.')
+            candidates[ver] = f
+
+    # Select versions > old_ver and <= new_ver
+    selected = []
+    for ver, path in candidates.items():
+        if bb.utils.vercmp_string(ver, old_ver) > 0 and \
+           bb.utils.vercmp_string(ver, new_ver) <= 0:
+            selected.append((ver, path))
+
+    selected.sort(key=lambda x: functools.cmp_to_key(
+        bb.utils.vercmp_string)(x[0]))
+    return [path for _, path in selected]
+
+
+def extract_changelog(srcdir, pn, old_ver, new_ver, workdir):
+    if not srcdir or not os.path.isdir(srcdir):
+        D(" %s: source directory %s not available" % (pn, srcdir))
+        return None
+
+    entries = []
+    cves = []
+
+    # Strategy 1: extract sections between version markers in changelog files
+    changelog_files = _find_changelog_files(srcdir)
+    for fpath in changelog_files:
+        try:
+            with open(fpath, 'r', encoding='utf-8', errors='replace') as f:
+                content = f.read()
+        except OSError:
+            continue
+        content = _resolve_rst_includes(content, os.path.dirname(fpath), srcdir)
+        section = _extract_entries_between_versions(content, old_ver, new_ver)
+        if section:
+            section = _condense_git_log(section)
+            entries.append(section)
+            cves.extend(CVE_PATTERN.findall(section))
+            break
+
+    # Strategy 2: concatenate per-version files (e.g. changelog-9.18.42.rst)
+    if not entries:
+        ver_files = _find_per_version_files(srcdir, old_ver, new_ver)
+        for fpath in ver_files:
+            try:
+                with open(fpath, 'r', encoding='utf-8', errors='replace') as f:
+                    content = f.read()
+            except OSError:
+                continue
+            entries.append(content)
+            cves.extend(CVE_PATTERN.findall(content))
+
+    # Strategy 3: git log between version tags
+    if not entries and os.path.isdir(os.path.join(srcdir, '.git')):
+        tag_prefixes = ['v', '', pn + '-']
+        old_tag = new_tag = None
+        for prefix in tag_prefixes:
+            try:
+                subprocess.check_output(
+                    ['git', 'rev-parse', prefix + old_ver],
+                    cwd=srcdir, stderr=subprocess.DEVNULL)
+                subprocess.check_output(
+                    ['git', 'rev-parse', prefix + new_ver],
+                    cwd=srcdir, stderr=subprocess.DEVNULL)
+                old_tag, new_tag = prefix + old_ver, prefix + new_ver
+                break
+            except (subprocess.CalledProcessError, OSError):
+                continue
+        if old_tag and new_tag:
+            try:
+                out = subprocess.check_output(
+                    ['git', 'log', '--oneline', '%s..%s' % (old_tag, new_tag)],
+                    cwd=srcdir, stderr=subprocess.DEVNULL).decode('utf-8', errors='replace')
+                if out.strip():
+                    entries.append(out.strip())
+                    cves.extend(CVE_PATTERN.findall(out))
+            except (subprocess.CalledProcessError, OSError):
+                pass
+
+    if not entries:
+        D(" %s: no changelog entries found" % pn)
+        return None
+
+    I(" %s: found %d changelog entries" % (pn, len(entries)))
+
+    cves = sorted(set(cves))
+    text = "Changelog for %s: %s -> %s\n" % (pn, old_ver, new_ver)
+    text += "=" * 60 + "\n\n"
+    if cves:
+        text += "SECURITY FIXES / CVEs FOUND:\n"
+        for cve in cves:
+            text += "  - %s\n" % cve
+        text += "\n" + "-" * 60 + "\n\n"
+    text += CVE_PATTERN.sub(r'*** \1 ***', _strip_rst_comments('\n\n'.join(entries)))
+
+    # Collapse multiple blank lines into one
+    text = re.sub(r'\n{3,}', '\n\n', text)
+
+    changelog_path = os.path.join(workdir, "changelog-%s.txt" % pn)
+    with open(changelog_path, 'w', encoding='utf-8') as f:
+        f.write(text)
+
+    I(" %s: changelog saved to %s" % (pn, os.path.basename(changelog_path)))
+    if cves:
+        I(" %s: CVEs found: %s" % (pn, ', '.join(cves)))
+
+    commit_text = text
+    if len(commit_text) > 3000:
+        commit_text = commit_text[:3000] + "\n\n[... changelog truncated ...]\n"
+    # Sanitize for shell-safe git commit -m "..."
+    for ch in '"', '`', '$', '\\':
+        commit_text = commit_text.replace(ch, '')
+
+    return {'text': text, 'commit_text': commit_text, 'cves': cves, 'file': changelog_path}
modules/steps.py +20 -0
index b3ec61c..78fcbbe 100644
@@ -29,6 +29,7 @@ from logging import warning as W
 
 from errors import Error, DevtoolError, CompilationError
 from buildhistory import BuildHistory
+from changelog import extract_changelog
 
 def load_env(devtool, bb, git, opts, group):
     group['workdir'] = os.path.join(group['base_dir'], group['name'])
@@ -150,10 +151,29 @@ def devtool_finish(devtool, bb, git, opts, group):
             pass
         raise e1
 
+def changelog_extract(devtool, bb, git, opts, group):
+    if not opts.get('changelog'):
+        return
+    for p in group['pkgs']:
+        # After devtool_upgrade, source is in workspace/sources/<pn>/
+        srcdir = os.path.join(os.environ.get('BUILDDIR', ''),
+                              'workspace', 'sources', p['PN'])
+        if not os.path.isdir(srcdir):
+            # Fallback: derive from env S, replacing old version
+            srcdir = p['env'].get('S', '')
+            if p['PV'] in srcdir:
+                srcdir = srcdir.replace(p['PV'], p['NPV'])
+        result = extract_changelog(srcdir, p['PN'], p['PV'],
+                                   p['NPV'], group['workdir'])
+        if result:
+            p['changelog'] = result
+            group['commit_msg'] += "\n\n" + result['commit_text']
+
 upgrade_steps = [
     (load_env, "Loading environment ..."),
     (buildhistory_init, None),
     (devtool_upgrade, "Running 'devtool upgrade' ..."),
+    (changelog_extract, "Extracting changelog ..."),
     (devtool_finish, "Running 'devtool finish' ..."),
     (compile, None),
 ]
upgrade-helper.py +16 -1
index df927d1..327bb6d 100755
@@ -95,6 +95,8 @@ def parse_cmdline():
 
     parser.add_argument("-t", "--to_version",
                         help="version to upgrade the recipe to")
+    parser.add_argument("--changelog", action="store_true", default=False,
+                        help="extract changelog between old and new versions, highlighting CVEs")
 
     parser.add_argument("-d", "--debug-level", type=int, default=4, choices=range(1, 6),
                         help="set the debug level: CRITICAL=1, ERROR=2, WARNING=3, INFO=4, DEBUG=5")
@@ -198,6 +200,7 @@ class Updater(object):
         self.opts['skip_compilation'] = self.args.skip_compilation
         self.opts['buildhistory'] = self._buildhistory_is_enabled()
         self.opts['testimage'] = self._testimage_is_enabled()
+        self.opts['changelog'] = self.args.changelog
 
     def _make_dirs(self, build_dir):
         self.uh_dir = os.path.join(build_dir, "upgrade-helper")
@@ -358,6 +361,19 @@ class Updater(object):
         if 'patch_file' in g and g['patch_file'] is not None:
             msg_body += next_steps_info % (os.path.basename(g['patch_file']))
 
+        # Add changelog summary if available
+        for pkg_ctx in g['pkgs']:
+            if 'changelog' in pkg_ctx:
+                cl = pkg_ctx['changelog']
+                msg_body += ("\n--- Changelog Summary for %s ---\n"
+                             % pkg_ctx['PN'])
+                if cl['cves']:
+                    msg_body += "\nSECURITY FIXES / CVEs:\n"
+                    for cve in cl['cves']:
+                        msg_body += "  - %s\n" % cve
+                    msg_body += "\n"
+                msg_body += cl['text'] + "\n"
+
         msg_body += mail_footer
 
         # Add possible attachments to email
--

2.34.1

A message that is not in the archive (sent off-list or not yet received): [email protected]

#12 lore raw

Re: [yocto-patches] [AUH][PATCH v2 4/9] upgrade-helper.py: add changelog flag

Quoted 8 lines · Alexander Kanavin via lists.yoctoproject.org

Can you add examples please? This implements three different 'strategies', all of them are doing 'guessing', so it would be really beneficial to see what they actually produce.

It would also be super nice to have tests for this module, especially if people start tweaking it further. It looks like something that can break super easily. I know AUH has no tests (I inherited it in that condition), but at least this particular part could.

I still need to see examples, but come to think of, this changelog extraction should be in devtool, at least partially. devtool can diff the source tree between the old and new version (it creates specific devtool specific tags for both, even when upgrading tarballs), and then filter the difference to only files that carry information about changes, which will eliminate most of the 'guessing'. Then it could write that into a file somewhere in workspace, and then further filter it to highlight CVEs or anything else that looks particularly important. Then AUH only needs to pick up those files and incorporate them into commit messages or emails.

Alex

#13 lore raw

RE: [yocto-patches] [AUH][PATCH v2 4/9] upgrade-helper.py: add changelog flag

Hi Alex,

Thanks for the feedback.

Here are some examples from scarthgap --stable run (148 recipes attempted, 99 changelogs extracted):

Strategy 1 — Changelog file parsing (52 packages, e.g. base-passwd 3.6.3 → 3.6.8, from debian/changelog):

base-passwd (3.6.8) unstable; urgency=medium

* Debconf translations:
- Turkish (thanks, Nuri KÜÇÜKLER; closes: #1102464).
* update-passwd(8) translations:
- French (thanks, Baptiste Jammet; closes: #1119914).

base-passwd (3.6.7) unstable; urgency=medium

    ...

Strategy 2 — Per-version files (1 package: git 2.44.0 → 2.44.4, from Documentation/RelNotes/v2.44.{1..4}.txt):

Git v2.44.1 Release Notes
...
Git v2.44.4 Release Notes

Strategy 3 — Git log between version tags (46 packages, e.g. asciidoc 10.2.0 → 10.2.1):

21e33ef Fix setting up debian backports in Dockerfile (#273) 22f3bf0 Bump version to 10.2.1 (#269)
c30d311 Fix running test suite for python 3.5 (#272) 6d9f76c Update GitHub actions badge

49 packages had no changelog found (no changelog file, no per-version files, no matching git tags).

I'll add unit tests for the changelog module in a separate commit in v3.

Regarding moving this to devtool — I agree that's the right long-term approach.
I can send a patch for devtool to oe-core master adding this. If accepted, we could request a backport to scarthgap through the Yocto TSC, and then drop the parsing from AUH in favour of just picking up devtool's output.

For now, keeping it in AUH lets us iterate on the extraction logic without requiring oe-core changes. If you prefer the devtool path, we can put the changelog path on hold

Cheers,
Daniel

Quoted 32 lines

-----Original Message-----
From: Alexander Kanavin <[email protected]>
Sent: Monday, 27 April 2026 13:17
To: [email protected]
Cc: Daniel Turull <[email protected]>; [email protected]; [email protected]; [email protected]
Subject: Re: [yocto-patches] [AUH][PATCH v2 4/9] upgrade-helper.py: add changelog flag

Quoted 8 lines · Alexander Kanavin via lists.yoctoproject.org

Can you add examples please? This implements three different 'strategies', all of them are doing 'guessing', so it would be really beneficial to see what they actually produce.

It would also be super nice to have tests for this module, especially if people start tweaking it further. It looks like something that can break super easily. I know AUH has no tests (I inherited it in that condition), but at least this particular part could.

I still need to see examples, but come to think of, this changelog extraction should be in devtool, at least partially. devtool can diff the source tree between the old and new version (it creates specific devtool specific tags for both, even when upgrading tarballs), and then filter the difference to only files that carry information about changes, which will eliminate most of the 'guessing'. Then it could write that into a file somewhere in workspace, and then further filter it to highlight CVEs or anything else that looks particularly important. Then AUH only needs to pick up those files and incorporate them into commit messages or emails.

Alex

#14 lore raw

Re: [yocto-patches] [AUH][PATCH v2 4/9] upgrade-helper.py: add changelog flag

Quoted 1 line · Daniel Turull

For now, keeping it in AUH lets us iterate on the extraction logic without requiring oe-core changes. If you prefer the devtool path, we can put the changelog path on hold

I absolutely do, yes. Devtool handles individual recipe upgrades, and extracting changelogs is a part of that. It also has actual tests, which massively helps with having confidence in adding complex, easily breakable code.

We shouldn't be adding features to AUH just to work around oe-core maintenance policies. It needs to remain short and simple.

Alex

#15 lore raw

RE: [yocto-patches] [AUH][PATCH v2 4/9] upgrade-helper.py: add changelog flag

Ok, I'll work to have something for oe-core and drop the changelog patch from the series

Daniel

Quoted 22 lines

-----Original Message-----
From: Alexander Kanavin <[email protected]>
Sent: Tuesday, 28 April 2026 12:43
To: Daniel Turull <[email protected]>
Cc: [email protected]; [email protected]; [email protected]; [email protected]
Subject: Re: [yocto-patches] [AUH][PATCH v2 4/9] upgrade-helper.py: add changelog flag

Quoted 3 lines · Daniel Turull

For now, keeping it in AUH lets us iterate on the extraction logic without requiring oe-core changes. If you prefer the devtool path, we can put the changelog path on hold

I absolutely do, yes. Devtool handles individual recipe upgrades, and extracting changelogs is a part of that. It also has actual tests, which massively helps with having confidence in adding complex, easily breakable code.

We shouldn't be adding features to AUH just to work around oe-core maintenance policies. It needs to remain short and simple.

Alex

#16 lore raw

PATCH v2 5/9 upgrade-helper.py: Add stable option for patch-only upgrades

In reply to [email protected]

From: Daniel Turull <[email protected]>

Add --stable flag to restrict upgrades to the next patch version within the current stable branch (e.g. 1.2.3 -> 1.2.4). When the latest upstream version is a major/minor bump, AUH queries all available versions and picks the best patch-level update.

Assisted-by Claude, Anthropic
---
 modules/utils/version.py | 160 +++++++++++++++++++++++++++++++++++++++
 upgrade-helper.py        |  51 +++++++++++++
 2 files changed, 211 insertions(+)
 create mode 100644 modules/utils/version.py
modules/utils/version.py new file +160 -0
new file mode 100644
index 0000000..b40eb1c
@@ -0,0 +1,160 @@
+# SPDX-License-Identifier: GPL-2.0-or-later
+#
+# Version utilities for --stable patch-only upgrades.
+#
+# get_all_upstream_versions() collects *all* available upstream versions so
+# that we can pick the highest patch-level release within the current stable
+# branch.  The existing bitbake/oe-core APIs (latest_versionstring,
+# get_recipe_upstream_version) only return the single highest version, so we
+# must re-implement the inner loops here.
+#
+# The HTTP path mirrors bb.fetch2.wget.Wget._check_latest_version() and the
+# git path mirrors bb.fetch2.git.Git.latest_versionstring(), both from
+# bitbake scarthgap.  We cannot modify oe-core on a stable release, hence
+# the duplication.
+
+import functools
+import re
+from logging import warning as W
+
+import bb.utils
+import bb.fetch2
+from bs4 import BeautifulSoup, SoupStrainer
+
+
+def _split_version(ver):
+    # Split on '.', '-', '_' and letter-digit boundaries (e.g. 10.0p2 -> [10, 0, p, 2])
+    parts = re.split(r'[\.\-_]', ver)
+    result = []
+    for p in parts:
+        result.extend(re.split(r'(?<=[a-zA-Z])(?=\d)|(?<=\d)(?=[a-zA-Z])', p))
+    return result
+
+
+def is_patch_update(current_ver, candidate_ver):
+    cur = _split_version(current_ver)
+    cand = _split_version(candidate_ver)
+    if len(cur) != len(cand) or len(cur) < 3:
+        return False
+    if cur[:-1] != cand[:-1]:
+        return False
+    try:
+        return int(cand[-1]) > int(cur[-1])
+    except ValueError:
+        return bb.utils.vercmp_string(candidate_ver, current_ver) > 0
+
+
+def _find_best_version(current_ver, all_versions, filter_fn):
+    candidates = [v for v in all_versions if filter_fn(current_ver, v)]
+    if not candidates:
+        return None
+    candidates.sort(
+        key=functools.cmp_to_key(bb.utils.vercmp_string), reverse=True
+    )
+    return candidates[0]
+
+
+def find_patch_version(current_ver, all_versions):
+    return _find_best_version(current_ver, all_versions, is_patch_update)
+
+
+def get_all_upstream_versions(rd):
+    """Get all upstream versions using the fetcher infrastructure.
+
+    Unlike ud.method.latest_versionstring() which returns only the highest
+    version, this collects every version so the caller can filter for
+    patch-only updates.
+    """
+    src_uris = rd.getVar('SRC_URI')
+    if not src_uris:
+        return []
+
+    src_uri = src_uris.split()[0]
+    ud = bb.fetch2.FetchData(src_uri, rd)
+
+    if ud.type == 'git':
+        return _get_git_versions(ud, rd)
+    return _get_http_versions(ud, rd)
+
+
+def _get_http_versions(ud, rd):
+    """Collect all upstream versions from an HTTP index page.
+
+    Adapted from bb.fetch2.wget.Wget._check_latest_version() and
+    ._init_regexes().  The upstream code only keeps the highest version;
+    we collect them all.  Uses BeautifulSoup to parse <a> tags, matching
+    the upstream behaviour.
+    """
+    try:
+        package = ud.path.split("/")[-1]
+
+        regex_uri = rd.getVar('UPSTREAM_CHECK_URI')
+        if not regex_uri:
+            path = ud.path.split(package)[0]
+            regex_uri = bb.fetch.encodeurl([ud.type, ud.host, path,
+                                            ud.user, ud.pswd, {}])
+
+        page = ud.method._fetch_index(regex_uri, ud, rd)
+        if not page:
+            return []
+
+        regex = rd.getVar('UPSTREAM_CHECK_REGEX')
+        if regex:
+            regex = re.compile(regex)
+        else:
+            regex = ud.method._init_regexes(package, ud, rd)
+        if not regex:
+            return []
+
+        # Parse HTML links, same as Wget._check_latest_version()
+        soup = BeautifulSoup(page, "html.parser",
+                             parse_only=SoupStrainer("a"))
+        if not soup:
+            return []
+
+        versions = set()
+        for link in soup.find_all('a', href=True):
+            for text in (link['href'], str(link)):
+                m = regex.search(text)
+                if m and 'pver' in m.groupdict() and m.group('pver'):
+                    versions.add(re.sub('_', '.', m.group('pver')))
+                    break
+        return list(versions)
+    except Exception as e:
+        W(" Failed to get HTTP versions: %s" % str(e))
+        return []
+
+
+def _get_git_versions(ud, rd):
+    """Collect all tagged versions from a git remote.
+
+    Adapted from bb.fetch2.git.Git.latest_versionstring().  The upstream
+    code only keeps the highest version; we collect them all.
+    """
+    try:
+        output = ud.method._lsremote(ud, rd, "refs/tags/*")
+    except (bb.fetch2.FetchError, bb.fetch2.NetworkAccess, OSError) as e:
+        W(" Failed to list remote tags: %s" % str(e))
+        return []
+
+    rev_tag_re = re.compile(r"([0-9a-f]{40})\s+refs/tags/(.*)")
+    pver_re = re.compile(
+        rd.getVar('UPSTREAM_CHECK_GITTAGREGEX')
+        or r"(?P<pver>([0-9][\.|_]?)+)"
+    )
+    nonrel_re = re.compile(r"(alpha|beta|rc|final)+")
+
+    versions = set()
+    for line in output.split("\n"):
+        if not line:
+            break
+        m = rev_tag_re.match(line)
+        if not m:
+            continue
+        tag = m.group(2)
+        if nonrel_re.search(tag):
+            continue
+        m = pver_re.search(tag)
+        if m:
+            versions.add(m.group('pver').replace("_", "."))
+    return list(versions)
upgrade-helper.py +51 -0

81 lines not on this page · raw message

Signature · 1 line
2.34.1
#17 lore raw

Re: [AUH][PATCH v2 5/9] upgrade-helper.py: Add stable option for patch-only upgrades

This functionality really needs to go to oe-core, and it should be based on recipe metadata, e.g. for things like openssl we could indicate in the recipe that stable maintenance is done with point version releases, or systemd is maintained via minor versions (259.3 -> 259.4) or glibc has commits on a maintenance branch. You can't assume that point releases are equivalent to bugfix-only maintenance.

So that you could run e.g. 'devtool check-upgrade-status --stable' and it would print a list of possible maintenance updates.

Alex

Quoted 275 lines · On Fri, 24 Apr 2026 at 13:46, <[email protected]> wrote:

From: Daniel Turull <[email protected]>

Add --stable flag to restrict upgrades to the next patch version within the current stable branch (e.g. 1.2.3 -> 1.2.4). When the latest upstream version is a major/minor bump, AUH queries all available versions and picks the best patch-level update.

Assisted-by Claude, Anthropic
---
 modules/utils/version.py | 160 +++++++++++++++++++++++++++++++++++++++
 upgrade-helper.py        |  51 +++++++++++++
 2 files changed, 211 insertions(+)
 create mode 100644 modules/utils/version.py
modules/utils/version.py new file +160 -0
new file mode 100644
index 0000000..b40eb1c
@@ -0,0 +1,160 @@
+# SPDX-License-Identifier: GPL-2.0-or-later
+#
+# Version utilities for --stable patch-only upgrades.
+#
+# get_all_upstream_versions() collects *all* available upstream versions so
+# that we can pick the highest patch-level release within the current stable
+# branch.  The existing bitbake/oe-core APIs (latest_versionstring,
+# get_recipe_upstream_version) only return the single highest version, so we
+# must re-implement the inner loops here.
+#
+# The HTTP path mirrors bb.fetch2.wget.Wget._check_latest_version() and the
+# git path mirrors bb.fetch2.git.Git.latest_versionstring(), both from
+# bitbake scarthgap.  We cannot modify oe-core on a stable release, hence
+# the duplication.
+
+import functools
+import re
+from logging import warning as W
+
+import bb.utils
+import bb.fetch2
+from bs4 import BeautifulSoup, SoupStrainer
+
+
+def _split_version(ver):
+    # Split on '.', '-', '_' and letter-digit boundaries (e.g. 10.0p2 -> [10, 0, p, 2])
+    parts = re.split(r'[\.\-_]', ver)
+    result = []
+    for p in parts:
+        result.extend(re.split(r'(?<=[a-zA-Z])(?=\d)|(?<=\d)(?=[a-zA-Z])', p))
+    return result
+
+
+def is_patch_update(current_ver, candidate_ver):
+    cur = _split_version(current_ver)
+    cand = _split_version(candidate_ver)
+    if len(cur) != len(cand) or len(cur) < 3:
+        return False
+    if cur[:-1] != cand[:-1]:
+        return False
+    try:
+        return int(cand[-1]) > int(cur[-1])
+    except ValueError:
+        return bb.utils.vercmp_string(candidate_ver, current_ver) > 0
+
+
+def _find_best_version(current_ver, all_versions, filter_fn):
+    candidates = [v for v in all_versions if filter_fn(current_ver, v)]
+    if not candidates:
+        return None
+    candidates.sort(
+        key=functools.cmp_to_key(bb.utils.vercmp_string), reverse=True
+    )
+    return candidates[0]
+
+
+def find_patch_version(current_ver, all_versions):
+    return _find_best_version(current_ver, all_versions, is_patch_update)
+
+
+def get_all_upstream_versions(rd):
+    """Get all upstream versions using the fetcher infrastructure.
+
+    Unlike ud.method.latest_versionstring() which returns only the highest
+    version, this collects every version so the caller can filter for
+    patch-only updates.
+    """
+    src_uris = rd.getVar('SRC_URI')
+    if not src_uris:
+        return []
+
+    src_uri = src_uris.split()[0]
+    ud = bb.fetch2.FetchData(src_uri, rd)
+
+    if ud.type == 'git':
+        return _get_git_versions(ud, rd)
+    return _get_http_versions(ud, rd)
+
+
+def _get_http_versions(ud, rd):
+    """Collect all upstream versions from an HTTP index page.
+
+    Adapted from bb.fetch2.wget.Wget._check_latest_version() and
+    ._init_regexes().  The upstream code only keeps the highest version;
+    we collect them all.  Uses BeautifulSoup to parse <a> tags, matching
+    the upstream behaviour.
+    """
+    try:
+        package = ud.path.split("/")[-1]
+
+        regex_uri = rd.getVar('UPSTREAM_CHECK_URI')
+        if not regex_uri:
+            path = ud.path.split(package)[0]
+            regex_uri = bb.fetch.encodeurl([ud.type, ud.host, path,
+                                            ud.user, ud.pswd, {}])
+
+        page = ud.method._fetch_index(regex_uri, ud, rd)
+        if not page:
+            return []
+
+        regex = rd.getVar('UPSTREAM_CHECK_REGEX')
+        if regex:
+            regex = re.compile(regex)
+        else:
+            regex = ud.method._init_regexes(package, ud, rd)
+        if not regex:
+            return []
+
+        # Parse HTML links, same as Wget._check_latest_version()
+        soup = BeautifulSoup(page, "html.parser",
+                             parse_only=SoupStrainer("a"))
+        if not soup:
+            return []
+
+        versions = set()
+        for link in soup.find_all('a', href=True):
+            for text in (link['href'], str(link)):
+                m = regex.search(text)
+                if m and 'pver' in m.groupdict() and m.group('pver'):
+                    versions.add(re.sub('_', '.', m.group('pver')))
+                    break
+        return list(versions)
+    except Exception as e:
+        W(" Failed to get HTTP versions: %s" % str(e))
+        return []
+
+
+def _get_git_versions(ud, rd):
+    """Collect all tagged versions from a git remote.
+
+    Adapted from bb.fetch2.git.Git.latest_versionstring().  The upstream
+    code only keeps the highest version; we collect them all.
+    """
+    try:
+        output = ud.method._lsremote(ud, rd, "refs/tags/*")
+    except (bb.fetch2.FetchError, bb.fetch2.NetworkAccess, OSError) as e:
+        W(" Failed to list remote tags: %s" % str(e))
+        return []
+
+    rev_tag_re = re.compile(r"([0-9a-f]{40})\s+refs/tags/(.*)")
+    pver_re = re.compile(
+        rd.getVar('UPSTREAM_CHECK_GITTAGREGEX')
+        or r"(?P<pver>([0-9][\.|_]?)+)"
+    )
+    nonrel_re = re.compile(r"(alpha|beta|rc|final)+")
+
+    versions = set()
+    for line in output.split("\n"):
+        if not line:
+            break
+        m = rev_tag_re.match(line)
+        if not m:
+            continue
+        tag = m.group(2)
+        if nonrel_re.search(tag):
+            continue
+        m = pver_re.search(tag)
+        if m:
+            versions.add(m.group('pver').replace("_", "."))
+    return list(versions)
upgrade-helper.py +51 -1
index 327bb6d..b7b8ddf 100755
@@ -59,6 +59,7 @@ from utils.emailhandler import Email
 from statistics import Statistics
 from steps import upgrade_steps
 from testimage import TestImage
+from utils.version import is_patch_update, find_patch_version, get_all_upstream_versions
 
 if not os.getenv('BUILDDIR', False):
     E(" You must source oe-init-build-env before running this script!\n")
@@ -74,6 +75,7 @@ scriptpath.add_bitbake_lib_path()
 scriptpath.add_oe_lib_path()
 
 import oe.recipeutils
+import bb.tinfoil
 
 help_text = """Usage examples:
 * To upgrade xmodmap recipe to the latest available version:
@@ -97,6 +99,8 @@ def parse_cmdline():
                         help="version to upgrade the recipe to")
     parser.add_argument("--changelog", action="store_true", default=False,
                         help="extract changelog between old and new versions, highlighting CVEs")
+    parser.add_argument("--stable", action="store_true", default=False,
+                        help="only upgrade to the next patch version within the stable branch (e.g. 1.2.3 -> 1.2.4)")
 
     parser.add_argument("-d", "--debug-level", type=int, default=4, choices=range(1, 6),
                         help="set the debug level: CRITICAL=1, ERROR=2, WARNING=3, INFO=4, DEBUG=5")
@@ -698,6 +702,30 @@ class UniverseUpdater(Updater):
 
     def _get_packagegroups_to_upgrade(self, packages=None):
 
+        def _resolve_stable_version(pn, cur_ver, next_ver, tinfoil):
+            """Find the latest patch version within the current stable branch."""
+            if is_patch_update(cur_ver, next_ver):
+                return next_ver, None
+            I(" %s: latest version %s is not a patch update from %s,"
+              " searching for versions..." %
+              (pn, next_ver, cur_ver))
+            try:
+                rd = tinfoil.parse_recipe(pn)
+                if not rd:
+                    I(" %s: could not parse recipe, skipping" % pn)
+                    return None, None
+                all_versions = get_all_upstream_versions(rd)
+                ver = find_patch_version(cur_ver, all_versions)
+                if ver:
+                    I(" %s: found version %s" % (pn, ver))
+                    return ver, "N/A"
+                else:
+                    I(" %s: no suitable version available, skipping" % pn)
+                    return None, None
+            except Exception as e:
+                I(" %s: failed to search for versions: %s" % (pn, e))
+                return None, None
+
         # Prepare a single pkg dict data (or None is not upgradable) from recipeutils.get_recipe_upgrade_status data.
         def _get_pkg_to_upgrade(self, layer_name, pn, status, cur_ver, next_ver, maintainer, revision, no_upgrade_reason):
             pkg_to_upgrade = None
@@ -763,6 +791,29 @@ class UniverseUpdater(Updater):
                         upgrade_group.append(pkg_to_upgrade)
                 if upgrade_group:
                     upgrade_pkggroups.append(upgrade_group)
+
+        if self.args.stable and upgrade_pkggroups:
+            stable_tinfoil = bb.tinfoil.Tinfoil()
+            stable_tinfoil.prepare(config_only=False)
+            try:
+                filtered = []
+                for group in upgrade_pkggroups:
+                    filtered_group = []
+                    for pkg in group:
+                        stable_ver, stable_rev = _resolve_stable_version(
+                            pkg['pn'], pkg['cur_ver'], pkg['next_ver'],
+                            stable_tinfoil)
+                        if stable_ver is not None:
+                            pkg['next_ver'] = stable_ver
+                            if stable_rev is not None:
+                                pkg['revision'] = stable_rev
+                            filtered_group.append(pkg)
+                    if filtered_group:
+                        filtered.append(filtered_group)
+                upgrade_pkggroups = filtered
+            finally:
+                stable_tinfoil.shutdown()
+
         return upgrade_pkggroups
 
     def pkg_upgrade_handler(self, pkg_ctx):
--

2.34.1

#18 lore raw

PATCH v2 6/9 upgrade-helper.py: Add minor option for minor version upgrades

In reply to [email protected]

From: Daniel Turull <[email protected]>

Add --minor option that allows upgrades within the same major version (e.g. 3.5.x -> 3.6.x), complementing --stable which only allows patch-level changes.

Extends _resolve_stable_version with a minor flag and adds is_minor_update / find_minor_version to utils/version.py.

Assisted-by Claude, Anthropic
---
 modules/utils/version.py | 15 +++++++++++++++
 upgrade-helper.py        | 23 ++++++++++++++---------
 2 files changed, 29 insertions(+), 9 deletions(-)
modules/utils/version.py +15 -0
index b40eb1c..71e0a1e 100644
@@ -44,6 +44,17 @@ def is_patch_update(current_ver, candidate_ver):
         return bb.utils.vercmp_string(candidate_ver, current_ver) > 0
 
 
+def is_minor_update(current_ver, candidate_ver):
+    """Check if candidate is a newer release within the same major version."""
+    cur = _split_version(current_ver)
+    cand = _split_version(candidate_ver)
+    if len(cur) < 2 or len(cand) < 2:
+        return False
+    if cur[0] != cand[0]:
+        return False
+    return bb.utils.vercmp_string(candidate_ver, current_ver) > 0
+
+
 def _find_best_version(current_ver, all_versions, filter_fn):
     candidates = [v for v in all_versions if filter_fn(current_ver, v)]
     if not candidates:
@@ -58,6 +69,10 @@ def find_patch_version(current_ver, all_versions):
     return _find_best_version(current_ver, all_versions, is_patch_update)
 
 
+def find_minor_version(current_ver, all_versions):
+    return _find_best_version(current_ver, all_versions, is_minor_update)
+
+
 def get_all_upstream_versions(rd):
     """Get all upstream versions using the fetcher infrastructure.
 
upgrade-helper.py +14 -9
index b7b8ddf..ffa7449 100755
@@ -59,7 +59,8 @@ from utils.emailhandler import Email
 from statistics import Statistics
 from steps import upgrade_steps
 from testimage import TestImage
-from utils.version import is_patch_update, find_patch_version, get_all_upstream_versions
+from utils.version import is_patch_update, find_patch_version, get_all_upstream_versions, \
+    is_minor_update, find_minor_version
 
 if not os.getenv('BUILDDIR', False):
     E(" You must source oe-init-build-env before running this script!\n")
@@ -101,6 +102,8 @@ def parse_cmdline():
                         help="extract changelog between old and new versions, highlighting CVEs")
     parser.add_argument("--stable", action="store_true", default=False,
                         help="only upgrade to the next patch version within the stable branch (e.g. 1.2.3 -> 1.2.4)")
+    parser.add_argument("--minor", action="store_true", default=False,
+                        help="allow upgrades within the same major version (e.g. 3.5.2 -> 3.6.0, 3.99.0)")
 
     parser.add_argument("-d", "--debug-level", type=int, default=4, choices=range(1, 6),
                         help="set the debug level: CRITICAL=1, ERROR=2, WARNING=3, INFO=4, DEBUG=5")
@@ -702,20 +705,22 @@ class UniverseUpdater(Updater):
 
     def _get_packagegroups_to_upgrade(self, packages=None):
 
-        def _resolve_stable_version(pn, cur_ver, next_ver, tinfoil):
-            """Find the latest patch version within the current stable branch."""
-            if is_patch_update(cur_ver, next_ver):
+        def _resolve_stable_version(pn, cur_ver, next_ver, tinfoil, minor=False):
+            """Find the latest patch (or minor) version within the allowed range."""
+            check_fn = is_minor_update if minor else is_patch_update
+            find_fn = find_minor_version if minor else find_patch_version
+            if check_fn(cur_ver, next_ver):
                 return next_ver, None
-            I(" %s: latest version %s is not a patch update from %s,"
+            I(" %s: latest version %s is not a %s update from %s,"
               " searching for versions..." %
-              (pn, next_ver, cur_ver))
+              (pn, next_ver, "minor" if minor else "patch", cur_ver))
             try:
                 rd = tinfoil.parse_recipe(pn)
                 if not rd:
                     I(" %s: could not parse recipe, skipping" % pn)
                     return None, None
                 all_versions = get_all_upstream_versions(rd)
-                ver = find_patch_version(cur_ver, all_versions)
+                ver = find_fn(cur_ver, all_versions)
                 if ver:
                     I(" %s: found version %s" % (pn, ver))
                     return ver, "N/A"
@@ -792,7 +797,7 @@ class UniverseUpdater(Updater):
                 if upgrade_group:
                     upgrade_pkggroups.append(upgrade_group)
 
-        if self.args.stable and upgrade_pkggroups:
+        if (self.args.stable or self.args.minor) and upgrade_pkggroups:
             stable_tinfoil = bb.tinfoil.Tinfoil()
             stable_tinfoil.prepare(config_only=False)
             try:
@@ -802,7 +807,7 @@ class UniverseUpdater(Updater):
                     for pkg in group:
                         stable_ver, stable_rev = _resolve_stable_version(
                             pkg['pn'], pkg['cur_ver'], pkg['next_ver'],
-                            stable_tinfoil)
+                            stable_tinfoil, minor=self.args.minor)
                         if stable_ver is not None:
                             pkg['next_ver'] = stable_ver
                             if stable_rev is not None:
Signature · 1 line
2.34.1
#19 lore raw

Re: [AUH][PATCH v2 6/9] upgrade-helper.py: Add minor option for minor version upgrades

upgrade-helper.py def parse_cmdline(): · line 106

Quoted 5 lines · On Fri, 24 Apr 2026 at 13:46, <[email protected]> wrote:

help="extract changelog between old and new versions, highlighting CVEs")
parser.add_argument("--stable", action="store_true", default=False,
help="only upgrade to the next patch version within the stable branch (e.g. 1.2.3 -> 1.2.4)")

upgrade-helper.py +2 -0
+    parser.add_argument("--minor", action="store_true", default=False,
+                        help="allow upgrades within the same major version (e.g. 3.5.2 -> 3.6.0, 3.99.0)")

I'm somewhat confused. When and how one would be using either of these options? What's the workflow for them?

I still think it's better to place stable maintenance information directly into recipes.

Alex

#20 lore raw

RE: [AUH][PATCH v2 6/9] upgrade-helper.py: Add minor option for minor version upgrades

Hi Alex,

The workflow is: when running AUH against a stable branch (e.g. scarthgap), you typically don't want to pull in major version bumps. --stable restricts upgrades to patch-only (1.2.3 → 1.2.4), and --minor relaxes that to same-major (1.2.3 → 1.3.0).

In practice, the right policy depends on the component. From our test runs on scarthgap with --prebuild and ABI checking (meta-binaryaudit [1]), even patch-level upgrades can break ABI. For example, libnotify 0.8.3 → 0.8.8 is a patch bump, but abidiff reports INCOMPATIBLE_CHANGE: 2 removed functions, 4 added (a breaking ABI change hidden behind a patch version bump)

On the other hand, many minor-level upgrades like curl, libxml2, and e2fsprogs succeed without any ABI issues.

So ideally you'd use --minor for some recipes and --stable for others. Right now the CLI flags apply globally, which means you either run --stable for all, or list specific recipes with --minor. That works but isn't ideal.

I agree that putting this information in the recipe is the better long-term approach. Something like:

AUH_UPGRADE_POLICY = "patch" # or "minor" or "none"

defaulting to "patch" for conservative behavior. That way maintainers can set "minor" on recipes where it's safe, without needing to modify AUH's command line.

That said, adding recipe variables to already-released branches (scarthgap) means backporting metadata changes. The CLI flags work today without touching any recipes, which is why I started there.

Would you prefer I rework this as a recipe variable for the next version, or keep the CLI flags as a first step? I mean only one option (--stable) that can read AUH_UPGRADE_POLICY if present otherwise default to patch?

[1] https://github.com/Nordix/meta-binaryaudit (https://github.com/Nordix/meta-binaryaudit)

Daniel

Quoted 26 lines

-----Original Message-----
From: Alexander Kanavin <[email protected]>
Sent: Monday, 27 April 2026 12:22
To: Daniel Turull <[email protected]>
Cc: [email protected]; [email protected]; [email protected]; [email protected]
Subject: Re: [AUH][PATCH v2 6/9] upgrade-helper.py: Add minor option for minor version upgrades

Quoted 1 line · On Fri, 24 Apr 2026 at 13:46, <[email protected]> wrote:

help="extract changelog between old and new versions,

highlighting CVEs")

Review

Quoted 6 lines

parser.add_argument("--stable", action="store_true", default=False,
help="only upgrade to the next patch version
within the stable branch (e.g. 1.2.3 -> 1.2.4)")

(quoted diff) +3 -0
+    parser.add_argument("--minor", action="store_true", default=False,
+                        help="allow upgrades within the same major
+ version (e.g. 3.5.2 -> 3.6.0, 3.99.0)")

I'm somewhat confused. When and how one would be using either of these options? What's the workflow for them?

I still think it's better to place stable maintenance information directly into recipes.

Alex

#21 lore raw

Re: [AUH][PATCH v2 6/9] upgrade-helper.py: Add minor option for minor version upgrades

Quoted 3 lines · Daniel Turull

That said, adding recipe variables to already-released branches (scarthgap) means backporting metadata changes. The CLI flags work today without touching any recipes, which is why I started there.

Would you prefer I rework this as a recipe variable for the next version, or keep the CLI flags as a first step? I mean only one option (--stable) that can read AUH_UPGRADE_POLICY if present otherwise default to patch?

Please see my comment to 5/9 for additional thoughts on this. The major point I need to stress is that the correct long term maintainable thing is to extend existing oe-core mechanisms, even when such changes are difficult to backport.

Specifically:

- the version check functionality in meta/lib/oe/recipeutils.py should be extended to support checking for latest minor and point releases, and possibly other ways to provide stable updates (e.g. commits in a branch, or a custom regex for e.g. openssh's 10.1p3 schema).

- 'devtool check-upgrade-status --stable' or 'devtool latest-version --stable' would return a list of what could be updated based on recipe metadata (e.g. UPSTREAM_STABLE_RELEASES = "point" in some recipe would make devtool query recipeutils for latest point release within the same minor release)

- then AUH would simply use these mechanisms to do stable updates, when it's run with --stable argument. It would be a trivial change; it wouldn't need to know or care about how to pick the correct version, just call a different function to obtain maintenance releases instead of latest releases.

Alex

#22 lore raw

PATCH v2 7/9 upgrade-helper.py: Add prebuild option

In reply to [email protected]

From: Daniel Turull <[email protected]>

Add --prebuild option to build each recipe at its current version before attempting the upgrade. This allows verifying that recipes build before applying the upgrade and enables comparing binaries produced before and after, for example for build size or ABI compatibility checks.

Recipes that fail the pre-build are skipped and recorded as failures.

Assisted-by Claude, Anthropic
---
 upgrade-helper.py | 20 ++++++++++++++++++++
 1 file changed, 20 insertions(+)
upgrade-helper.py +20 -0
index ffa7449..11a97d2 100755
@@ -105,6 +105,9 @@ def parse_cmdline():
     parser.add_argument("--minor", action="store_true", default=False,
                         help="allow upgrades within the same major version (e.g. 3.5.2 -> 3.6.0, 3.99.0)")
 
+    parser.add_argument("--prebuild", action="store_true", default=False,
+                        help="build each recipe at its current version before attempting upgrade")
+
     parser.add_argument("-d", "--debug-level", type=int, default=4, choices=range(1, 6),
                         help="set the debug level: CRITICAL=1, ERROR=2, WARNING=3, INFO=4, DEBUG=5")
     parser.add_argument("-e", "--send-emails", action="store_true", default=False,
@@ -516,6 +519,21 @@ class Updater(object):
             attempted_pkggroups += 1
             pkggroup_name = g["name"]
             I(" ATTEMPT PACKAGE GROUP %d/%d" % (attempted_pkggroups, total_pkggroups))
+
+            # Build current version first to verify it builds and seed ABI reference
+            if self.args.prebuild and not self.args.skip_compilation:
+                I(" %s: Pre-building current version ..." % pkggroup_name)
+                try:
+                    for machine in self.opts['machines']:
+                        self.bb.complete(" ".join([p['PN'] for p in g['pkgs']]), machine)
+                except Exception as e:
+                    E(" %s: Pre-build FAILED, skipping upgrade" % pkggroup_name)
+                    if isinstance(e, Error):
+                        E(e.stdout + e.stderr)
+                    g['error'] = e if isinstance(e, Error) else Error(message=str(e))
+                    failed_pkggroups_ctx.append(g)
+                    continue
+
             try:
                 for pkg_ctx in g['pkgs']:
                     I(" %s: Upgrading to %s" % (pkg_ctx['PN'], pkg_ctx['NPV']))
@@ -571,6 +589,8 @@ class Updater(object):
             tim.run()
 
         for g in pkggroups_ctx:
+            if 'workdir' not in g:
+                continue
 
             if g in succeeded_pkggroups_ctx:
                 os.symlink(g['workdir'], os.path.join( \
Signature · 1 line
2.34.1
#23 lore raw

Re: [AUH][PATCH v2 7/9] upgrade-helper.py: Add prebuild option

There's already a buildhistory option which does such a pre-build and size comparison? Perhaps you can extend buildhistory with hooks into additional external checks?

Alex

Quoted 64 lines · On Fri, 24 Apr 2026 at 13:46, <[email protected]> wrote:

From: Daniel Turull <[email protected]>

Add --prebuild option to build each recipe at its current version before attempting the upgrade. This allows verifying that recipes build before applying the upgrade and enables comparing binaries produced before and after, for example for build size or ABI compatibility checks.

Recipes that fail the pre-build are skipped and recorded as failures.

Assisted-by Claude, Anthropic
---
 upgrade-helper.py | 20 ++++++++++++++++++++
 1 file changed, 20 insertions(+)
upgrade-helper.py +20 -1
index ffa7449..11a97d2 100755
@@ -105,6 +105,9 @@ def parse_cmdline():
     parser.add_argument("--minor", action="store_true", default=False,
                         help="allow upgrades within the same major version (e.g. 3.5.2 -> 3.6.0, 3.99.0)")
 
+    parser.add_argument("--prebuild", action="store_true", default=False,
+                        help="build each recipe at its current version before attempting upgrade")
+
     parser.add_argument("-d", "--debug-level", type=int, default=4, choices=range(1, 6),
                         help="set the debug level: CRITICAL=1, ERROR=2, WARNING=3, INFO=4, DEBUG=5")
     parser.add_argument("-e", "--send-emails", action="store_true", default=False,
@@ -516,6 +519,21 @@ class Updater(object):
             attempted_pkggroups += 1
             pkggroup_name = g["name"]
             I(" ATTEMPT PACKAGE GROUP %d/%d" % (attempted_pkggroups, total_pkggroups))
+
+            # Build current version first to verify it builds and seed ABI reference
+            if self.args.prebuild and not self.args.skip_compilation:
+                I(" %s: Pre-building current version ..." % pkggroup_name)
+                try:
+                    for machine in self.opts['machines']:
+                        self.bb.complete(" ".join([p['PN'] for p in g['pkgs']]), machine)
+                except Exception as e:
+                    E(" %s: Pre-build FAILED, skipping upgrade" % pkggroup_name)
+                    if isinstance(e, Error):
+                        E(e.stdout + e.stderr)
+                    g['error'] = e if isinstance(e, Error) else Error(message=str(e))
+                    failed_pkggroups_ctx.append(g)
+                    continue
+
             try:
                 for pkg_ctx in g['pkgs']:
                     I(" %s: Upgrading to %s" % (pkg_ctx['PN'], pkg_ctx['NPV']))
@@ -571,6 +589,8 @@ class Updater(object):
             tim.run()
 
         for g in pkggroups_ctx:
+            if 'workdir' not in g:
+                continue
 
             if g in succeeded_pkggroups_ctx:
                 os.symlink(g['workdir'], os.path.join( \
--

2.34.1

#24 lore raw

RE: [AUH][PATCH v2 7/9] upgrade-helper.py: Add prebuild option

Quoted 10 lines

-----Original Message-----
From: Alexander Kanavin <[email protected]>
Sent: Monday, 27 April 2026 12:20
To: Daniel Turull <[email protected]>
Cc: [email protected]; [email protected]; [email protected]; [email protected]
Subject: Re: [AUH][PATCH v2 7/9] upgrade-helper.py: Add prebuild option

Quoted 3 lines

There's already a buildhistory option which does such a pre-build and size comparison? Perhaps you can extend buildhistory with hooks into additional external checks?

I missed the buildhistory work. I'll drop the patch. I'll investigate about the hook for external checks.

Daniel

#25 lore raw

PATCH v2 8/9 upgrade-helper.py: Add resume option to skip already attempted recipes

In reply to [email protected]

From: Daniel Turull <[email protected]>

Add --resume option that reads the most recent run's log and skips recipes that were already attempted (either upgraded or failed pre-build).

This allows restarting an interrupted run without re-processing recipes that have already been handled, saving significant time on large runs (e.g. 12h for 135 recipes).

The skip set is built by parsing 'Upgrading to' and 'Pre-build FAILED' lines from the previous run's upgrade-helper.log.

Assisted-by Claude, Anthropic
---
 upgrade-helper.py | 27 +++++++++++++++++++++++++++
 1 file changed, 27 insertions(+)
upgrade-helper.py +27 -0
index 11a97d2..58fd660 100755
@@ -108,6 +108,9 @@ def parse_cmdline():
     parser.add_argument("--prebuild", action="store_true", default=False,
                         help="build each recipe at its current version before attempting upgrade")
 
+    parser.add_argument("--resume", action="store_true", default=False,
+                        help="skip recipes already attempted in the last run")
+
     parser.add_argument("-d", "--debug-level", type=int, default=4, choices=range(1, 6),
                         help="set the debug level: CRITICAL=1, ERROR=2, WARNING=3, INFO=4, DEBUG=5")
     parser.add_argument("-e", "--send-emails", action="store_true", default=False,
@@ -515,9 +518,33 @@ class Updater(object):
         succeeded_pkggroups_ctx = []
         failed_pkggroups_ctx = []
         attempted_pkggroups = 0
+
+        # --resume: skip recipes already attempted in the most recent run
+        resume_skip = set()
+        if self.args.resume:
+            import glob as _glob
+            prev_runs = sorted(_glob.glob(os.path.join(self.uh_dir, "20*")))
+            # skip the current run dir (last entry) if it exists
+            prev_runs = [r for r in prev_runs if r != self.uh_work_dir]
+            if prev_runs:
+                prev_log = os.path.join(prev_runs[-1], "upgrade-helper.log")
+                if os.path.isfile(prev_log):
+                    with open(prev_log) as f:
+                        for line in f:
+                            m = re.match(r'\s+(\S+): (?:Upgrading to|Pre-build FAILED)', line)
+                            if m:
+                                resume_skip.add(m.group(1))
+                    I(" --resume: skipping %d recipes from %s" %
+                      (len(resume_skip), prev_runs[-1]))
         for g in pkggroups_ctx:
             attempted_pkggroups += 1
             pkggroup_name = g["name"]
+
+            if any(p['PN'] in resume_skip for p in g['pkgs']):
+                I(" SKIP PACKAGE GROUP %d/%d (already attempted): %s" %
+                  (attempted_pkggroups, total_pkggroups, pkggroup_name))
+                continue
+
             I(" ATTEMPT PACKAGE GROUP %d/%d" % (attempted_pkggroups, total_pkggroups))
 
             # Build current version first to verify it builds and seed ABI reference
Signature · 1 line
2.34.1
#26 lore raw

Re: [AUH][PATCH v2 8/9] upgrade-helper.py: Add resume option to skip already attempted recipes

Quoted 2 lines · On Fri, 24 Apr 2026 at 13:46, <[email protected]> wrote:

The skip set is built by parsing 'Upgrading to' and 'Pre-build FAILED' lines from the previous run's upgrade-helper.log.

I wonder if this could be less brittle? For instance the skip set could be built by checking if the upgrade output is symlinked in failed/ or succeeded/. Currently those symlinks are created after everything is finished, but it could be done directly after each particular update.

Alex

#27 lore raw

RE: [AUH][PATCH v2 8/9] upgrade-helper.py: Add resume option to skip already attempted recipes

Quoted 11 lines

-----Original Message-----
From: Alexander Kanavin <[email protected]>
Sent: Monday, 27 April 2026 12:49
To: Daniel Turull <[email protected]>
Cc: [email protected]; [email protected]; [email protected]; [email protected]
Subject: Re: [AUH][PATCH v2 8/9] upgrade-helper.py: Add resume option to skip already attempted recipes

Quoted 8 lines
Quoted 2 lines · On Fri, 24 Apr 2026 at 13:46, <[email protected]> wrote:

The skip set is built by parsing 'Upgrading to' and 'Pre-build FAILED' lines from the previous run's upgrade-helper.log.

I wonder if this could be less brittle? For instance the skip set could be built by checking if the upgrade output is symlinked in failed/ or succeeded/. Currently those symlinks are created after everything is finished, but it could be done directly after each particular update.

Good idea. I'll redo the patch as you suggested in v3.

#28 lore raw

PATCH v2 9/9 upgrade-helper.py: Limit number of requests to remote servers

In reply to [email protected]

From: Daniel Turull <[email protected]>

In systems with lots of CPUs, we overflood some remote servers and then we get timeouts because of rate control.

Be more conservative. Defaults to 8 parallel workers instead of 64. Configurable via scan_workers=N in upgrade-helper.conf

For example, ftp.gnu.org was timing out

Assisted-by Claude, Anthropic
---
 upgrade-helper.py | 10 +++++++++-
 1 file changed, 9 insertions(+), 1 deletion(-)
upgrade-helper.py +9 -1
index 58fd660..11b8d58 100755
@@ -808,9 +808,17 @@ class UniverseUpdater(Updater):
             return pkg_to_upgrade
 
         upgrade_pkggroups = []
+        scan_workers = int(settings.get("scan_workers", "8"))
 
         for layer_name, layer_recipes in self.recipes:
-            pkggroups_iter = oe.recipeutils.get_recipe_upgrade_status(layer_recipes)
+            # Limit parallel version checks to avoid overwhelming upstream
+            # servers (oe-core defaults to cpu_count which can be 64+).
+            _orig_cpu_count = oe.utils.cpu_count
+            oe.utils.cpu_count = lambda at_least=1, at_most=64: min(max(at_least, scan_workers), at_most)
+            try:
+                pkggroups_iter = oe.recipeutils.get_recipe_upgrade_status(layer_recipes)
+            finally:
+                oe.utils.cpu_count = _orig_cpu_count
 
             # Collect results, logging any fetch error that terminates
             # the iterator early (oe-core raises inside executor.map,
Signature · 1 line
2.34.1
#29 lore raw

Re: [AUH][PATCH v2 9/9] upgrade-helper.py: Limit number of requests to remote servers

Quoted 1 line · On Fri, 24 Apr 2026 at 13:46, <[email protected]> wrote:

+ pkggroups_iter = oe.recipeutils.get_recipe_upgrade_status(layer_recipes)

Any such rate limiting needs to be handled inside this function by passing in a parameter, and certainly not by hacking oe.utils.cpu_count. Also, I'm not seeing the issue locally (256 cores, 64 worker threads in 'devtool check-upgrade-status'), are you redirected to some gnu mirror which does it?

I understand that you want to automate scarthgap updates, and such tweaks can't be easily backported in oe-core, but code shouldn't just 'fix issues', it also needs to be maintainable in the long term.

Alex

#30 lore raw

RE: [AUH][PATCH v2 9/9] upgrade-helper.py: Limit number of requests to remote servers

Hi,

I was experimenting to run it with an early version if scarthgap and GNU_MIRROR was not corrected.

-GNU_MIRROR = "https://ftp.gnu.org/gnu"
+GNU_MIRROR = "https://ftpmirror.gnu.org/gnu"

We can probably drop it, just wanted to be a bit more gentle against upstream servers. I'll remove it from v3

Daniel

Quoted 24 lines

-----Original Message-----
From: Alexander Kanavin <[email protected]>
Sent: Monday, 27 April 2026 12:35
To: Daniel Turull <[email protected]>
Cc: [email protected]; [email protected]; [email protected]; [email protected]
Subject: Re: [AUH][PATCH v2 9/9] upgrade-helper.py: Limit number of requests to remote servers

Quoted 2 lines · On Fri, 24 Apr 2026 at 13:46, <[email protected]> wrote:

+ pkggroups_iter =
+ oe.recipeutils.get_recipe_upgrade_status(layer_recipes)

Any such rate limiting needs to be handled inside this function by passing in a parameter, and certainly not by hacking oe.utils.cpu_count. Also, I'm not seeing the issue locally (256 cores,
64 worker threads in 'devtool check-upgrade-status'), are you redirected to some gnu mirror which does it?

I understand that you want to automate scarthgap updates, and such tweaks can't be easily backported in oe-core, but code shouldn't just 'fix issues', it also needs to be maintainable in the long term.

Alex