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

236 lines
13 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.
A rerun takes the tag an earlier run pushed, once it checks the tag lists the same changelog entries, and the merge-back's open pull request.
"""
import dataclasses
import pathlib
import re
import subprocess
import typing
from git_cli.git_repo import default_ref, git
from deploy_release.cut import delete_release_branch, drop_unpushed_cut_tags, land, push_branch, ready_release, said, same_origin, scratch_worktree
from deploy_release.deploy import deploy
from failure import Failure
from forge.commands import forge_of
from plan.release import newest_tag, tagged, UNRELEASED_TITLE, version
from text_files.markdown_text import section
# The files a patch leaves as the tag holds them: the changelog, whose section the cut writes itself; the plan; and the records each chunk appends to, which seldom apply on an older tag.
LEFT_AS_TAGGED = ("CHANGELOG.md", "docs/comprehension-history.md", "docs/reading-cost.md", "todo.md")
MERGE_BACK_BODY = "Merge the patch release's tag into main, keeping main's files, and list its changelog entries under its version."
@dataclasses.dataclass(frozen=True)
class Patch:
"""A patch release ready to cut."""
# origin's default branch, as default_ref names it.
ref: str
# The newest tag ref holds, which the patch goes on top of.
base: str
# The patch's version, the base's next patch.
named: str
# The commits the patch ships, oldest first.
commits: list[str]
# The CHANGELOG.md entries the commits added under ref's ## Unreleased, in ref's order.
entries: list[str]
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 a range as git log reads it, or one commit."""
patch = planned(clone, checkout, commits)
if isinstance(patch, Failure):
return patch
for commit in patch.commits:
subject = git("log", "-1", "--format=%h %s", commit, cwd=clone)
said(f"ships {'' if isinstance(subject, Failure) else subject.strip()}")
tag, branch = f"v{patch.named}", f"release-{patch.named}"
pushed = git("ls-remote", "--tags", "--refs", "origin", f"refs/tags/{tag}", cwd=clone)
if isinstance(pushed, Failure):
return pushed
made = tagged_entries(clone, patch) if pushed.strip() else tag_patch(clone, patch)
if isinstance(made, Failure):
return made
build = lambda replacing: push_merge_back(clone, patch, replacing)
if isinstance(landed := land(clone, patch.ref, branch, f"Merge release {patch.named} into main", MERGE_BACK_BODY, build, sleep), Failure):
return landed
if isinstance(fetched := git("fetch", "--quiet", "origin", cwd=clone), Failure):
return fetched
if isinstance(git("merge-base", "--is-ancestor", tag, patch.ref, cwd=clone), Failure):
return Failure(f"the merge-back merged, but {patch.ref} doesn't hold {tag}, so the next cut can't read it as cut")
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 planned(clone: str, checkout: str, commits: str) -> Patch | Failure:
"""The patch commits names, once the clone, the plan and the commits allow it; a Failure saying why not, before anything changes on origin."""
if isinstance(same := same_origin(clone, checkout), Failure):
return same
url = git("config", "--get", "remote.origin.url", cwd=clone)
if isinstance(url, Failure):
return url
if forge_of(url) == "gh":
return Failure("--cut-patch merges the tag back fast-forward, which GitHub can't, since its rebase merge drops the merge commit: cut the patch by hand there")
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 = tagged(base)
if base is None or cut is None:
return Failure(f"{ref}'s newest tag, {base}, names no release x.y.z to cut a patch of" if base else f"{ref} holds no v* tag to cut a patch of")
named = version((cut[0], cut[1], cut[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)
return entries if isinstance(entries, Failure) else Patch(ref, base, named, picked, entries)
def patch_commits(clone: str, ref: str, base: str, commits: str) -> list[str] | Failure:
"""The commits commits names, oldest first: merge commits, and the commits a merge brought into a range, are left out. A Failure where one is missing from ref or the tag base already holds it."""
listed = git("rev-list", "--reverse", "--no-merges", "--first-parent", 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 that isn't a merge: write a range as <older>..<newer>")
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 tagged_entries(clone: str, patch: Patch) -> Failure | None:
"""A Failure unless the tag an earlier run pushed lists patch's entries under its version, so a rerun with other commits doesn't merge back entries the tag doesn't ship."""
changelog = git("show", f"v{patch.named}:CHANGELOG.md", cwd=clone)
if isinstance(changelog, Failure):
return changelog
listed = [line for line in section(changelog, re.escape(patch.named)) or [] if line.strip()]
if listed != patch.entries:
return Failure(f"origin's v{patch.named} lists other changelog entries under ## {patch.named} than the commits named added under ## Unreleased. The tag lists:\n" + "\n".join(listed) + "\nThe commits added:\n" + "\n".join(patch.entries))
return None
def tag_patch(clone: str, patch: Patch) -> Failure | None:
"""In a worktree at the base tag, apply patch's commits but for LEFT_AS_TAGGED, head CHANGELOG.md with its section, commit that titled `Cut release <version>`, test it with ci.sh, then tag it and push the tag."""
title, tag = f"Cut release {patch.named}", f"v{patch.named}"
with scratch_worktree(clone, patch.base) as worktree:
if isinstance(worktree, Failure):
return worktree
for commit in patch.commits:
if isinstance(applied := apply_commit(clone, worktree, commit, patch), Failure):
return applied
changelog = worktree / "CHANGELOG.md"
changelog.write_text(headed(changelog.read_text() if changelog.exists() else "# Changelog\n", patch.entries, patch.named))
if isinstance(committed := git("commit", "--quiet", "--all", "--message", title, cwd=str(worktree)), Failure):
return committed
said(f"applied the commits on {patch.base}; testing them with ci.sh")
if isinstance(tested := run_ci(worktree, patch.ref), 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
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" + added
return changelog[:first.start()] + added + "\n" + changelog[first.start():]
def apply_commit(clone: str, worktree: pathlib.Path, commit: str, patch: Patch) -> Failure | None:
"""Apply commit's change, but for LEFT_AS_TAGGED, to worktree's index and files, merging three ways where the base tag'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_file = worktree.parent / "commit.patch"
patch_file.write_text(diff)
if isinstance(applied := git("apply", "--3way", "--index", str(patch_file), 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 {patch.base}: {applied.reason}. "
f"Cut the patch by hand: on {patch.base}, apply the fix and add a ## {patch.named} section to CHANGELOG.md, commit that titled `Cut release {patch.named}`, "
f"tag it v{patch.named}, annotated with that title, and push the tag. A rerun with the same commits then merges it back and deploys it, "
f"where the section holds exactly these lines:\n" + "\n".join(patch.entries)
)
return None
def run_ci(worktree: pathlib.Path, ref: str) -> 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. Fix it on {ref}, then rerun naming the fix's commits too. The end of its output:\n{tail}")
def push_merge_back(clone: str, patch: Patch, replacing: str | None) -> Failure | None:
"""On origin's main, merge the patch's tag keeping main's files, move its entries from ## Unreleased to a ## <version> section below ## Unreleased, and push that as the branch release-<version>, replacing the commit origin's branch points at, where there is one."""
with scratch_worktree(clone, patch.ref) as worktree:
if isinstance(worktree, Failure):
return worktree
if isinstance(merged := git("merge", "--quiet", "--no-ff", "--no-commit", "--strategy", "ours", f"v{patch.named}", cwd=str(worktree)), Failure):
return merged
changelog = worktree / "CHANGELOG.md"
changelog.write_text(moved_entries(changelog.read_text(), patch.entries, patch.named))
if isinstance(committed := git("commit", "--quiet", "--all", "--message", f"Merge release {patch.named} into main", cwd=str(worktree)), Failure):
return committed
return push_branch(worktree, f"release-{patch.named}", replacing)
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 below that section."""
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:]])