Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
108 changes: 107 additions & 1 deletion .github/scripts/release_branch.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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:]))
109 changes: 109 additions & 0 deletions .github/scripts/tests/test_release_branch.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
71 changes: 71 additions & 0 deletions .github/scripts/tests/test_release_branch_cut_job.py
Original file line number Diff line number Diff line change
@@ -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/<previous line>.x` from the last tag of
that line, creates the `backport:<line>` 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()
Loading
Loading