"""`deploy-release --cut-patch `: 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 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, rewritten, 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 deploy_release.trace import Say 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] @dataclasses.dataclass(frozen=True) class CiRan: code: int # stdout and stderr, as ci.sh interleaved them. output: str class Ci(typing.Protocol): """Runs the ci.sh that worktree holds, as ci_script.ci_runner's does: a Failure where it could not start or was stopped.""" def __call__(self, worktree: pathlib.Path) -> CiRan | Failure: ... def cut_patch(clone: str, checkout: str, commits: str, sleep: typing.Callable[[float], None], say: Say, ci: Ci) -> 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. say takes each step as it finishes, and ci runs the patch's ci.sh.""" 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) say(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, say, ci) 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, say), 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, say) 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)) ready = ready_release(clone, ref) if isinstance(ready, Failure): return ready # A patch holds only fixes, and the release review reads the whole project, so a patch is cut whether or not ready.reviewed. if version(ready.release) != named: return Failure(f"the next release in todo.md is {version(ready.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 ..") 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, or where ref's CHANGELOG.md has no such section, which the merge-back moves the entries out of.""" 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 unreleased = section(changelog, UNRELEASED_TITLE) # The merge-back finds the heading with unreleased_start only after the tag is pushed, so check it here first. if unreleased is None or unreleased_start(changelog.split("\n")) is None: return Failure(f"CHANGELOG.md on {ref} has no ## Unreleased section, which the patch's entries come from: add it on {ref}") entries = [line for line in unreleased 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, say: Say, ci: Ci) -> 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 `, 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 head = lambda changelog: headed("# Changelog\n" if changelog is None else changelog, patch.entries, patch.named) if isinstance(written := rewritten(worktree / "CHANGELOG.md", f"head CHANGELOG.md with ## {patch.named} in the patch's worktree", "Nothing is tagged.", head), Failure): return written if isinstance(committed := git("commit", "--quiet", "--all", "--message", title, cwd=str(worktree)), Failure): return committed say(f"applied the commits on {patch.base}; testing them with ci.sh") if isinstance(tested := run_ci(worktree, patch.ref, ci), Failure): return tested say("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 say(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" if isinstance(written := rewritten(patch_file, f"write {commit[:12]}'s changes to a file to apply", "Nothing is tagged.", lambda _: diff), Failure): return written 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, ci: Ci) -> Failure | None: """None where the patch's ci.sh passes on its committed head, run by ci; a Failure with the end of its output where it fails, or with ci's reason where it could not run or was stopped.""" if not (worktree / "ci.sh").exists(): return Failure("the patch holds no ci.sh to test it with") ran = ci(worktree) if isinstance(ran, Failure): return Failure(f"{ran.reason}. Nothing is tagged: fix that and rerun.") if ran.code == 0: return None tail = "\n".join(ran.output.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 ## section below ## Unreleased, and push that as the branch release-, 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 # The tag is pushed by now, so each stop here says that a rerun with the same commits takes it and builds only this merge-back again. rerun = f"v{patch.named} is pushed, and a rerun with the same commits merges it back." def move(changelog: str | None) -> str | Failure: moved = moved_entries(changelog or "", patch.entries, patch.named, patch.ref) return Failure(f"{moved.reason}: add the heading there. {rerun}") if isinstance(moved, Failure) else moved if isinstance(written := rewritten(worktree / "CHANGELOG.md", f"move the entries of {patch.named} out of ## Unreleased in the merge-back's worktree", rerun, move), Failure): return written 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, ref: str) -> str | Failure: """changelog, as ref holds it, with entries taken out of its ## Unreleased section and put in a ## named section right below that section; a Failure where it has no such heading.""" lines = changelog.split("\n") start = unreleased_start(lines) if start is None: return Failure(f"CHANGELOG.md on {ref} has no ## Unreleased heading to move the entries of {named} from") 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:]]) def unreleased_start(lines: list[str]) -> int | None: """The index in lines of a changelog's ## Unreleased heading; None where it has none.""" return next((index for index, line in enumerate(lines) if re.fullmatch(f"## {UNRELEASED_TITLE}", line)), None)