Files
claude-config/bin/deploy_release/patch.py
T

199 lines
11 KiB
Python

"""`deploy-release --cut-patch <commits>`: cut the newest tag's next patch release holding only the commits named, test it with ci.sh, tag it, merge the tag back into main through a pull request, then move ~/.claude to it.
Each step first checks whether an earlier run did it, so a rerun continues where the last run stopped.
"""
import pathlib
import re
import shutil
import subprocess
import tempfile
import typing
from git_cli.git_repo import default_ref, git
from deploy_release.cut import delete_release_branch, drop_unpushed_cut_tags, land, ready_release, said, same_origin
from deploy_release.deploy import deploy
from failure import Failure
from plan.release import newest_tag, Release, tagged, UNRELEASED_TITLE, version
from text_files.markdown_text import section
# The files a patch leaves as the tag holds them: the plan, the changelog the cut writes itself, and the records every chunk appends to, which seldom apply on an older tag.
LEFT_AS_TAGGED = ("todo.md", "CHANGELOG.md", "docs/reading-cost.md", "docs/comprehension-history.md")
MERGE_BACK_BODY = "Merge the patch release's tag into main, keeping main's files, and list its changelog entries under its version."
def cut_patch(clone: str, checkout: str, commits: str, sleep: typing.Callable[[float], None]) -> str | Failure:
"""What the patch cut did, as the tool prints it; a Failure with git's, the forge's, ci.sh's or the tool's reason where a step stopped. commits is one revision as git log reads it, or one commit."""
if isinstance(same := same_origin(clone, checkout), Failure):
return same
if isinstance(fetched := git("fetch", "--quiet", "--tags", "origin", cwd=clone), Failure):
return fetched
if isinstance(dropped := drop_unpushed_cut_tags(clone), Failure):
return dropped
ref = default_ref(cwd=clone)
if isinstance(ref, Failure):
return ref
base = newest_tag(clone, merged_into=ref)
if isinstance(base, Failure):
return base
cut_release = tagged(base)
if base is None or cut_release is None:
return Failure(f"{ref} holds no v* tag to cut a patch of")
named = version((cut_release[0], cut_release[1], cut_release[2] + 1))
# A patch holds only fixes, and the release review reads the whole project, so a patch is cut without one.
release = ready_release(clone, ref, review=False)
if isinstance(release, Failure):
return release
if version(release) != named:
return Failure(f"the next release in todo.md is {version(release)}, not {named}, the patch of {base}: file the fix under {named}")
picked = patch_commits(clone, ref, base, commits)
if isinstance(picked, Failure):
return picked
entries = changelog_entries(clone, ref, picked)
if isinstance(entries, Failure):
return entries
title, tag = f"Cut release {named}", f"v{named}"
pushed = git("ls-remote", "--tags", "--refs", "origin", f"refs/tags/{tag}", cwd=clone)
if isinstance(pushed, Failure):
return pushed
if not pushed.strip():
if isinstance(made := tag_patch(clone, base, picked, entries, named, title), Failure):
return made
if isinstance(git("merge-base", "--is-ancestor", tag, ref, cwd=clone), Failure):
branch = f"release-{named}"
build = lambda replacing: push_merge_back(clone, ref, branch, tag, named, entries, replacing)
if isinstance(landed := land(clone, ref, branch, f"Merge release {named} into main", MERGE_BACK_BODY, build, sleep), Failure):
return landed
delete_release_branch(clone, branch)
moved = deploy(checkout)
if isinstance(moved, Failure):
return Failure(f"cut and pushed {tag}, but moving {checkout} stopped: {moved.reason}. Fix that, then run a bare deploy-release.")
return f"{moved}\n\nDone: {tag} is cut and pushed, and {checkout} is on it."
def patch_commits(clone: str, ref: str, base: str, commits: str) -> list[str] | Failure:
"""The commits commits names, oldest first, merge commits left out; a Failure where one is missing from ref or the tag base already holds it."""
listed = git("rev-list", "--reverse", "--no-merges", commits if ".." in commits else f"{commits}^!", "--", cwd=clone)
if isinstance(listed, Failure):
return listed
picked = listed.split()
if not picked:
return Failure(f"{commits} names no commit but merges")
for commit in picked:
if isinstance(git("merge-base", "--is-ancestor", commit, ref, cwd=clone), Failure):
return Failure(f"{commit[:12]} isn't on {ref}: merge it there first")
if not isinstance(git("merge-base", "--is-ancestor", commit, base, cwd=clone), Failure):
return Failure(f"{commit[:12]} is in {base} already")
return picked
def changelog_entries(clone: str, ref: str, commits: list[str]) -> list[str] | Failure:
"""The entries under ref's ## Unreleased in CHANGELOG.md that commits added, in the order ref lists them; a Failure where they added none."""
added: set[str] = set()
for commit in commits:
diff = git("diff", f"{commit}^", commit, "--", "CHANGELOG.md", cwd=clone)
if isinstance(diff, Failure):
return diff
added |= {line[1:] for line in diff.splitlines() if line.startswith("+- ")}
changelog = git("show", f"{ref}:CHANGELOG.md", cwd=clone)
if isinstance(changelog, Failure):
return changelog
entries = [line for line in section(changelog, UNRELEASED_TITLE) or [] if line in added]
return entries or Failure(f"the commits add no entry under ## Unreleased in CHANGELOG.md on {ref}: name the commit that finished the fix's item too")
def tag_patch(clone: str, base: str, commits: list[str], entries: list[str], named: str, title: str) -> Failure | None:
"""In a worktree at the tag base, apply commits but for LEFT_AS_TAGGED, head CHANGELOG.md with entries under ## named, commit that titled title, test it with ci.sh, then tag it v<named> and push the tag."""
tag = f"v{named}"
worktree = pathlib.Path(tempfile.mkdtemp(prefix="deploy-release-")) / "patch"
try:
if isinstance(added := git("worktree", "add", "--quiet", "--detach", str(worktree), base, cwd=clone), Failure):
return added
for commit in commits:
if isinstance(applied := apply_commit(clone, worktree, commit, base), Failure):
return applied
changelog = worktree / "CHANGELOG.md"
changelog.write_text(headed(changelog.read_text() if changelog.exists() else "# Changelog\n", entries, named))
if isinstance(committed := git("commit", "--quiet", "--all", "--message", title, cwd=str(worktree)), Failure):
return committed
said(f"applied {len(commits)} commit(s) on {base}; testing them with ci.sh")
if isinstance(tested := run_ci(worktree), Failure):
return tested
said("ci.sh passed")
if isinstance(made := git("tag", "--annotate", "--message", title, tag, "HEAD", cwd=str(worktree)), Failure):
return made
if isinstance(pushed := git("push", "--quiet", "origin", f"refs/tags/{tag}", cwd=clone), Failure):
# Until a rerun, chunk-preflight would read a tag only the clone holds as cut.
git("tag", "--delete", tag, cwd=clone)
return pushed
said(f"pushed the tag {tag}")
return None
finally:
git("worktree", "remove", "--force", str(worktree), cwd=clone)
shutil.rmtree(worktree.parent, ignore_errors=True)
def headed(changelog: str, entries: list[str], named: str) -> str:
"""changelog with a ## named section holding entries before its first ## section, or at its end where it has none."""
added = f"## {named}\n\n" + "\n".join(entries) + "\n"
first = re.search(r"^## ", changelog, flags=re.M)
if first is None:
return changelog.rstrip("\n") + "\n\n" + added
return changelog[:first.start()] + added + "\n" + changelog[first.start():]
def apply_commit(clone: str, worktree: pathlib.Path, commit: str, base: str) -> Failure | None:
"""Apply commit's change, but for LEFT_AS_TAGGED, to worktree's index and files, merging three ways where the tag base's files differ from commit's parent."""
diff = git("diff", "--binary", f"{commit}^", commit, "--", ".", *(f":(exclude){path}" for path in LEFT_AS_TAGGED), cwd=clone)
if isinstance(diff, Failure):
return diff
if not diff:
return None
patch = worktree.parent / "commit.patch"
patch.write_text(diff)
if isinstance(applied := git("apply", "--3way", "--index", str(patch), cwd=str(worktree)), Failure):
subject = git("log", "-1", "--format=%s", commit, cwd=clone)
return Failure(f"{commit[:12]} ({'' if isinstance(subject, Failure) else subject.strip()}) doesn't apply on {base}: {applied.reason}. Cut this patch by hand.")
return None
def run_ci(worktree: pathlib.Path) -> Failure | None:
"""None where the patch's ci.sh passes on its committed head; a Failure with the end of its output where it fails."""
if not (worktree / "ci.sh").exists():
return Failure("the patch holds no ci.sh to test it with")
ran = subprocess.run(["sh", "ci.sh"], capture_output=True, cwd=worktree, text=True, errors="replace")
if ran.returncode == 0:
return None
tail = "\n".join((ran.stdout + ran.stderr).strip().splitlines()[-30:])
return Failure(f"ci.sh failed on the patch, so nothing is tagged:\n{tail}")
def push_merge_back(clone: str, ref: str, branch: str, tag: str, named: str, entries: list[str], replacing: str | None) -> Failure | None:
"""On ref, merge tag keeping ref's files, with entries moved from ## Unreleased to a ## named section after it, in a worktree of its own; push that as branch: a new one, or in place of replacing, the commit origin's branch points at."""
worktree = pathlib.Path(tempfile.mkdtemp(prefix="deploy-release-")) / "merge-back"
try:
if isinstance(added := git("worktree", "add", "--quiet", "--detach", str(worktree), ref, cwd=clone), Failure):
return added
if isinstance(merged := git("merge", "--quiet", "--no-ff", "--no-commit", "--strategy", "ours", tag, cwd=str(worktree)), Failure):
return merged
changelog = worktree / "CHANGELOG.md"
changelog.write_text(moved_entries(changelog.read_text(), entries, named))
if isinstance(committed := git("commit", "--quiet", "--all", "--message", f"Merge release {named} into main", cwd=str(worktree)), Failure):
return committed
lease = [f"--force-with-lease=refs/heads/{branch}:{replacing}"] if replacing else []
pushed = git("push", "--quiet", *lease, "origin", f"HEAD:refs/heads/{branch}", cwd=str(worktree))
return pushed if isinstance(pushed, Failure) else None
finally:
git("worktree", "remove", "--force", str(worktree), cwd=clone)
shutil.rmtree(worktree.parent, ignore_errors=True)
def moved_entries(changelog: str, entries: list[str], named: str) -> str:
"""changelog with entries taken out of its ## Unreleased section and put in a ## named section right after it."""
lines = changelog.split("\n")
start = next(index for index, line in enumerate(lines) if re.fullmatch(f"## {UNRELEASED_TITLE}", line))
end = next((index for index in range(start + 1, len(lines)) if lines[index].startswith("## ")), len(lines))
kept = [line for line in lines[start + 1:end] if line not in entries]
while kept and not kept[-1].strip():
kept.pop()
return "\n".join([*lines[:start + 1], *kept, "", f"## {named}", "", *entries, "", *lines[end:]])