diff --git a/scripts/generate-changelog-input.sh b/scripts/generate-changelog-input.sh index 08bd00bd4..5c57a30d7 100755 --- a/scripts/generate-changelog-input.sh +++ b/scripts/generate-changelog-input.sh @@ -512,6 +512,48 @@ else echo " commits without a PR reference in the subject will be referenced by commit hash" fi +# Run Claude with prompt $1 and print its response. A non-zero exit status +# means the call failed (e.g. an expired login or an unavailable model). +# The CLI prints its error message to stdout, so on failure the output is +# reported on stderr and must never be used as content. Call it as +# RESULT=$(run_claude "$PROMPT") || exit 1: an exit inside the command +# substitution would only leave the subshell. +run_claude() { + local out rc=0 + out=$(claude --model "$CLAUDE_MODEL" --effort "$CLAUDE_EFFORT" -p "$1") || rc=$? + if [ "$rc" -ne 0 ]; then + echo "Error: claude exited with status $rc:" >&2 + echo "$out" | sed 's/^/ /' >&2 + return 1 + fi + printf '%s\n' "$out" +} + +# Restore CHANGELOG.md to its state before the run if the script fails +# before committing: an aborted run must not leave entries for some of +# the tags behind, which a later --auto run would take as done +CHANGELOG_BACKUP=$(mktemp) +CHANGELOG_EXISTED=false +if [ -f CHANGELOG.md ]; then + cp CHANGELOG.md "$CHANGELOG_BACKUP" + CHANGELOG_EXISTED=true +fi +RESTORE_CHANGELOG=true + +on_exit() { + local rc=$? + if [ "$rc" -ne 0 ] && [ "$RESTORE_CHANGELOG" = true ]; then + if [ "$CHANGELOG_EXISTED" = true ]; then + cp "$CHANGELOG_BACKUP" CHANGELOG.md + else + rm -f CHANGELOG.md + fi + echo "Run failed: CHANGELOG.md restored to its state before the run" >&2 + fi + rm -f "$CHANGELOG_BACKUP" +} +trap on_exit EXIT + _USER_OUTPUT_FILE="$OUTPUT_FILE" # Process each tag @@ -989,7 +1031,7 @@ if [ "$RUN_CLAUDE" = true ]; then echo "Processing batch $((batch+1)) of $NUM_BATCHES..." # Run Claude and append output to main file - RESULT=$(claude --model "$CLAUDE_MODEL" --effort "$CLAUDE_EFFORT" -p "$(cat "$BATCH_FILE")" 2>&1) || true + RESULT=$(run_claude "$(cat "$BATCH_FILE")") || exit 1 BATCH_RESULTS+=("$RESULT") echo "" >> "$OUTPUT_FILE" @@ -1033,14 +1075,18 @@ Rules: $(cat "$OUTPUT_FILE")" # Run final merge - FINAL_RESULT=$(claude --model "$CLAUDE_MODEL" --effort "$CLAUDE_EFFORT" -p "$MERGE_PROMPT" 2>&1) || true + FINAL_RESULT=$(run_claude "$MERGE_PROMPT") || exit 1 fi # NUM_BATCHES # Strip any preamble before the first ## [v line CLEAN_RESULT=$(echo "$FINAL_RESULT" | sed -n '/^## \[v/,$p') if [ -z "$CLEAN_RESULT" ]; then - CLEAN_RESULT="$FINAL_RESULT" + # Without the version header the entry would be inserted into + # CHANGELOG.md as part of the previous version + echo "Error: Generated entry has no version header (## [$LATEST_TAG] - $TAG_DATE):" >&2 + echo "$FINAL_RESULT" | sed 's/^/ /' >&2 + exit 1 fi # Ensure that every reference resolved for this release (subject, GitHub @@ -1131,13 +1177,26 @@ Rules: Changelog entry: $CLEAN_RESULT" - FIX_RESULT=$(claude --model "$CLAUDE_MODEL" --effort "$CLAUDE_EFFORT" -p "$FIX_PROMPT" 2>&1) || true + FIX_RESULT=$(run_claude "$FIX_PROMPT") || exit 1 FIX_CLEAN=$(echo "$FIX_RESULT" | sed -n '/^## \[v/,$p') if [ -n "$FIX_CLEAN" ]; then CLEAN_RESULT="$FIX_CLEAN" fi MISSING_REFS=$(find_missing_refs) + + # The direct repair below patches a few references the model + # dropped. If most of them are missing, the model output is not a + # usable entry, and the repair would turn the raw commit subjects + # into the changelog. + NUM_EXPECTED=$(echo "$EXPECTED_REFS" | grep -c . || true) + NUM_MISSING=$(echo "$MISSING_REFS" | grep -c . || true) + if [ $((NUM_MISSING * 2)) -gt "$NUM_EXPECTED" ]; then + echo "Error: $NUM_MISSING of $NUM_EXPECTED references are missing from the generated entry, not repairing:" >&2 + echo "$CLEAN_RESULT" | sed 's/^/ /' >&2 + exit 1 + fi + if [ -n "$MISSING_REFS" ]; then # Last resort: repair or append the missing references # deterministically so that no change ends up in the changelog @@ -1261,7 +1320,7 @@ Rules: Diff: $CHANGELOG_DIFF" - COMMIT_BODY=$(claude --model "$CLAUDE_MODEL" --effort "$CLAUDE_EFFORT" -p "$COMMIT_PROMPT" 2>&1) || true + COMMIT_BODY=$(run_claude "$COMMIT_PROMPT") || exit 1 # Drop code fences, any trailers and a subject the model added anyway COMMIT_BODY=$(echo "$COMMIT_BODY" \ @@ -1279,6 +1338,11 @@ $CHANGELOG_DIFF" $COMMIT_BODY" + # The restore on failure ends here: CHANGELOG.md is committed next, and + # restoring it afterwards would leave the working tree out of step with + # the commit + RESTORE_CHANGELOG=false + # Branch off if we are on the default branch CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD) BRANCH="$CURRENT_BRANCH" diff --git a/tests/test_generate_changelog_input.py b/tests/test_generate_changelog_input.py new file mode 100644 index 000000000..d014a160b --- /dev/null +++ b/tests/test_generate_changelog_input.py @@ -0,0 +1,149 @@ +import os +import pathlib +import subprocess + +import pytest + +SCRIPT = ( + pathlib.Path(__file__).resolve().parents[1] + / "scripts" + / "generate-changelog-input.sh" +) +REPO = "osism/demo" + +CHANGELOG = """# Changelog + +All notable changes to this project will be documented in this file. + +## [v0.20261001.0] - 2026-10-01 + +### Added + +- Initial release (osism/demo#0) +""" + +# Stub of the claude CLI. Like the real one, it prints its error message to +# stdout and exits 1 when a call fails. It fails on prompts that contain +# $FAKE_CLAUDE_FAIL_ON, answers without any references if +# $FAKE_CLAUDE_NO_REFS is set, and otherwise writes one entry per #N +# reference of a commit subject in the prompt. +CLAUDE_STUB = """#!/bin/bash +while [ $# -gt 0 ]; do + case "$1" in + -p) prompt="$2"; shift 2 ;; + *) shift ;; + esac +done +if [ -n "$FAKE_CLAUDE_FAIL_ON" ] && [[ "$prompt" == *"$FAKE_CLAUDE_FAIL_ON"* ]]; then + echo "Failed to authenticate. API Error: 401 OAuth access token is invalid." + exit 1 +fi +echo "### Changed" +echo "" +if [ -n "$FAKE_CLAUDE_NO_REFS" ]; then + echo "- Something changed" + exit 0 +fi +for num in $(echo "$prompt" | grep -oE '\\(#[0-9]+\\)' | tr -d '(#)' | sort -un); do + [ "$num" = 0 ] || echo "- Change $num (osism/demo#$num)" +done +""" + +# Stub of the GitHub CLI: not authenticated, so the script never calls the +# GitHub API +GH_STUB = """#!/bin/bash +exit 1 +""" + + +@pytest.fixture +def repo(release_repo, tmp_path): + release_repo.set_origin(f"https://github.com/{REPO}.git") + release_repo.commit({"CHANGELOG.md": CHANGELOG}, "Initial release (#0)") + release_repo.tag("v0.20261001.0", push=False) + release_repo.commit({"a": "a"}, "Add a (#1)") + release_repo.commit({"b": "b"}, "Fix b (#2)") + release_repo.tag("v0.20261002.0", push=False) + release_repo.commit({"c": "c"}, "Add c (#3)") + release_repo.tag("v0.20261003.0", push=False) + + bin_dir = tmp_path / "bin" + bin_dir.mkdir() + for name, content in (("claude", CLAUDE_STUB), ("gh", GH_STUB)): + (bin_dir / name).write_text(content) + (bin_dir / name).chmod(0o755) + release_repo.env = { + **release_repo.env, + "PATH": f"{bin_dir}{os.pathsep}{os.environ['PATH']}", + "INTERNAL_EMAIL_DOMAINS": "example.com", + } + return release_repo + + +def generate(repo, *options, **env): + return subprocess.run( + ["bash", str(SCRIPT), "--auto", "--tags-only", *options], + cwd=repo.checkout, + env={**repo.env, **env}, + stdin=subprocess.DEVNULL, + capture_output=True, + text=True, + ) + + +def changelog(repo): + return (repo.checkout / "CHANGELOG.md").read_text() + + +def test_writes_entries_with_references(repo): + result = generate(repo) + assert result.returncode == 0, result.stdout + result.stderr + text = changelog(repo) + assert "## [v0.20261003.0]" in text + assert "## [v0.20261002.0]" in text + new_entries = text[: text.index("## [v0.20261001.0]")] + assert sorted( + line for line in new_entries.splitlines() if line.startswith("- ") + ) == [f"- Change {num} ({REPO}#{num})" for num in (1, 2, 3)] + + +def test_claude_failure_stops_the_run(repo): + result = generate(repo, FAKE_CLAUDE_FAIL_ON="v0.20261002.0") + assert result.returncode == 1 + assert "claude exited with status 1" in result.stderr + assert "Failed to authenticate" in result.stderr + assert changelog(repo) == CHANGELOG + + +def test_failure_on_a_later_tag_restores_changelog(repo): + # The first tag succeeds and is inserted into CHANGELOG.md, then the + # login fails on the second one + result = generate(repo, FAKE_CLAUDE_FAIL_ON="v0.20261003.0") + assert result.returncode == 1 + assert "Inserted into CHANGELOG.md" in result.stdout + assert "CHANGELOG.md restored" in result.stderr + assert changelog(repo) == CHANGELOG + + +def test_claude_failure_on_commit_message_commits_nothing(repo): + head = repo.git("rev-parse", "HEAD") + result = generate(repo, "--commit", FAKE_CLAUDE_FAIL_ON="Write the body") + assert result.returncode == 1 + assert repo.git("rev-parse", "HEAD") == head + assert repo.git("branch", "--show-current") == "main" + assert changelog(repo) == CHANGELOG + + +def test_entry_without_references_is_not_repaired(repo): + # Without the check, the direct repair would build the entry from the + # raw commit subjects + result = generate(repo, FAKE_CLAUDE_NO_REFS="1") + assert result.returncode == 1 + assert "references are missing from the generated entry" in result.stderr + assert changelog(repo) == CHANGELOG + + +def test_no_claude_run_needs_no_claude(repo): + result = generate(repo, "--no-run", FAKE_CLAUDE_FAIL_ON="v0") + assert result.returncode == 0, result.stdout + result.stderr + assert changelog(repo) == CHANGELOG