diff --git a/cli/contributing/update/README.md b/cli/contributing/update/README.md index b785f77586..8d2d2f9fa5 100644 --- a/cli/contributing/update/README.md +++ b/cli/contributing/update/README.md @@ -18,6 +18,8 @@ Every role-scoped updater (`docker`, `source`, `pip`, `repository`) and the addo A branch name and a short SHA stay as they are. `# nocheck: repository-version` on the line above `ref:` freezes a pin. Each repository is queried once per run and lookup, and a failed query leaves its pins untouched. The `update-repository-refs` job of `.github/workflows/cron-update.yml` opens one PR per changed role, and `tests/external/update/repository/` warns about pending bumps and fails on a commit SHA that a release tag already contains. A pin newer than the newest release keeps following the tip, so no pin moves back to an older release. +Every update PR carries the label `update` and one of `major`, `minor` or `patch`: the highest step among its changed versions, read by [level.py](../../../utils/update/level.py). A change that is no number step (a commit SHA, a SHA moving to a tag) counts as `major`. + ## Declared version sources A pin the Docker updater (`image` + `version`) and the repository updater diff --git a/cli/contributing/update/label/__init__.py b/cli/contributing/update/label/__init__.py new file mode 100644 index 0000000000..ead172a6cf --- /dev/null +++ b/cli/contributing/update/label/__init__.py @@ -0,0 +1,30 @@ +"""Labels an update pull request carries: ``update`` plus its semver level.""" + +from __future__ import annotations + +from typing import NamedTuple + + +class Label(NamedTuple): + """One repository label. + + Args: + name: the label name. + color: the six-digit hex colour, without ``#``. + description: the text the repository's label list shows. + """ + + name: str + color: str + description: str + + +UPDATE = Label("update", "0366D6", "Automated dependency or version update") +MAJOR = Label( + "major", "B60205", "Update raises a major version, or one of unknown reach" +) +MINOR = Label("minor", "FBCA04", "Update raises a minor version") +PATCH = Label("patch", "0E8A16", "Update raises a patch version") +LEVELS = (MAJOR, MINOR, PATCH) + +__all__ = ["LEVELS", "MAJOR", "MINOR", "PATCH", "UPDATE", "Label"] diff --git a/cli/contributing/update/label/__main__.py b/cli/contributing/update/label/__main__.py new file mode 100644 index 0000000000..460c355ccb --- /dev/null +++ b/cli/contributing/update/label/__main__.py @@ -0,0 +1,173 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import subprocess +from typing import TYPE_CHECKING +from urllib.parse import quote + +from . import LEVELS, MAJOR, MINOR, PATCH, UPDATE + +if TYPE_CHECKING: + from collections.abc import Callable, Iterable, Sequence + + from . import Label + +GH_TIMEOUT_SECONDS = 120 +_LEVEL_OF_UPDATE_TYPE = { + "version-update:semver-major": MAJOR, + "version-update:semver-minor": MINOR, + "version-update:semver-patch": PATCH, +} + + +def level(update_type: str) -> Label: + """The semver label of a Dependabot update. + + Args: + update_type: the ``update-type`` output of ``dependabot/fetch-metadata``. + + Returns: + ``minor`` or ``patch`` for those semver levels, ``major`` for everything + else, so an update of unknown reach is never filed as a small one. + """ + return _LEVEL_OF_UPDATE_TYPE.get(update_type.strip(), MAJOR) + + +def run_gh(args: Sequence[str]) -> str: + return subprocess.run( + ["gh", *args], + capture_output=True, + text=True, + check=True, + timeout=GH_TIMEOUT_SECONDS, + ).stdout + + +def names(gh: Callable[[Sequence[str]], str], path: str) -> set[str]: + """The ``name`` of every label a paginated REST list returns. + + Args: + gh: runs ``gh`` with the given arguments and returns its stdout. + path: the REST path listing the labels. + + Returns: + the label names. + """ + out = gh(["api", "--paginate", path, "--jq", ".[].name"]) + return {line for line in out.splitlines() if line} + + +def ensure_labels( + gh: Callable[[Sequence[str]], str], repo: str, labels: Iterable[Label] +) -> list[str]: + """Create the labels the repository lacks, leaving existing ones untouched. + + Args: + gh: runs ``gh`` with the given arguments and returns its stdout. + repo: ``owner/name``. + labels: the labels that must exist. + + Returns: + the names created. A create that fails because a parallel run created + the label first counts as done; any other failure raises. + """ + existing = names(gh, f"repos/{repo}/labels") + created: list[str] = [] + for label in labels: + if label.name in existing: + continue + try: + gh( + [ + "label", + "create", + label.name, + "--repo", + repo, + "--color", + label.color, + "--description", + label.description, + ] + ) + except subprocess.CalledProcessError: + if label.name not in names(gh, f"repos/{repo}/labels"): + raise + continue + created.append(label.name) + return created + + +def sync( + gh: Callable[[Sequence[str]], str], repo: str, pr: int, update_type: str +) -> list[str]: + """Leave *pr* carrying ``update`` and exactly one semver label. + + Args: + gh: runs ``gh`` with the given arguments and returns its stdout. + repo: ``owner/name``. + pr: the pull request number. + update_type: the ``update-type`` output of ``dependabot/fetch-metadata``. + + Returns: + what was done, one line per action. A label the pull request already + carries is not added again: a ``labeled`` event restarts its CI run. + """ + wanted = (UPDATE, level(update_type)) + actions = [f"created label {name}" for name in ensure_labels(gh, repo, wanted)] + current = names(gh, f"repos/{repo}/issues/{pr}/labels") + for stale in LEVELS: + if stale not in wanted and stale.name in current: + gh( + [ + "api", + "--method", + "DELETE", + f"repos/{repo}/issues/{pr}/labels/{quote(stale.name)}", + ] + ) + actions.append(f"removed {stale.name}") + missing = [label.name for label in wanted if label.name not in current] + if missing: + args = ["api", "--method", "POST", f"repos/{repo}/issues/{pr}/labels"] + for name in missing: + args += ["-f", f"labels[]={name}"] + gh(args) + actions.append(f"added {', '.join(missing)}") + return actions + + +def main(argv: Sequence[str] | None = None) -> int: + parser = argparse.ArgumentParser( + description=( + "Label a Dependabot pull request `update` plus exactly one of " + "`major`, `minor` and `patch`, creating labels the repository lacks." + ) + ) + parser.add_argument("--repo", required=True, help="owner/name") + parser.add_argument( + "--ensure-only", + action="store_true", + help="Only create the update labels the repository lacks", + ) + parser.add_argument("--pr", type=int, help="Pull request number") + parser.add_argument( + "--update-type", + help="update-type output of dependabot/fetch-metadata, possibly empty", + ) + args = parser.parse_args(argv) + if args.ensure_only: + for name in ensure_labels(run_gh, args.repo, (UPDATE, *LEVELS)): + print(f"created label {name}") + return 0 + if args.pr is None or args.update_type is None: + parser.error("--pr and --update-type are required without --ensure-only") + actions = sync(run_gh, args.repo, args.pr, args.update_type) + for line in actions or [f"#{args.pr} already carries its labels"]: + print(line) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/github/update/open/pr.sh b/scripts/github/update/open/pr.sh index c99fa9170f..d59abbc00d 100755 --- a/scripts/github/update/open/pr.sh +++ b/scripts/github/update/open/pr.sh @@ -44,6 +44,9 @@ fi git commit -m "${UPDATE_COMMIT_MESSAGE}" +UPDATE_LEVEL="$(python3 -m utils.update.level HEAD~1 HEAD)" +echo "Update level: ${UPDATE_LEVEL}" + fingerprint_ref() { local ref="$1" shift @@ -115,6 +118,8 @@ git push --force \ "https://x-access-token:${GH_TOKEN}@github.com/${REPO}.git" \ "HEAD:refs/heads/${BRANCH}" +python3 -m cli.contributing.update.label --repo "${REPO}" --ensure-only + PR_NUMBER="$( gh pr list \ --repo "${REPO}" \ @@ -129,7 +134,9 @@ if [[ -n "${PR_NUMBER}" ]]; then gh pr edit "${PR_NUMBER}" \ --repo "${REPO}" \ --title "${UPDATE_PR_TITLE}" \ - --body "${UPDATE_PR_BODY}" + --body "${UPDATE_PR_BODY}" \ + --add-label update \ + --add-label "${UPDATE_LEVEL}" else echo "Creating PR for ${BRANCH}" PR_URL="$( @@ -138,7 +145,9 @@ else --title "${UPDATE_PR_TITLE}" \ --body "${UPDATE_PR_BODY}" \ --base "${UPDATE_BASE_BRANCH}" \ - --head "${OWNER}:${BRANCH}" + --head "${OWNER}:${BRANCH}" \ + --label update \ + --label "${UPDATE_LEVEL}" )" PR_NUMBER="${PR_URL##*/}" echo "Created PR #${PR_NUMBER}: ${PR_URL}" diff --git a/tests/unit/python/cli/contributing/update/__init__.py b/tests/unit/python/cli/contributing/update/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/cli/contributing/update/label/__init__.py b/tests/unit/python/cli/contributing/update/label/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/cli/contributing/update/label/test_main.py b/tests/unit/python/cli/contributing/update/label/test_main.py new file mode 100644 index 0000000000..6681d02cf2 --- /dev/null +++ b/tests/unit/python/cli/contributing/update/label/test_main.py @@ -0,0 +1,137 @@ +from __future__ import annotations + +import io +import subprocess +import unittest +from contextlib import redirect_stdout +from unittest import mock + +import cli.contributing.update.label.__main__ as label_main + +REPO = "infinito-nexus/core" + + +class FakeGh: + """Answers the label reads and records every write. + + Args: + repository: label names the repository has. + pull_request: label names pull request 4 carries. + racing: names whose create fails because a parallel run made them. + """ + + def __init__(self, repository, pull_request, racing=()): + self.repository = set(repository) + self.pull_request = set(pull_request) + self.racing = set(racing) + self.writes = [] + + def __call__(self, args): + if args[:2] == ["api", "--paginate"]: + names = self.pull_request if "/issues/" in args[2] else self.repository + return "".join(f"{name}\n" for name in sorted(names)) + self.writes.append(list(args)) + if args[:2] == ["label", "create"] and args[2] in self.racing: + self.repository.add(args[2]) + raise subprocess.CalledProcessError(1, ["gh", *args]) + return "" + + +class TestLevel(unittest.TestCase): + def test_semver_levels_map_to_their_label(self): + self.assertEqual( + [ + label_main.level(f"version-update:semver-{name}").name + for name in ("major", "minor", "patch") + ], + ["major", "minor", "patch"], + ) + + def test_an_unknown_or_empty_type_counts_as_major(self): + self.assertEqual( + {label_main.level(kind).name for kind in ("", "security", "semver-minor")}, + {"major"}, + ) + + +class TestSync(unittest.TestCase): + def test_a_bare_pull_request_gets_update_and_its_level(self): + gh = FakeGh({"update", "minor"}, set()) + actions = label_main.sync(gh, REPO, 4, "version-update:semver-minor") + self.assertEqual(actions, ["added update, minor"]) + self.assertEqual( + gh.writes, + [ + [ + "api", + "--method", + "POST", + f"repos/{REPO}/issues/4/labels", + "-f", + "labels[]=update", + "-f", + "labels[]=minor", + ] + ], + ) + + def test_labels_already_present_cause_no_write(self): + gh = FakeGh({"update", "patch"}, {"update", "patch", "dependencies"}) + self.assertEqual( + label_main.sync(gh, REPO, 4, "version-update:semver-patch"), [] + ) + self.assertEqual(gh.writes, []) + + def test_a_stale_level_is_removed(self): + gh = FakeGh({"update", "major", "minor"}, {"update", "minor"}) + actions = label_main.sync(gh, REPO, 4, "version-update:semver-major") + self.assertEqual(actions, ["removed minor", "added major"]) + + def test_missing_repository_labels_are_created_first(self): + gh = FakeGh(set(), set()) + label_main.sync(gh, REPO, 4, "version-update:semver-patch") + created = [write[2] for write in gh.writes if write[:2] == ["label", "create"]] + self.assertEqual(created, ["update", "patch"]) + + def test_a_label_a_parallel_run_created_counts_as_done(self): + gh = FakeGh({"patch"}, set(), racing={"update"}) + actions = label_main.sync(gh, REPO, 4, "version-update:semver-patch") + self.assertEqual(actions, ["added update, patch"]) + + def test_a_create_failure_that_leaves_the_label_missing_raises(self): + gh = FakeGh(set(), set()) + + def failing(args): + if args[:2] == ["label", "create"]: + raise subprocess.CalledProcessError(1, ["gh", *args]) + return gh(args) + + with self.assertRaises(subprocess.CalledProcessError): + label_main.sync(failing, REPO, 4, "") + + +class TestMain(unittest.TestCase): + def test_main_reports_when_nothing_changes(self): + gh = FakeGh({"update", "major"}, {"update", "major"}) + out = io.StringIO() + with mock.patch.object(label_main, "run_gh", gh), redirect_stdout(out): + code = label_main.main(["--repo", REPO, "--pr", "4", "--update-type", ""]) + self.assertEqual((code, out.getvalue()), (0, "#4 already carries its labels\n")) + + def test_ensure_only_creates_the_missing_labels_and_touches_no_pr(self): + gh = FakeGh({"update", "minor"}, set()) + out = io.StringIO() + with mock.patch.object(label_main, "run_gh", gh), redirect_stdout(out): + code = label_main.main(["--repo", REPO, "--ensure-only"]) + created = [w[2] for w in gh.writes if w[:2] == ["label", "create"]] + self.assertEqual((code, created), (0, ["major", "patch"])) + self.assertEqual(len(gh.writes), 2) + + def test_without_ensure_only_the_pr_and_type_are_required(self): + with self.assertRaises(SystemExit) as raised, redirect_stdout(io.StringIO()): + label_main.main(["--repo", REPO, "--pr", "4"]) + self.assertEqual(raised.exception.code, 2) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/utils/update/test_level.py b/tests/unit/python/utils/update/test_level.py new file mode 100644 index 0000000000..e90e0f7c6e --- /dev/null +++ b/tests/unit/python/utils/update/test_level.py @@ -0,0 +1,68 @@ +from __future__ import annotations + +import unittest + +from utils.update.level import bump_level, diff_level, line_level + +SHA_A = "3fa19f8b6d3eecbacbdbf79406e0f877ebe11e26" +SHA_B = "dc95a4d7e7e5531b1fdaa59528121afcffb8b3f0" + + +class TestBumpLevel(unittest.TestCase): + def test_the_first_changed_number_sets_the_level(self) -> None: + self.assertEqual(bump_level("1.2.3", "2.0.0"), "major") + self.assertEqual(bump_level("v8.8.3-alpine", "v8.9.0-alpine"), "minor") + self.assertEqual(bump_level("6.8.0", "6.8.1"), "patch") + self.assertEqual(bump_level("2026.05.18.0", "2026.05.18.1"), "patch") + self.assertEqual(bump_level("24.04", "26.04"), "major") + + def test_a_sha_or_a_numberless_side_is_major(self) -> None: + self.assertEqual(bump_level(SHA_A, SHA_B), "major") + self.assertEqual(bump_level(SHA_A, "v0.1.1"), "major") + self.assertEqual(bump_level("latest", "1.0.0"), "major") + + def test_a_longer_version_with_the_same_prefix_is_patch(self) -> None: + self.assertEqual(bump_level("1.2", "1.2.1"), "patch") + + +class TestLineLevel(unittest.TestCase): + def test_the_first_differing_token_decides(self) -> None: + self.assertEqual( + line_level(' version: "1.2.3"', ' version: "1.3.0"'), "minor" + ) + self.assertEqual(line_level("pkg==4.0.1", "pkg==4.0.2"), "patch") + self.assertEqual( + line_level(" runs-on: ubuntu-24.04", " runs-on: ubuntu-26.04"), + "major", + ) + self.assertEqual(line_level(f" ref: {SHA_A}", " ref: v0.1.1"), "major") + + def test_unpaired_tokens_are_major(self) -> None: + self.assertEqual(line_level("ref: main", "ref: v1.0.0"), "major") + + +class TestDiffLevel(unittest.TestCase): + def test_the_highest_level_of_every_hunk_wins(self) -> None: + diff = ( + "diff --git a/roles/a/meta/services.yml b/roles/a/meta/services.yml\n" + "--- a/roles/a/meta/services.yml\n" + "+++ b/roles/a/meta/services.yml\n" + "@@ -3 +3 @@\n" + '- version: "1.2.3"\n' + '+ version: "1.2.4"\n' + "@@ -9 +9 @@\n" + '- version: "4.1.0"\n' + '+ version: "4.2.0"\n' + ) + self.assertEqual(diff_level(diff), "minor") + + def test_a_hunk_with_unequal_sides_is_major(self) -> None: + diff = "@@ -3 +3,2 @@\n- version: 1.0.0\n+ version: 1.0.1\n+ extra: 1\n" + self.assertEqual(diff_level(diff), "major") + + def test_an_empty_diff_is_major(self) -> None: + self.assertEqual(diff_level(""), "major") + + +if __name__ == "__main__": + unittest.main() diff --git a/utils/update/level.py b/utils/update/level.py new file mode 100644 index 0000000000..2af98890af --- /dev/null +++ b/utils/update/level.py @@ -0,0 +1,122 @@ +"""Classify the version step an update commit makes as major, minor or patch. + +Standard library only: the runner-label update job installs no dependencies. + +Usage: ``python3 -m utils.update.level `` prints the highest +level of every version changed between the two revisions. +""" + +from __future__ import annotations + +import re +import subprocess +import sys + +LEVELS = ("patch", "minor", "major") +_SHA_RE = re.compile(r"[0-9a-f]{40}") +_VERSION_TOKEN_RE = re.compile(r"[0-9a-f]{40}|\d+(?:\.\d+)*") + + +def bump_level(old: str, new: str) -> str: + """Return the level of the step between two versions. + + Args: + old: version before the update. + new: version after it. + + Returns: + ``major`` when the first number changes or either side is a commit + SHA or carries no number, ``minor`` when the second changes, else + ``patch``. + """ + if _SHA_RE.fullmatch(old) or _SHA_RE.fullmatch(new): + return "major" + old_parts = re.findall(r"\d+", old) + new_parts = re.findall(r"\d+", new) + if not old_parts or not new_parts: + return "major" + for index, (before, after) in enumerate(zip(old_parts, new_parts, strict=False)): + if int(before) != int(after): + return LEVELS[max(0, 2 - index)] + return "patch" + + +def line_level(old: str, new: str) -> str: + """Return the level of one rewritten line. + + Args: + old: the line before the update. + new: the line after it. + + Returns: + The level of the first version token that differs; ``major`` when + the lines carry a different number of version tokens or none differs. + """ + old_tokens = _VERSION_TOKEN_RE.findall(old) + new_tokens = _VERSION_TOKEN_RE.findall(new) + if len(old_tokens) != len(new_tokens): + return "major" + for before, after in zip(old_tokens, new_tokens, strict=True): + if before != after: + return bump_level(before, after) + return "major" + + +def diff_level(diff: str) -> str: + """Return the highest level of every line pair a ``-U0`` diff rewrites. + + Args: + diff: output of ``git diff -U0``. + + Returns: + The highest level; ``major`` when a hunk removes and adds a different + number of lines or the diff rewrites nothing. + """ + levels: list[str] = [] + removed: list[str] = [] + added: list[str] = [] + + def flush() -> None: + if len(removed) != len(added): + levels.append("major") + levels.extend(line_level(o, n) for o, n in zip(removed, added, strict=False)) + removed.clear() + added.clear() + + for line in diff.splitlines(): + if line.startswith(("--- ", "+++ ")): + continue + if line.startswith("@@"): + flush() + elif line.startswith("-"): + removed.append(line[1:]) + elif line.startswith("+"): + added.append(line[1:]) + flush() + return max(levels, key=LEVELS.index, default="major") + + +def main(argv: list[str]) -> int: + """Print the level of the update between two revisions. + + Args: + argv: ``[base, head]`` revisions passed to ``git diff``. + + Returns: + Exit status 0, or 2 on a usage error. + """ + if len(argv) != 2: + print("usage: python3 -m utils.update.level ", file=sys.stderr) + return 2 + diff = subprocess.run( + ["git", "diff", "-U0", argv[0], argv[1]], + capture_output=True, + text=True, + check=True, + ).stdout + print(diff_level(diff)) + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:]))