"""`deploy-release --cut`: cut the next release once it is ready, through a pull request, then tag it and move ~/.claude to it. Each step first checks whether an earlier run did it, so a rerun continues where the last run stopped. """ import contextlib import dataclasses import pathlib import shutil import tempfile import typing from release_plan.release_standing import chunk_item, Cut, default_plan, Next, ReadyToCut, ReviewDue, Unplanned from project_config.settings import DEFAULT_FLOOR from git_cli.git_repo import default_ref, git from deploy_release.deploy import deploy from failure import Failure from plan_store.todo_md import FilePlan from record_store.stores import FileStore from forge.commands import forge_of, runner from plan.release import newest_tag, Release, REVIEW_TITLE, tagged, UNRELEASED_HEADING, version from forge import pulls from deploy_release import release_pull from deploy_release.trace import Say from project_config import templates CUT_BODY = "Rename ## Unreleased in CHANGELOG.md to the version." @dataclasses.dataclass(frozen=True) class Ready: """The next release, which holds no item in todo.md while changes are unreleased.""" release: Release # Whether its release review has landed. reviewed: bool def cut(clone: str, checkout: str, sleep: typing.Callable[[float], None], say: Say) -> str | Failure: """What the cut did, as the tool prints it; a Failure with git's, the forge's or the tool's reason where a step stopped. say takes each step as it finishes.""" 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 ready = ready_release(clone, ref) if isinstance(ready, Failure): return ready named = version(ready.release) # The patch refusal comes before the review's: a patch takes no release review, so "hasn't landed" would send the human the wrong way. if isinstance(patched := patch_refusal(clone, ref, ready.release), Failure): return patched if not ready.reviewed: return Failure(f"the release review of {named} hasn't landed: {ref} holds no commit titled `{REVIEW_TITLE}{named}` after the newest tag. `chunk-preflight --help` says which commit counts.") title, tag, branch = f"Cut release {named}", f"v{named}", f"release-{named}" merged = commit_titled(title, ref, clone) if merged is None: build = lambda replacing: push_cut_commit(clone, ref, branch, named, title, replacing) landed = land(clone, ref, branch, title, CUT_BODY, build, sleep, say) if isinstance(landed, Failure): return landed if isinstance(fetched := git("fetch", "--quiet", "origin", cwd=clone), Failure): return fetched merged = commit_titled(title, ref, clone) if merged is None: return Failure(f"the pull request merged, but {ref} holds no commit titled {title!r}") if isinstance(merged, Failure): return merged if isinstance(made := git("tag", "--annotate", "--message", title, tag, merged, cwd=clone), Failure): return made say(f"tagged {merged[:12]} {tag}") 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}") 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 patch_refusal(clone: str, ref: str, release: Release) -> Failure | None: """A Failure where release is a patch of the newest tag ref holds: a cut of all of ref would ship its other work under a patch number.""" tag = newest_tag(clone, merged_into=ref) if isinstance(tag, Failure): return tag cut_release = tagged(tag) if cut_release is not None and release[:2] == cut_release[:2]: return Failure(f"{version(release)} is a patch of {tag}: cut it with --cut-patch , so it holds only the fix and not all of {ref}") return None def delete_release_branch(clone: str, branch: str, say: Say) -> None: """Delete origin's merged branch, where it is still there; only warn where that fails, since the release is cut by then.""" listed = branch_head(branch, clone) if listed is None: return deleted = listed if isinstance(listed, Failure) else git("push", "--quiet", "origin", "--delete", f"refs/heads/{branch}", cwd=clone) if isinstance(deleted, Failure): say(f"warning: the branch {branch} stays on origin: {deleted.reason}") else: say(f"deleted the branch {branch} on origin") def drop_unpushed_cut_tags(clone: str) -> Failure | None: """Delete each v* tag the clone holds but origin doesn't, where it tags a commit titled `Cut release `: one a run made and never pushed, such as a run that died between the two. The clone reads cut releases from its own tags, so such a tag would read as a cut nobody published.""" local = git("tag", "--list", "v*", "--format=%(refname:short) %(*subject)", cwd=clone) remote = git("ls-remote", "--tags", "--refs", "origin", "refs/tags/v*", cwd=clone) if isinstance(local, Failure): return local if isinstance(remote, Failure): return remote pushed = {line.split("refs/tags/", 1)[-1] for line in remote.splitlines()} for line in local.splitlines(): tag, _, subject = line.partition(" ") if tag not in pushed and subject == f"Cut release {tag.removeprefix('v')}": if isinstance(deleted := git("tag", "--delete", tag, cwd=clone), Failure): return deleted return None def same_origin(clone: str, checkout: str) -> Failure | None: """A Failure unless clone is a clone of the origin checkout takes its releases from, so a cut never cuts another project.""" urls = [git("ls-remote", "--get-url", "origin", cwd=where) for where in (clone, checkout)] failed = next((url for url in urls if isinstance(url, Failure)), None) if failed is not None: return failed if urls[0] != urls[1]: return Failure(f"run deploy-release in a clone of {checkout}'s origin, {str(urls[1]).strip()}; this directory's origin is {str(urls[0]).strip()}") return None def clone_plan(clone: str) -> FilePlan: """The clone's plan, at the path this repo keeps it. ready_release only reads it; FilePlan also takes the files and the floor a write would rank it against, and the clone has no config to set the floor.""" goals, decisions, history = (FileStore(pathlib.Path(clone, path), path) for path in ("README.md", "docs/decisions.md", "docs/comprehension-history.md")) return FilePlan(pathlib.Path(clone, "todo.md"), "todo.md", goals, decisions, history, DEFAULT_FLOOR) def ready_release(clone: str, ref: str) -> Ready | Failure: """The next release, as chunk-preflight works it out, where it holds no item in todo.md and changes are unreleased, with whether its release review has landed: the caller decides whether the cut needs one.""" # No project's config names the clone, so its changelog is read at the fixed path, on ref like the plan, and its titles as they stand. plan = default_plan(clone, ref, clone_plan(clone), FileStore(pathlib.Path(clone, "CHANGELOG.md"), "CHANGELOG.md"), templates.BARE) if isinstance(plan.plan, Failure): return Failure(f"todo.md on {ref} cannot be read: {plan.plan.reason}") match chunk_item(plan.plan.items, plan.cut): case ReadyToCut(release=release) if release is not None: return Ready(release, reviewed=True) case ReadyToCut(): return Failure("todo.md names no release after the last one cut") case Next(release=release) if release is not None: return Failure(f"release {version(release)} still holds items in todo.md") case ReviewDue(release=release) if release is not None: return Ready(release, reviewed=False) case ReviewDue(): return Failure("the release review of the next release hasn't landed") case Unplanned(): return Failure("every change is released already: nothing has landed since the last release cut") case Cut(release=release): return Failure(f"todo.md files items under {version(release)}, which is cut already") case _: return Failure("cannot tell which release is next") def commit_titled(title: str, ref: str, clone: str) -> str | None | Failure: """The commit titled title on ref, after the newest tag; None where there is none.""" tag = newest_tag(clone, merged_into=ref) if isinstance(tag, Failure): return tag log = git("log", "--format=%H %s", f"{tag}..{ref}" if tag else ref, cwd=clone) if isinstance(log, Failure): return log return next((line.split(" ", 1)[0] for line in log.splitlines() if line.split(" ", 1)[1:] == [title]), None) def land(clone: str, ref: str, branch: str, title: str, body: str, build: typing.Callable[[str | None], Failure | None], sleep: typing.Callable[[float], None], say: Say) -> Failure | None: """Push branch and open its pull request, titled title with body, where an earlier run hasn't; then wait for its checks and merge it. build pushes branch's commit, made on ref. It takes the commit origin's branch points at, which the push replaces, or None where origin has no such branch yet.""" url = git("config", "--get", "remote.origin.url", cwd=clone) if isinstance(url, Failure): return url on, run, base = forge_of(url), runner(clone), ref.removeprefix("origin/") head = branch_head(branch, clone) if isinstance(head, Failure): return head behind = head is not None and behind_main(branch, head, ref, clone) if isinstance(behind, Failure): return behind if head is None or behind: # Where main moved on, such as to fix a failed check, the branch could no longer merge fast-forward, so it is rebuilt on main. if isinstance(pushed := build(head), Failure): return pushed say(f"pushed the branch {branch}") head = branch_head(branch, clone) or Failure(f"pushed {branch}, but origin holds no such branch") if isinstance(head, Failure): return head number = pulls.open_pull(on, branch, head, run) if number is None: if isinstance(created := release_pull.create_pull(on, branch, base, title, body, run), Failure): return created number = pulls.open_pull(on, branch, head, run) or Failure(f"opened a pull request for {branch}, but the forge lists none from origin at {head[:12]}") if isinstance(number, str): say(f"opened pull request {number}") if isinstance(number, Failure): return number required = pulls.required_checks(on, base, run) if isinstance(required, Failure): return required say(f"waiting for the checks of pull request {number}" + (f"; {base} requires {', '.join(sorted(required))}" if required else "")) if isinstance(passed := pulls.checks_passed(on, number, head, required, run, sleep), Failure): return passed say(f"the checks of pull request {number} passed") if isinstance(merged := release_pull.merge(on, number, head, run), Failure): return merged say(f"merged pull request {number}") return None def branch_head(branch: str, clone: str) -> str | None | Failure: """The commit origin's branch points at; None where origin has no such branch.""" listed = git("ls-remote", "--heads", "origin", f"refs/heads/{branch}", cwd=clone) return listed if isinstance(listed, Failure) else next(iter(listed.split()), None) def behind_main(branch: str, head: str, ref: str, clone: str) -> bool | Failure: """Whether origin's branch, at head, lacks a commit ref holds.""" if isinstance(fetched := git("fetch", "--quiet", "origin", f"refs/heads/{branch}", cwd=clone), Failure): return fetched return isinstance(git("merge-base", "--is-ancestor", ref, head, cwd=clone), Failure) def push_cut_commit(clone: str, ref: str, branch: str, named: str, title: str, replacing: str | None) -> Failure | None: """Commit ref's CHANGELOG.md with ## Unreleased renamed to named, in a worktree of its own, and push it as branch, replacing the commit origin's branch points at, where there is one.""" with scratch_worktree(clone, ref) as worktree: if isinstance(worktree, Failure): return worktree def renamed(changelog: str | None) -> str | Failure: text, count = UNRELEASED_HEADING.subn(f"## {named}", changelog or "", count=1) return text if count else Failure(f"CHANGELOG.md on {ref} has no ## Unreleased section to rename") if isinstance(written := rewritten(worktree / "CHANGELOG.md", f"rename ## Unreleased to ## {named} in the cut's worktree", "Nothing is pushed.", renamed), Failure): return written if isinstance(committed := git("commit", "--quiet", "-am", title, cwd=str(worktree)), Failure): return committed return push_branch(worktree, branch, replacing) def rewritten(file: pathlib.Path, doing: str, outcome: str, rewrite: typing.Callable[[str | None], str | Failure]) -> Failure | None: """Replace file's text with what rewrite makes of it, or of None where there is no such file. Where rewrite gives a Failure, return it and leave the file. Where the file can't be read or written, the Failure names doing, the step that stopped, then the file, and ends with outcome, a sentence on where that leaves the run.""" try: text = rewrite(file.read_text(encoding="utf-8") if file.exists() else None) if isinstance(text, Failure): return text file.write_text(text, encoding="utf-8") except (OSError, UnicodeError) as failure: return Failure(f"could not {doing}: {failure}" + ("" if str(file) in str(failure) else f" ({file})") + f". {outcome}") return None @contextlib.contextmanager def scratch_worktree(clone: str, at: str) -> typing.Iterator[pathlib.Path | Failure]: """A worktree of clone, detached at at, in a folder of its own that is removed afterwards, so the clone's checkout stays as it is; a Failure where git can't add it.""" worktree = pathlib.Path(tempfile.mkdtemp(prefix="deploy-release-")) / "worktree" try: added = git("worktree", "add", "--quiet", "--detach", str(worktree), at, cwd=clone) yield added if isinstance(added, Failure) else worktree finally: git("worktree", "remove", "--force", str(worktree), cwd=clone) shutil.rmtree(worktree.parent, ignore_errors=True) def push_branch(worktree: pathlib.Path, branch: str, replacing: str | None) -> Failure | None: """Push worktree's HEAD to origin as branch: a new one, or in place of replacing, only while origin's branch still points at it.""" 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