From 41c1d7184b8c1079b6c4360a1af2d95cb3005579 Mon Sep 17 00:00:00 2001 From: TheMeinerLP Date: Fri, 20 Nov 2026 17:53:06 +0100 Subject: [PATCH] ci(release): cut the release branch when a new line ships When a release with patch 0 ships on main, the line before it enters its security window and needs a branch to receive backports. Cutting that branch by hand from the right tag is easy to get wrong, because main already holds the new line. A cut-release-branch job now runs after such a release. It asks release_branch.py, which gains a command line, for the decision: it creates release/.x at the last tag of the previous line, leaves an existing branch at that tag alone and fails on one that points elsewhere. It then creates the backport label and a tracking issue, and opens a pull request that lists the new line in support-lines.json and renders the tables, so main only changes through review. A patch release changes nothing. Signed-off-by: TheMeinerLP --- .github/scripts/release_branch.py | 108 ++++++++++++++++- .github/scripts/tests/test_release_branch.py | 109 ++++++++++++++++++ .../tests/test_release_branch_cut_job.py | 71 ++++++++++++ .github/workflows/release-please.yml | 108 +++++++++++++++++ 4 files changed, 395 insertions(+), 1 deletion(-) create mode 100644 .github/scripts/tests/test_release_branch_cut_job.py diff --git a/.github/scripts/release_branch.py b/.github/scripts/release_branch.py index 95bfda6b87..27a03f6237 100644 --- a/.github/scripts/release_branch.py +++ b/.github/scripts/release_branch.py @@ -15,12 +15,25 @@ The tags are given as a mapping from tag name to the commit it points at. The standard library and `release_tags` only, so the decision needs no network, no clock and no file. + +The command line wires the decision into the `cut-release-branch` job of .github/workflows/release-please.yml: + +- `cut VERSION` reads `git ls-remote --tags --heads` output on stdin and prints the decision as `key=value` lines for + `$GITHUB_OUTPUT`. It exits 1 on a refusal. +- `add-line LINE DATE --file support-lines.json` lists the line that shipped on DATE as the latest line and opens the + window of the line before it. The date is a parameter, so the script never reads the clock. """ +import argparse +import copy +import datetime +import json +import sys from dataclasses import dataclass -from typing import Mapping, Optional, Tuple +from typing import IO, Dict, List, Mapping, Optional, Tuple from release_tags import VERSION_PATTERN, parse_version +from render_support_tables import WINDOW_DAYS @dataclass(frozen=True) @@ -72,3 +85,96 @@ def decide_cut(released: str, tags: Mapping[str, str], branch_sha: Optional[str] base_sha=base_sha, reason=f"{branch} exists and does not point at {base_tag}, the maintainer decides how to continue", ) + + +def parse_ls_remote(listing: str) -> Tuple[Dict[str, str], Dict[str, str]]: + """Reads `git ls-remote` output into tag name to commit and branch name to commit. + + An annotated tag appears twice; its peeled `^{}` entry names the commit and wins over the tag object. + """ + tags: Dict[str, str] = {} + heads: Dict[str, str] = {} + peeled = set() + for row in listing.splitlines(): + if "\t" not in row: + continue + sha, ref = row.strip().split("\t", 1) + if ref.startswith("refs/heads/"): + heads[ref[len("refs/heads/"):]] = sha + elif ref.startswith("refs/tags/"): + name = ref[len("refs/tags/"):] + if name.endswith("^{}"): + name = name[:-3] + tags[name] = sha + peeled.add(name) + elif name not in peeled: + tags[name] = sha + return tags, heads + + +def add_line(lines: List[dict], line: str, released: str) -> List[dict]: + """Returns the lines with `line` listed first as latest, released on `released`. + + The line that was latest becomes `previous`, and its window ends WINDOW_DAYS after `released`. A line that is already + listed changes nothing, so a rerun never moves a window. The input is not modified. + """ + if any(entry.get("line") == line for entry in lines): + return copy.deepcopy(lines) + end_of_life = datetime.date.fromisoformat(released) + datetime.timedelta(days=WINDOW_DAYS) + updated = [{"line": line, "kind": "regular", "status": "latest", "released": released}] + for entry in copy.deepcopy(lines): + if entry.get("status") == "latest": + entry["status"] = "previous" + entry["end_of_life"] = end_of_life.isoformat() + updated.append(entry) + return updated + + +def format_lines(lines: List[dict]) -> str: + """Writes the file with one entry per line, the layout support-lines.json is kept in.""" + entries = [" { " + json.dumps(entry)[1:-1] + " }" for entry in lines] + return '{\n "lines": [\n' + ",\n".join(entries) + "\n ]\n}\n" + + +def main(argv: List[str], stdin: Optional[IO[str]] = None, stdout: Optional[IO[str]] = None) -> int: + """Runs one command for the cut job. See the module documentation.""" + parser = argparse.ArgumentParser(prog="release_branch.py", description=__doc__.splitlines()[0]) + commands = parser.add_subparsers(dest="command", required=True) + cut = commands.add_parser("cut", help="decide the cut for a release, reading ls-remote output on stdin") + cut.add_argument("version") + add = commands.add_parser("add-line", help="list a new latest line in support-lines.json") + add.add_argument("line") + add.add_argument("released") + add.add_argument("--file", required=True) + args = parser.parse_args(argv) + + stdin = stdin if stdin is not None else sys.stdin + stdout = stdout if stdout is not None else sys.stdout + + if args.command == "add-line": + with open(args.file, encoding="utf-8") as handle: + data = json.load(handle) + data["lines"] = add_line(data["lines"], args.line, args.released) + with open(args.file, "w", encoding="utf-8") as handle: + handle.write(format_lines(data["lines"])) + return 0 + + tags, heads = parse_ls_remote(stdin.read()) + branch = decide_cut(args.version, tags, None).branch + decision = decide_cut(args.version, tags, heads.get(branch) if branch else None) + outputs = { + "action": decision.action, + "branch": decision.branch or "", + "base_tag": decision.base_tag or "", + "base_sha": decision.base_sha or "", + "line": decision.branch[len("release/"):-len(".x")] if decision.branch else "", + "new_line": _line_of(parse_version(args.version)), + "reason": decision.reason, + } + for key, value in outputs.items(): + stdout.write(f"{key}={value}\n") + return 1 if decision.action == "refuse" else 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/.github/scripts/tests/test_release_branch.py b/.github/scripts/tests/test_release_branch.py index f4cd0b7230..09ffb580c0 100644 --- a/.github/scripts/tests/test_release_branch.py +++ b/.github/scripts/tests/test_release_branch.py @@ -120,5 +120,114 @@ def test_cut_rejects_a_released_version_that_is_not_a_version(self): release_branch.decide_cut("2.0", {"v1.1.1": OLD_LAST_TAG_SHA}, None) +class LsRemoteTest(unittest.TestCase): + + def test_annotated_tag_resolves_to_its_commit(self): + listing = f"9999\trefs/tags/v1.1.1\n{OLD_LAST_TAG_SHA}\trefs/tags/v1.1.1^{{}}\n" + + tags, _ = release_branch.parse_ls_remote(listing) + + self.assertEqual({"v1.1.1": OLD_LAST_TAG_SHA}, tags, "the peeled entry names the commit, not the tag object") + + def test_heads_are_read_by_branch_name(self): + listing = f"{OLD_TIP}\trefs/heads/release/1.1.x\n" + + _, heads = release_branch.parse_ls_remote(listing) + + self.assertEqual({"release/1.1.x": OLD_TIP}, heads, "a head is keyed by the branch name without refs/heads/") + + +class AddLineTest(unittest.TestCase): + + def lines(self): + return [{"line": "1.1", "kind": "regular", "status": "latest", "released": "2026-08-09"}] + + def test_new_line_becomes_the_latest_line_on_top(self): + updated = release_branch.add_line(self.lines(), "2.0", "2026-12-01") + + self.assertEqual({"line": "2.0", "kind": "regular", "status": "latest", "released": "2026-12-01"}, updated[0], + "the line that just shipped is listed first as latest") + + def test_old_latest_line_opens_its_window_of_ninety_days(self): + updated = release_branch.add_line(self.lines(), "2.0", "2026-12-01") + + self.assertEqual("previous", updated[1]["status"], "the superseded line receives security fixes") + self.assertEqual("2027-03-01", updated[1]["end_of_life"], "the window ends 90 days after the ship date") + + def test_adding_a_listed_line_changes_nothing(self): + once = release_branch.add_line(self.lines(), "2.0", "2026-12-01") + + self.assertEqual(once, release_branch.add_line(once, "2.0", "2026-12-02"), "a rerun never shifts the window") + + def test_input_is_not_modified(self): + lines = self.lines() + release_branch.add_line(lines, "2.0", "2026-12-01") + + self.assertEqual(self.lines(), lines, "the caller keeps its own list") + + +class CommandLineTest(unittest.TestCase): + + def run_cli(self, argv, stdin_text=""): + import io + + stdout = io.StringIO() + code = release_branch.main(argv, stdin=io.StringIO(stdin_text), stdout=stdout) + return code, stdout.getvalue() + + def test_cut_command_prints_the_outputs_of_a_create(self): + listing = f"{OLD_LAST_TAG_SHA}\trefs/tags/v1.1.1\n{MAIN_TIP}\trefs/tags/v2.0.0\n" + + code, out = self.run_cli(["cut", "2.0.0"], listing) + + self.assertEqual(0, code, "a cut is not a failure") + self.assertIn("action=create\n", out, "the job reads the action") + self.assertIn("branch=release/1.1.x\n", out, "the job reads the branch") + self.assertIn(f"base_sha={OLD_LAST_TAG_SHA}\n", out, "the job creates the branch at the old tag") + self.assertIn("line=1.1\n", out, "the job names the label and the issue after the old line") + self.assertIn("new_line=2.0\n", out, "the job adds the new line to support-lines.json") + + def test_cut_command_reads_the_existing_branch(self): + listing = f"{OLD_LAST_TAG_SHA}\trefs/tags/v1.1.1\n{OLD_LAST_TAG_SHA}\trefs/heads/release/1.1.x\n" + + code, out = self.run_cli(["cut", "2.0.0"], listing) + + self.assertEqual(0, code, "a rerun is not a failure") + self.assertIn("action=exists\n", out, "a branch at the old tag is left alone") + + def test_cut_command_fails_on_a_refusal(self): + listing = f"{OLD_LAST_TAG_SHA}\trefs/tags/v1.1.1\n{OLD_TIP}\trefs/heads/release/1.1.x\n" + + code, out = self.run_cli(["cut", "2.0.0"], listing) + + self.assertEqual(1, code, "a branch that points elsewhere stops the job") + self.assertIn("action=refuse\n", out, "the refusal is still reported") + + def test_add_line_command_rewrites_the_file_in_its_own_layout(self): + import tempfile + + with tempfile.TemporaryDirectory() as root: + path = os.path.join(root, "support-lines.json") + with open(path, "w", encoding="utf-8") as handle: + handle.write('{\n "lines": [\n' + ' { "line": "1.1", "kind": "regular", "status": "latest", "released": "2026-08-09" }\n' + ' ]\n}\n') + + code, _ = self.run_cli(["add-line", "2.0", "2026-12-01", "--file", path]) + + with open(path, encoding="utf-8") as handle: + written = handle.read() + + self.assertEqual(0, code, "adding a line succeeds") + self.assertEqual( + '{\n "lines": [\n' + ' { "line": "2.0", "kind": "regular", "status": "latest", "released": "2026-12-01" },\n' + ' { "line": "1.1", "kind": "regular", "status": "previous", "released": "2026-08-09", "end_of_life": "2027-03-01" }\n' + ' ]\n}\n', + written, + "one line per entry, as the file is written by hand", + ) + + if __name__ == "__main__": unittest.main() diff --git a/.github/scripts/tests/test_release_branch_cut_job.py b/.github/scripts/tests/test_release_branch_cut_job.py new file mode 100644 index 0000000000..afab6ce32c --- /dev/null +++ b/.github/scripts/tests/test_release_branch_cut_job.py @@ -0,0 +1,71 @@ +"""Shape tests for the cut-release-branch job of .github/workflows/release-please.yml. + +When a new line ships on main (a release with patch 0), the job cuts `release/.x` from the last tag of +that line, creates the `backport:` label and a tracking issue, and opens the pull request that adds the new line to +support-lines.json (design decision 2). The decision itself is tested in test_release_branch.py; these tests guard the +wiring. Each test reads the workflow file fresh. + +Run from the repository root: + + python3 -m unittest discover -s .github/scripts/tests -t .github/scripts/tests -v +""" + +import os +import unittest + +import yaml + +TESTS_DIR = os.path.dirname(os.path.abspath(__file__)) +GITHUB_DIR = os.path.dirname(os.path.dirname(TESTS_DIR)) +RELEASE_WORKFLOW = os.path.join(GITHUB_DIR, "workflows", "release-please.yml") +JOB = "cut-release-branch" + + +def load_job(): + with open(RELEASE_WORKFLOW, encoding="utf-8") as handle: + return yaml.safe_load(handle)["jobs"].get(JOB) + + +def run_text(job): + return "\n".join(step.get("run") or "" for step in job.get("steps", [])) + + +class CutReleaseBranchJobTest(unittest.TestCase): + + def test_job_exists(self): + self.assertIsNotNone(load_job(), f"release-please.yml needs a {JOB} job") + + def test_job_runs_only_after_a_release_on_main(self): + job = load_job() + self.assertIn("release-please", job.get("needs"), "the cut follows the release that ships the new line") + self.assertIn("needs.release-please.outputs.release_created == 'true'", job["if"], "no release, no cut") + self.assertIn("github.ref == 'refs/heads/main'", job["if"], "only a new line on main cuts a branch") + + def test_decision_comes_from_the_tested_script(self): + self.assertIn("release_branch.py cut", run_text(load_job()), "the YAML only wires the tested decision") + + def test_branch_is_created_only_on_a_create_decision(self): + steps = [step for step in load_job()["steps"] if "git/refs" in (step.get("run") or "")] + self.assertEqual(1, len(steps), "exactly one step creates the branch") + self.assertIn("steps.cut.outputs.action == 'create'", steps[0].get("if", ""), + "an existing branch is never moved and a refusal never creates one") + + def test_job_creates_the_backport_label_and_the_tracking_issue(self): + text = run_text(load_job()) + self.assertIn("gh label create", text, "the backport label of the line is created") + self.assertIn("gh issue create", text, "a tracking issue names the end of the window") + + def test_support_lines_change_through_a_reviewed_pull_request(self): + text = run_text(load_job()) + self.assertIn("release_branch.py add-line", text, "the new line is added by the tested script") + self.assertIn("render_support_tables.py --mode write", text, "the tables follow the file") + self.assertIn("gh pr create", text, "main changes only through review") + self.assertNotIn("git push origin main", text, "the job never pushes to main") + + def test_job_token_is_limited(self): + self.assertEqual({"contents": "read", "issues": "write"}, load_job().get("permissions"), + "pushes and pull requests use the release bot token, the job token only writes issues") + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/workflows/release-please.yml b/.github/workflows/release-please.yml index 2ba2d57ebc..f81b77889d 100644 --- a/.github/workflows/release-please.yml +++ b/.github/workflows/release-please.yml @@ -1039,3 +1039,111 @@ jobs: "ghcr.io/onelitefeathernet/ingot@$SERVER_DIGEST" cosign verify --certificate-identity "$SIGNER_IDENTITY" --certificate-oidc-issuer "$OIDC_ISSUER" \ "ghcr.io/onelitefeathernet/ingot-dashboard@$DASHBOARD_DIGEST" + + # A release with patch 0 on main ships a new line, and the line before it keeps receiving + # security fixes for its window. This job cuts `release/.x` from the last + # tag of that line, never from main, which already holds the new line. It also creates the + # backport label and a tracking issue, and opens the pull request that lists the new line in + # support-lines.json, so main only changes through review. The decision lives in + # .github/scripts/release_branch.py and its tests. A rerun finds everything in place and + # does nothing; a branch that points elsewhere fails the job and is never moved. + cut-release-branch: + name: "Cut the release branch of the previous line" + needs: release-please + if: needs.release-please.outputs.release_created == 'true' && github.ref == 'refs/heads/main' + runs-on: ubuntu-latest + permissions: + contents: read + issues: write + steps: + # The release bot pushes the branch past a protection rule that allows only that actor, + # and opens the pull request so its checks run. + - name: "Create release bot token" + id: app-token + uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0 + with: + client-id: ${{ secrets.RELEASE_PLEASE_APP_CLIENT_ID }} + private-key: ${{ secrets.RELEASE_PLEASE_APP_PRIVATE_KEY }} + permission-contents: write + permission-pull-requests: write + + - name: "Checkout repository" + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + token: ${{ steps.app-token.outputs.token }} + + - name: "Decide the cut" + id: cut + env: + VERSION: ${{ needs.release-please.outputs.version }} + run: | + set -euo pipefail + released="$(date -u +%F)" + { + echo "released=${released}" + echo "end_of_life=$(date -u -d "${released} + 90 days" +%F)" + } >> "$GITHUB_OUTPUT" + git ls-remote --tags --heads origin \ + | python3 .github/scripts/release_branch.py cut "$VERSION" | tee -a "$GITHUB_OUTPUT" + + - name: "Create the release branch" + if: steps.cut.outputs.action == 'create' + env: + GH_TOKEN: ${{ steps.app-token.outputs.token }} + BRANCH: ${{ steps.cut.outputs.branch }} + BASE_SHA: ${{ steps.cut.outputs.base_sha }} + BASE_TAG: ${{ steps.cut.outputs.base_tag }} + run: | + set -euo pipefail + gh api "repos/${GITHUB_REPOSITORY}/git/refs" -f ref="refs/heads/${BRANCH}" -f sha="$BASE_SHA" > /dev/null + echo "Created ${BRANCH} at ${BASE_TAG}." + + - name: "Create the backport label and the tracking issue" + if: steps.cut.outputs.action == 'create' || steps.cut.outputs.action == 'exists' + env: + GH_TOKEN: ${{ github.token }} + LINE: ${{ steps.cut.outputs.line }} + BRANCH: ${{ steps.cut.outputs.branch }} + END_OF_LIFE: ${{ steps.cut.outputs.end_of_life }} + run: | + set -euo pipefail + label="backport:${LINE}" + if ! gh label list --repo "$GITHUB_REPOSITORY" --limit 500 --json name --jq '.[].name' | grep -qxF "$label"; then + gh label create "$label" --repo "$GITHUB_REPOSITORY" --color "d93f0b" \ + --description "Backport a security fix to ${BRANCH}" + fi + if gh issue list --repo "$GITHUB_REPOSITORY" --state all --limit 100 --search "Window for ${LINE} ends on in:title" \ + --json title --jq '.[].title' | grep -qF "Window for ${LINE} ends on "; then + echo "A tracking issue for ${LINE} exists." + else + gh issue create --repo "$GITHUB_REPOSITORY" --title "Window for ${LINE} ends on ${END_OF_LIFE}" \ + --body "The ${LINE} line receives security fixes on \`${BRANCH}\` until ${END_OF_LIFE}. Label a merged \`fix(security)\` pull request into main with \`${label}\` to backport it." + fi + + - name: "Open the pull request that lists the new line" + if: steps.cut.outputs.action == 'create' || steps.cut.outputs.action == 'exists' + env: + GH_TOKEN: ${{ steps.app-token.outputs.token }} + NEW_LINE: ${{ steps.cut.outputs.new_line }} + RELEASED: ${{ steps.cut.outputs.released }} + run: | + set -euo pipefail + work="release-lines/${NEW_LINE}" + if git ls-remote --exit-code --heads origin "refs/heads/${work}" > /dev/null; then + echo "${work} already exists, nothing to do." + exit 0 + fi + python3 .github/scripts/release_branch.py add-line "$NEW_LINE" "$RELEASED" --file support-lines.json + python3 .github/scripts/render_support_tables.py --mode write + if git diff --quiet; then + echo "support-lines.json already lists ${NEW_LINE}." + exit 0 + fi + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + git switch -c "$work" + git commit -s -am "docs(support): list the ${NEW_LINE} line in the support tables" + git push origin "$work" + gh pr create --base main --head "$work" \ + --title "docs(support): list the ${NEW_LINE} line in the support tables" \ + --body "The ${NEW_LINE} line shipped on ${RELEASED}. This lists it as the latest line in \`support-lines.json\`, opens the 90 day security window of the line before it and renders the tables of \`SUPPORT.md\` and \`.github/SECURITY.md\`."