mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-22 13:29:19 +08:00
## Description Merging release PR #4643 did not create `v0.43.0` because its body contained repeated carriage returns (`CRCRLF`). Release Please removes one CRLF layer and then looks for exact `---` delimiter lines; the leftover CR prevents release detection. The merge-triggered [run](https://github.com/headroomlabs-ai/headroom/actions/runs/42065983322) succeeded while logging `Pull request body did not match` and `could not parse pull request body as a release PR`, leaving #4643 labeled `autorelease: pending` and opening #4661 from the old release baseline. Normalize only the damaged envelope before Release Please reads pending merged releases. Eligibility requires a merged bot PR, a main base, a release-please main branch in this repository, the pending label, and repeated-CR damage. Ordinary CRLF, open PRs, human PRs, forks and unrelated historical bodies are untouched. The normalized body must still have a valid release-note envelope. JSON is sent through stdin, avoiding another Windows text-file conversion. The malformed body came from Windows text-mode maintainer tooling, not contributor runtime code. That local writer has separately been corrected to preserve LF. ## Type of Change - [x] Bug fix (release automation) ## Changes Made - Add a narrow, default-read-only body normalizer and tests. - Run it with the workflow's existing release credential before release detection. - Allowlist the checked-in helper in `.gitignore`. ## Testing - `pytest scripts/tests/test_normalize_release_pr_bodies.py tests/test_release_workflows.py -q`: **75 passed**. - Ruff 0.17.3 check/format and `git diff --check`: pass. - `actionlint .github/workflows/release-please.yml`: pass. - Regression tests demonstrate the old exact-delimiter parser fails on CRCRLF, then verify repaired delimiters, eligibility exclusions, dry-run no writes, JSON-stdin transport and workflow ordering. ## Real Behavior Proof - Environment: Windows, Python 3.12.13, gh CLI; current main `8d3e9e5ca`. - Exact command: `python scripts/normalize_release_pr_bodies.py --repo headroomlabs-ai/headroom` (default read-only). - Observed result: `Would normalize release PR #4643`, exit 0. Other historical pending PR formats were not edited. Current GitHub has no `v0.43.0` tag/release; the exact merge-triggered log identifies the failed body parse above. - Not tested: deliberately did not run `--apply`, repair the live body, create a tag/release, dispatch a release workflow, or publish packages. No hosted release recovery is claimed. ## Runtime Rollout Safety - Rollout-managed feature(s): none; trusted main release automation only. - Stable/default behavior changed: on the next normal main push after this fix merges, the workflow can normalize #4643's damaged body and let Release Please create its pending release. This is the intended recovery; review this effect before merging. - Disable/rollback: revert the normalization step. The helper defaults to read-only when invoked manually without `--apply`. - No package versions, notes, labels, tags or releases are directly changed by the helper; Release Please retains those responsibilities. ## Review Readiness - [ ] This PR is ready for human merge review (draft pending independent review/hosted checks). ## Additional Notes Do not manually remove repeated generated entries from #4661. Once 0.43.0 is recovered, release notes should be regenerated from that proper baseline. This PR does not perform that recovery or change generated `CHANGELOG.md` itself.
96 lines
3.6 KiB
Python
96 lines
3.6 KiB
Python
"""Repair newline-damaged merged release-please bodies before release detection.
|
|
|
|
Windows text-mode writes can turn existing CRLF into CRCRLF. release-please
|
|
normalizes CRLF once and then looks for an exact ``---`` line, so the remaining
|
|
CR hides its envelope and a successful run silently skips the pending release.
|
|
This tool only repairs merged, pending release PRs on the configured base.
|
|
It never changes labels, tags, releases, release notes, or package versions.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import json
|
|
import os
|
|
import re
|
|
import subprocess
|
|
from typing import Any
|
|
from urllib.parse import urlencode
|
|
|
|
|
|
def github_json(endpoint: str, **payload: Any) -> Any:
|
|
command = ["gh", "api", endpoint]
|
|
if payload:
|
|
command.extend(["--method", "PATCH", "--input", "-"])
|
|
result = subprocess.run(
|
|
command,
|
|
input=json.dumps(payload) if payload else None,
|
|
capture_output=True,
|
|
text=True,
|
|
encoding="utf-8",
|
|
check=True,
|
|
)
|
|
return json.loads(result.stdout)
|
|
|
|
|
|
def normalize_body(body: str) -> str:
|
|
"""Collapse CR runs before LF without altering note content or blank lines."""
|
|
return re.sub(r"\r+\n", "\n", body)
|
|
|
|
|
|
def repair_release(repo: str, pr: dict[str, Any], *, apply: bool = True) -> bool:
|
|
if (
|
|
not pr.get("merged_at")
|
|
or pr.get("base", {}).get("ref") != "main"
|
|
or pr.get("user", {}).get("type") != "Bot"
|
|
or (pr.get("head", {}).get("repo") or {}).get("full_name") != repo
|
|
or not pr.get("head", {}).get("ref", "").startswith("release-please--branches--main--")
|
|
or "autorelease: pending" not in {label["name"] for label in pr.get("labels", [])}
|
|
):
|
|
return False
|
|
body = pr.get("body") or ""
|
|
# Normal CRLF already works. Do not rewrite unrelated historical formats.
|
|
if not re.search(r"\r{2,}\n", body):
|
|
return False
|
|
normalized = normalize_body(body)
|
|
# Match the structural boundary release-please needs, not an arbitrary body
|
|
# containing a version somewhere in its maintainer comments.
|
|
lines = normalized.strip().split("\n")
|
|
delimiters = [i for i, line in enumerate(lines) if line == "---"]
|
|
if len(delimiters) < 2 or not re.search(
|
|
r"^#{2,} \[?\d+\.\d+\.\d+", "\n".join(lines[delimiters[0] + 1 : delimiters[-1]]), re.M
|
|
):
|
|
raise ValueError(f"PR #{pr['number']} lacks a parseable release-please envelope")
|
|
if body == normalized:
|
|
return False
|
|
if apply:
|
|
github_json(f"repos/{repo}/pulls/{pr['number']}", body=normalized)
|
|
print(f"{'Normalized' if apply else 'Would normalize'} release PR #{pr['number']}")
|
|
return True
|
|
|
|
|
|
def main() -> None:
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--repo", default=os.environ.get("GITHUB_REPOSITORY"), required=False)
|
|
parser.add_argument("--apply", action="store_true", help="Write only normalized PR body text")
|
|
args = parser.parse_args()
|
|
if not args.repo or not re.fullmatch(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+", args.repo):
|
|
parser.error("--repo must be owner/repository")
|
|
page = 1
|
|
while True:
|
|
query = urlencode(
|
|
{"state": "closed", "labels": "autorelease: pending", "per_page": 100, "page": page}
|
|
)
|
|
issues = github_json(f"repos/{args.repo}/issues?{query}")
|
|
for issue in issues:
|
|
if "pull_request" in issue:
|
|
pr = github_json(f"repos/{args.repo}/pulls/{issue['number']}")
|
|
repair_release(args.repo, pr, apply=args.apply)
|
|
if len(issues) < 100:
|
|
return
|
|
page += 1
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|