187 lines
6.6 KiB
Python
187 lines
6.6 KiB
Python
#!/usr/bin/env python3
|
|||
|
|
"""Release tool implementing AGENTS.md (Version bump, Commit, Tag).
|
||
|
|
|
||
|
|
Stages (dry-run unless --apply):
|
||
|
|
prepare parse commits since the last tag, choose the bump, write VERSION
|
||
|
|
and the CHANGELOG.md entry, commit them.
|
||
|
|
tag create the annotated tag vMAJOR.MINOR.PATCH for the VERSION in the
|
||
|
|
tree. Run it only after deploy + verify were green (AGENTS.md:
|
||
|
|
failed verification blocks the tag).
|
||
|
|
|
||
|
|
Rules: Conventional Commits `<type>[(scope)][!]: <description>`, subject max
|
||
|
|
100 chars, allowed types and scopes from AGENTS.md. Malformed commits are
|
||
|
|
counted and listed loudly and skipped before version analysis (history is
|
||
|
|
never rewritten). Bump: any `!` or BREAKING CHANGE -> MAJOR; else any feat ->
|
||
|
|
MINOR; else any fix -> PATCH; else no release. Max 20 changelog lines.
|
||
|
|
Stdlib only.
|
||
|
|
"""
|
||
|
|
import argparse
|
||
|
|
import re
|
||
|
|
import subprocess
|
||
|
|
import sys
|
||
|
|
from datetime import date
|
||
|
|
from pathlib import Path
|
||
|
|
|
||
|
|
ROOT = Path(__file__).resolve().parent.parent
|
||
|
|
TYPES = {"feat", "fix", "docs", "style", "refactor", "perf", "test", "build", "ci", "chore"}
|
||
|
|
SCOPES = {"runtime", "security", "data", "routing", "realtime", "supervisor",
|
||
|
|
"clients", "cli", "workflow"}
|
||
|
|
SUBJECT_MAX = 100
|
||
|
|
CHANGELOG_MAX_LINES = 20
|
||
|
|
PATTERN = re.compile(r"^(?P<type>[a-z]+)(\((?P<scope>[a-z]+)\))?(?P<bang>!)?: (?P<desc>.+)$")
|
||
|
|
SECTION = {"feat": "Features", "fix": "Fixes", "perf": "Performance"}
|
||
|
|
|
||
|
|
|
||
|
|
def git(*args, check=True):
|
||
|
|
r = subprocess.run(["git", *args], cwd=ROOT, capture_output=True, text=True)
|
||
|
|
if check and r.returncode != 0:
|
||
|
|
sys.exit(f"git {' '.join(args)} failed: {r.stderr.strip()}")
|
||
|
|
return r.stdout.strip()
|
||
|
|
|
||
|
|
|
||
|
|
def last_tag():
|
||
|
|
tags = [t for t in git("tag", "--list", "v*.*.*", "--sort=-v:refname").splitlines() if t]
|
||
|
|
return tags[0] if tags else None
|
||
|
|
|
||
|
|
|
||
|
|
def commits_since(tag):
|
||
|
|
rng = f"{tag}..HEAD" if tag else "HEAD"
|
||
|
|
out = git("log", rng, "--format=%H%x1f%s%x1f%b%x1e")
|
||
|
|
items = []
|
||
|
|
for rec in out.split("\x1e"):
|
||
|
|
rec = rec.strip("\n")
|
||
|
|
if not rec:
|
||
|
|
continue
|
||
|
|
h, subject, body = (rec.split("\x1f") + ["", ""])[:3]
|
||
|
|
items.append((h[:9], subject, body))
|
||
|
|
return items
|
||
|
|
|
||
|
|
|
||
|
|
def classify(items):
|
||
|
|
ok, bad = [], []
|
||
|
|
for h, subject, body in items:
|
||
|
|
m = PATTERN.match(subject)
|
||
|
|
reason = None
|
||
|
|
if not m:
|
||
|
|
reason = "not <type>[(scope)][!]: <description>"
|
||
|
|
elif m["type"] not in TYPES:
|
||
|
|
reason = f"type '{m['type']}' not allowed"
|
||
|
|
elif m["scope"] and m["scope"] not in SCOPES:
|
||
|
|
reason = f"scope '{m['scope']}' not allowed"
|
||
|
|
elif len(subject) > SUBJECT_MAX:
|
||
|
|
reason = f"subject over {SUBJECT_MAX} chars"
|
||
|
|
if reason:
|
||
|
|
bad.append((h, subject, reason))
|
||
|
|
else:
|
||
|
|
breaking = bool(m["bang"]) or "BREAKING CHANGE" in body
|
||
|
|
ok.append((h, m["type"], m["scope"], m["desc"], breaking))
|
||
|
|
return ok, bad
|
||
|
|
|
||
|
|
|
||
|
|
def choose_bump(ok):
|
||
|
|
if any(b for *_, b in ok):
|
||
|
|
return "major"
|
||
|
|
if any(t == "feat" for _, t, *_ in ok):
|
||
|
|
return "minor"
|
||
|
|
if any(t == "fix" for _, t, *_ in ok):
|
||
|
|
return "patch"
|
||
|
|
return None
|
||
|
|
|
||
|
|
|
||
|
|
def current_version(tag):
|
||
|
|
if tag:
|
||
|
|
return tuple(int(x) for x in tag[1:].split("."))
|
||
|
|
return (0, 0, 0)
|
||
|
|
|
||
|
|
|
||
|
|
def bumped(v, kind):
|
||
|
|
major, minor, patch = v
|
||
|
|
if kind == "major":
|
||
|
|
return (major + 1, 0, 0)
|
||
|
|
if kind == "minor":
|
||
|
|
return (major, minor + 1, 0)
|
||
|
|
return (major, minor, patch + 1)
|
||
|
|
|
||
|
|
|
||
|
|
def changelog_entry(version, ok, bad):
|
||
|
|
lines = [f"## v{version} - {date.today().isoformat()}", ""]
|
||
|
|
body = []
|
||
|
|
for key, title in SECTION.items():
|
||
|
|
rows = [(s, d) for _, t, s, d, _ in ok if t == key]
|
||
|
|
if rows:
|
||
|
|
body.append(f"### {title}")
|
||
|
|
for scope, desc in rows:
|
||
|
|
body.append(f"- {scope + ': ' if scope else ''}{desc}")
|
||
|
|
brk = [(s, d) for _, _, s, d, b in ok if b]
|
||
|
|
if brk:
|
||
|
|
body.append("### Breaking changes")
|
||
|
|
body += [f"- {s + ': ' if s else ''}{d}" for s, d in brk]
|
||
|
|
room = CHANGELOG_MAX_LINES - len(lines) - 2
|
||
|
|
if len(body) > room:
|
||
|
|
hidden = len(body) - (room - 1)
|
||
|
|
body = body[: room - 1] + [f"- ... and {hidden} more (see git log)"]
|
||
|
|
lines += body
|
||
|
|
if bad:
|
||
|
|
lines += ["", f"Skipped {len(bad)} commits not in Conventional Commit form."]
|
||
|
|
return "\n".join(lines) + "\n"
|
||
|
|
|
||
|
|
|
||
|
|
def prepare(apply):
|
||
|
|
if git("status", "--porcelain"):
|
||
|
|
if apply:
|
||
|
|
sys.exit("refusing: working tree is not clean")
|
||
|
|
print("note: working tree is not clean (a real run would refuse)")
|
||
|
|
tag = last_tag()
|
||
|
|
ok, bad = classify(commits_since(tag))
|
||
|
|
print(f"last tag: {tag or '(none)'}; conformant commits: {len(ok)}; malformed: {len(bad)}")
|
||
|
|
for h, s, why in bad:
|
||
|
|
print(f" SKIPPED {h} {s[:70]!r}: {why}")
|
||
|
|
kind = choose_bump(ok)
|
||
|
|
if not kind:
|
||
|
|
print("no release: no feat, fix, or breaking commit")
|
||
|
|
return 0
|
||
|
|
new = bumped(current_version(tag), kind)
|
||
|
|
version = ".".join(map(str, new))
|
||
|
|
entry = changelog_entry(version, ok, bad)
|
||
|
|
print(f"bump: {kind} -> v{version}\n--- CHANGELOG entry ---\n{entry}")
|
||
|
|
if not apply:
|
||
|
|
print("dry run: nothing written (use --apply)")
|
||
|
|
return 0
|
||
|
|
(ROOT / "VERSION").write_text(version + "\n")
|
||
|
|
path = ROOT / "CHANGELOG.md"
|
||
|
|
old = path.read_text() if path.exists() else "# Changelog\n\n"
|
||
|
|
head, _, rest = old.partition("\n\n")
|
||
|
|
path.write_text(head + "\n\n" + entry + "\n" + rest)
|
||
|
|
git("add", "VERSION", "CHANGELOG.md")
|
||
|
|
git("commit", "-m", f"chore(workflow): release v{version}\n\nCo-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>")
|
||
|
|
print(f"committed release v{version}; deploy, verify, then run: tools/release.py tag --apply")
|
||
|
|
return 0
|
||
|
|
|
||
|
|
|
||
|
|
def tag(apply):
|
||
|
|
if git("status", "--porcelain"):
|
||
|
|
sys.exit("refusing: working tree is not clean")
|
||
|
|
version = (ROOT / "VERSION").read_text().strip()
|
||
|
|
name = f"v{version}"
|
||
|
|
if git("tag", "--list", name):
|
||
|
|
sys.exit(f"refusing: tag {name} already exists")
|
||
|
|
print(f"tag {name} at {git('rev-parse', '--short', 'HEAD')}")
|
||
|
|
if not apply:
|
||
|
|
print("dry run: no tag created (use --apply)")
|
||
|
|
return 0
|
||
|
|
git("tag", "-a", name, "-m", f"Release {name}")
|
||
|
|
print(f"created annotated tag {name}")
|
||
|
|
return 0
|
||
|
|
|
||
|
|
|
||
|
|
def main():
|
||
|
|
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||
|
|
ap.add_argument("stage", choices=["prepare", "tag"])
|
||
|
|
ap.add_argument("--apply", action="store_true", help="write (default is dry run)")
|
||
|
|
a = ap.parse_args()
|
||
|
|
return prepare(a.apply) if a.stage == "prepare" else tag(a.apply)
|
||
|
|
|
||
|
|
|
||
|
|
if __name__ == "__main__":
|
||
|
|
sys.exit(main())
|