mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-22 13:29:19 +08:00
## Description Fixes two silent-failure bugs in scripts/changelog-gen.py that could let the release pipeline produce an empty changelog with exit code 0. 1. run_git_log() never checked subprocess.returncode, so a failed git log (e.g. a non-existent --since ref) silently returned empty output and wrote a blank .changelog.md, allowing the pipeline to continue as if nothing went wrong. 2. iter_commit_entries() had a dead fallback branch using COMMIT_ENTRY_PATTERN — a regex that expected | as a field separator, but the actual git log format uses \x1f/\x1e. The fallback could never match real output and would silently return zero commits if the primary parse path was skipped. Closes # ## Type of Change - [x] Bug fix (non-breaking change that fixes an issue) - [ ] New feature (non-breaking change that adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to change) - [ ] Documentation update - [ ] Performance improvement - [ ] Code refactoring (no functional changes) ## Changes Made - scripts/changelog-gen.py: run_git_log() now raises RuntimeError on non-zero git exit, with the stderr included in the message. - scripts/changelog-gen.py: removed the unused COMMIT_ENTRY_PATTERN constant; replaced the dead fallback in iter_commit_entries() with an explicit ValueError so format mismatches surface immediately instead of returning empty results. ## Testing - [x] Unit tests pass (pytest) - [ ] Linting passes (ruff check .) - [ ] Type checking passes (mypy headroom) - [ ] New tests added for new functionality - [ ] Manual testing performed ### Test Output ``` $ uv run python -m pytest scripts/tests/test_changelog_gen.py -q ============================= test session starts ============================== platform linux -- Python 3.14.0, pytest-9.1.1, pluggy-1.6.0 rootdir: /home/sepurisaikrishna/Documents/calude-here/headroom configfile: pyproject.toml collected 28 items scripts/tests/test_changelog_gen.py ............................ [100%] =============================== warnings summary =============================== PytestConfigWarning: Unknown config option: asyncio_mode -- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html ======================== 28 passed, 1 warning in 0.03s ========================= $ git diff --check origin/main..HEAD # no output; command exited 0 ``` ## Real Behavior Proof - Environment: Linux, Python 3.14.0, uv-managed .venv, branch based on current origin/main. - Exact command / steps: invoke python scripts/changelog-gen.py --version 0.1.0 --since v99.99.99 (non-existent tag); before the fix the script exits 0 with an empty .changelog.md; after the fix it raises RuntimeError: git log failed and exits non-zero. - Observed result: all 28 test_changelog_gen.py tests pass; script now fails loudly on bad git input. - Not tested: full repository pytest, ruff, and mypy; live CI run against a real release tag. ## Review Readiness - [x] I have performed a self-review - [x] This PR is ready for human review ## Checklist - [x] My code follows the project's style guidelines - [x] I have performed a self-review of my code - [ ] I have commented my code, particularly in hard-to-understand areas - [ ] I have made corresponding changes to the documentation - [x] My changes generate no new warnings - [ ] I have added tests that prove my fix is effective or that my feature works - [x] New and existing unit tests pass locally with my changes - [ ] I have updated the CHANGELOG.md if applicable ## Screenshots (if applicable) N/A. ## Additional Notes - Both bugs share the same failure mode (silent empty output instead of a clear error) and are in the same file, so they are fixed together in one PR. - The COMMIT_ENTRY_PATTERN constant is removed as it is now unreferenced. - No production behaviour changes — these scripts are only invoked during the release pipeline. --------- Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
201 lines
6.2 KiB
Python
201 lines
6.2 KiB
Python
#!/usr/bin/env python3
|
|
"""Generate changelog from conventional commits."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import re
|
|
import subprocess
|
|
from datetime import date
|
|
from pathlib import Path
|
|
from typing import NamedTuple
|
|
|
|
ROOT = Path(__file__).parent.parent
|
|
|
|
COMMIT_PATTERN = re.compile(
|
|
r"^(feat|fix|ci|chore|perf|refactor|docs|style|test)(\(.+\))?(!)?:\s*(.+)$"
|
|
)
|
|
BREAKING_CHANGE_PATTERN = re.compile(r"^BREAKING CHANGE:\s*(.+)$", re.MULTILINE)
|
|
FIELD_SEP = "\x1f"
|
|
RECORD_SEP = "\x1e"
|
|
GIT_LOG_FORMAT = "%s%x1f%b%x1f%h%x1e"
|
|
|
|
TYPE_LABELS: dict[str, str] = {
|
|
"feat": "Features",
|
|
"fix": "Bug Fixes",
|
|
"ci": "CI/CD",
|
|
"chore": "Chores",
|
|
"perf": "Performance",
|
|
"refactor": "Refactors",
|
|
"docs": "Documentation",
|
|
"style": "Styles",
|
|
"test": "Tests",
|
|
"other": "Other Changes",
|
|
}
|
|
|
|
|
|
class ParsedCommit(NamedTuple):
|
|
type: str
|
|
scope: str | None
|
|
breaking: bool
|
|
message: str
|
|
hash: str
|
|
|
|
|
|
def iter_commit_entries(log_output: str) -> list[tuple[str, str, str]]:
|
|
"""Split raw git log output into (subject, body, hash) tuples."""
|
|
|
|
if not log_output.strip():
|
|
return []
|
|
|
|
if RECORD_SEP not in log_output or FIELD_SEP not in log_output:
|
|
raise ValueError(
|
|
"git log output does not contain expected field/record separators "
|
|
"(\\x1f / \\x1e). Check GIT_LOG_FORMAT."
|
|
)
|
|
|
|
entries: list[tuple[str, str, str]] = []
|
|
for raw_entry in log_output.split(RECORD_SEP):
|
|
if not raw_entry:
|
|
continue
|
|
if FIELD_SEP not in raw_entry:
|
|
continue
|
|
subject, body_and_hash = raw_entry.split(FIELD_SEP, 1)
|
|
if FIELD_SEP not in body_and_hash:
|
|
continue
|
|
body, commit_hash = body_and_hash.rsplit(FIELD_SEP, 1)
|
|
entries.append((subject.strip(), body.strip(), commit_hash.strip()))
|
|
return entries
|
|
|
|
|
|
def get_merge_summary(subject: str, body: str) -> str:
|
|
"""Return the first meaningful summary line for a merge commit."""
|
|
|
|
if not subject.startswith("Merge "):
|
|
return ""
|
|
|
|
for line in body.splitlines():
|
|
stripped = line.strip()
|
|
if stripped:
|
|
return stripped
|
|
return ""
|
|
|
|
|
|
def parse_commits(log_output: str) -> list[ParsedCommit]:
|
|
"""Parse git log output into structured commits."""
|
|
|
|
commits: list[ParsedCommit] = []
|
|
|
|
for subject, body, commit_hash in iter_commit_entries(log_output):
|
|
is_breaking = bool(BREAKING_CHANGE_PATTERN.search(body))
|
|
merge_summary = get_merge_summary(subject, body)
|
|
candidates = [subject]
|
|
if merge_summary:
|
|
candidates.insert(0, merge_summary)
|
|
|
|
for candidate in candidates:
|
|
commit_match = COMMIT_PATTERN.match(candidate)
|
|
if not commit_match:
|
|
continue
|
|
|
|
scope = commit_match.group(2)
|
|
if scope:
|
|
scope = scope[1:-1]
|
|
commits.append(
|
|
ParsedCommit(
|
|
type=commit_match.group(1),
|
|
scope=scope,
|
|
breaking=is_breaking or bool(commit_match.group(3)),
|
|
message=commit_match.group(4),
|
|
hash=commit_hash,
|
|
)
|
|
)
|
|
break
|
|
else:
|
|
fallback_message = merge_summary or subject
|
|
if not fallback_message or fallback_message.startswith("Merge "):
|
|
continue
|
|
commits.append(
|
|
ParsedCommit(
|
|
type="other",
|
|
scope=None,
|
|
breaking=is_breaking,
|
|
message=fallback_message,
|
|
hash=commit_hash,
|
|
)
|
|
)
|
|
|
|
return commits
|
|
|
|
|
|
def generate_changelog(version: str, commits: list[ParsedCommit]) -> str:
|
|
"""Generate markdown changelog from parsed commits."""
|
|
today = date.today().isoformat()
|
|
lines = [f"## [{version}] - {today}", ""]
|
|
|
|
# Collect breaking changes
|
|
breaking_commits = [c for c in commits if c.breaking]
|
|
if breaking_commits:
|
|
lines.append("### Breaking Changes")
|
|
for commit in breaking_commits:
|
|
if commit.scope:
|
|
lines.append(f"- **{commit.scope}**: {commit.message} ({commit.hash})")
|
|
else:
|
|
lines.append(f"- {commit.message} ({commit.hash})")
|
|
lines.append("")
|
|
|
|
# Group by type
|
|
by_type: dict[str, list[ParsedCommit]] = {}
|
|
for commit in commits:
|
|
by_type.setdefault(commit.type, []).append(commit)
|
|
|
|
for commit_type, label in TYPE_LABELS.items():
|
|
type_commits = by_type.get(commit_type, [])
|
|
if not type_commits:
|
|
continue
|
|
lines.append(f"### {label}")
|
|
for commit in type_commits:
|
|
if commit.scope:
|
|
lines.append(f"- **{commit.scope}**: {commit.message} ({commit.hash})")
|
|
else:
|
|
lines.append(f"- {commit.message} ({commit.hash})")
|
|
lines.append("")
|
|
|
|
return "\n".join(lines) + "\n"
|
|
|
|
|
|
def run_git_log(since: str | None, cwd: Path) -> str:
|
|
"""Run git log command and return output."""
|
|
cmd = ["git", "log", "--first-parent", f"--pretty=format:{GIT_LOG_FORMAT}"]
|
|
if since:
|
|
cmd.append(f"{since}..HEAD")
|
|
else:
|
|
cmd.append("HEAD")
|
|
result = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True)
|
|
if result.returncode != 0:
|
|
raise RuntimeError(f"git log failed (exit {result.returncode}): {result.stderr.strip()}")
|
|
return result.stdout
|
|
|
|
|
|
def main() -> None:
|
|
parser = argparse.ArgumentParser(description="Generate changelog from conventional commits")
|
|
parser.add_argument("--version", required=True, help="Version number (e.g., 0.6.0)")
|
|
parser.add_argument("--since", help="Starting tag (exclusive)")
|
|
parser.add_argument("--dry-run", action="store_true", help="Print to stdout instead of writing")
|
|
args = parser.parse_args()
|
|
|
|
log_output = run_git_log(args.since, ROOT)
|
|
commits = parse_commits(log_output)
|
|
changelog = generate_changelog(args.version, commits)
|
|
|
|
if args.dry_run:
|
|
print(changelog)
|
|
else:
|
|
output_path = ROOT / ".changelog.md"
|
|
output_path.write_text(changelog, encoding="utf-8")
|
|
print(f"Changelog written to {output_path}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|