Replace deploy-release with self-update, which moves the clone it ships in, and cut-release
CI / tests (pull_request) Has been cancelled

This commit is contained in:
2026-12-03 23:52:02 +01:00
parent b56ab170f0
commit 3b07c05eba
10 changed files with 0 additions and 0 deletions
View File
+79
View File
@@ -0,0 +1,79 @@
"""Run a patch's ci.sh with its output in a file the human can follow, and stop it where it runs too long."""
import contextlib
import os
import pathlib
import signal
import subprocess
import typing
from deploy_release.patch import Ci, CiRan
from failure import Failure
from deploy_release.trace import Say
from forge.pulls import WAIT_SECONDS
# As long as a pull request's checks get, since they run the same ci.sh.
CI_SECONDS = WAIT_SECONDS
# How long a stopped ci.sh has to end on SIGINT before it is killed.
GRACE_SECONDS = 10
# How long docker has to remove a stopped ci.sh's container.
REMOVE_SECONDS = 60
# Where ci.sh reads the name to give its test container.
CONTAINER = "CI_CONTAINER"
# Removes the container of a name, running or not; a Failure where it may still run.
Remove = typing.Callable[[str], Failure | None]
def ci_runner(log: pathlib.Path, seconds: float, say: Say, container: str, remove: Remove, grace: float = GRACE_SECONDS) -> Ci:
"""Runs ci.sh in a worktree with its output in log, as it comes, and its test container named container. A Failure where it can't start, where log can't be written, or where it still runs after seconds. In that last case the runner stops ci.sh, each process ci.sh started, and that container."""
def run(worktree: pathlib.Path) -> CiRan | Failure:
say(f"ci.sh's output goes to {log}; it is stopped where it still runs after {lasting(seconds)}")
try:
with log.open("wb") as output:
# In a session of its own, ci.sh and each process it starts share one process group, which `stopped` ends whole.
process = subprocess.Popen(["sh", "ci.sh"], cwd=worktree, stdin=subprocess.DEVNULL, stdout=output, stderr=subprocess.STDOUT, start_new_session=True, env={**os.environ, CONTAINER: container})
try:
code = process.wait(timeout=seconds)
except subprocess.TimeoutExpired:
left = stopped(process, grace, container, remove)
running = f", but its container {container} may still run: {left.reason}" if left else ""
return Failure(f"ci.sh still ran after {lasting(seconds)} and was stopped{running}; {log} holds its output")
except BaseException:
# The cut is ending, as on Ctrl-C, which reaches only this process's group.
stopped(process, grace, container, remove)
raise
return CiRan(code, log.read_text(encoding="utf-8", errors="replace"))
except OSError as failure:
return Failure(f"ci.sh could not run: {failure}")
return run
def stopped(process: subprocess.Popen[bytes], grace: float, container: str, remove: Remove) -> Failure | None:
"""End process's whole group, SIGINT first, then SIGKILL once grace seconds have passed, and then its container; a Failure where the container may still run."""
try:
with contextlib.suppress(ProcessLookupError):
os.killpg(process.pid, signal.SIGINT)
with contextlib.suppress(subprocess.TimeoutExpired):
process.wait(timeout=grace)
finally:
with contextlib.suppress(ProcessLookupError):
os.killpg(process.pid, signal.SIGKILL)
process.wait()
# The daemon runs the container, outside the group, and no signal to ci.sh's docker CLI ends the tests in it. It is removed last, once nothing in the group can start it.
left = remove(container)
return left
def removed_container(container: str, run: typing.Callable[..., subprocess.CompletedProcess[str]] = subprocess.run) -> Failure | None:
"""Removes container with docker, running or not; None too where no such container exists."""
argv = ["docker", "rm", "--force", container]
try:
ran = run(argv, stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=REMOVE_SECONDS)
except (OSError, subprocess.TimeoutExpired) as failure:
return Failure(f"{' '.join(argv)} failed: {failure}")
return Failure(f"{' '.join(argv)} failed: {ran.stderr.strip()}") if ran.returncode else None
def lasting(seconds: float) -> str:
count, unit = (seconds / 60, "minute") if seconds >= 60 else (seconds, "second")
return f"{count:g} {unit}{'' if count == 1 else 's'}"
+280
View File
@@ -0,0 +1,280 @@
"""`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 <commits>, 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 <its version>`: 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
+122
View File
@@ -0,0 +1,122 @@
"""Move the checkout Claude Code reads its configuration from to this repo's newest release; with --cut, first cut the next release, and with --cut-patch, a patch release of only the commits named.
usage: deploy-release [--cut | --cut-patch <commits>] [<checkout>]
<checkout> defaults to ~/.claude. The tool fetches origin's tags and checks out the newest v* tag,
detached, so the checkout holds only what a release holds. Development happens in another clone,
such as ~/code/claude-config. It prints the version it moved from and to, then CHANGELOG.md's
section for each version since, so you can do what each asks, such as a new step under Install.
Where the move changed settings.json, it asks you to pick the model again with /model, since git's
clean filter keeps the model out of every commit.
It refuses, exit 1, and leaves the checkout as it was where a file the checkout tracks has an
uncommitted change the newest tag doesn't hold: such as a hook Claude Code wrote into settings.json.
Merge the change through the development clone and cut a release first. A model picked with /model
is no such change. It also refuses where the newest tag doesn't hold the checkout's commit, since
the move would drop work no release holds. Untracked files, such as Claude Code's sessions and
memory, stay as they are.
--cut runs in the development clone, and refuses where that clone's origin isn't <checkout>'s. It cuts the next release, as chunk-preflight works it out, and
refuses without changing anything, unless that release holds no item in todo.md, its release review has
landed, as chunk-preflight --help counts one, and changes are unreleased. The release names the version; the tool doesn't choose one. It also refuses a
release that is a patch of the newest tag, such as 0.15.2 after v0.15.1, since it would ship all of main: cut that
with --cut-patch.
1. On a fresh origin/main, it renames ## Unreleased in CHANGELOG.md to the version, commits that
titled `Cut release <version>`, and pushes it as the branch release-<version>. The clone's own
checkout stays as it is. Where main has moved past the branch, it rebuilds the branch on main.
2. It opens a pull request for the branch, with gh on a GitHub origin and tea elsewhere, waits for
its checks where there are any, and merges it fast-forward only. On Gitea it also waits for
each check main's branch protection requires to report, and names them. It gives up after 30
minutes, naming any required check that never passed. GitHub has no fast-forward merge, so
there it rebase-merges the branch, which is already on top of main.
3. It tags the merged commit v<version>, annotated `Cut release <version>`, pushes only the tag,
deletes the branch on origin, then moves <checkout> to the tag as above. A failed delete only warns.
It says on stderr as each step finishes, and ends stdout, after the changelog, with the line
`Done: v<version> is cut and pushed, and <checkout> is on it.`
It keeps each of those lines, with its time in UTC, in the run's trace: a file of its own under
$XDG_STATE_HOME/build-release/deploy-release (default ~/.local/state/build-release/deploy-release), named by when the run began. --cut-patch does too.
Where Ctrl-C or an unexpected fault ends the run, the trace ends with a line that starts `stopped:`.
Where a step fails it stops, exit 1, with git's or the forge's reason, and leaves the pull request
and the branch as they are. A rerun continues: it takes the branch's open pull request and a cut
commit already merged, and drops a cut tag an earlier run made but never pushed. Once the tag is pushed, the release is cut: where only the
move stopped, fix what it names and run a bare deploy-release.
--cut-patch <commits> runs in the development clone too, for a fix that must ship before main's other unreleased work. It
cuts the newest tag's next patch release, holding only <commits> on top of the tag. <commits> is a range as git log reads
it, such as 794ce37..1aa2367, which leaves out 794ce37 as git's `..` does, or one commit, which it reads as that commit
alone. Name the commits the fix's chunk merged, including the one that finished its item: the entries that commit added
under ## Unreleased in CHANGELOG.md become the release's. Each commit must be on origin's main and not in the tag. Merge
commits are left out, and so are the commits a merge of main brought into the range. todo.md must name the release and
file no item under it; a patch skips the release review. Cut it as soon as the fix merges: until then chunk-preflight calls
the patch's release review due, and build-release would run it. It refuses without changing anything where any of that
doesn't hold, and on a GitHub origin, whose rebase merge would drop the tag from main's history.
1. It says on stderr which commits the release ships.
2. In a worktree of its own at the tag, it applies each commit's changes, except to CHANGELOG.md, todo.md,
docs/comprehension-history.md and docs/reading-cost.md, heads CHANGELOG.md with the release's section, and commits that
titled `Cut release <version>`. Where a commit doesn't apply, it stops, names it, and says how to cut the patch by hand.
3. It runs ci.sh on that commit and names on stderr the file, beside the run's trace, that takes ci.sh's output. It
stops where ci.sh fails or still runs after 30 minutes, before anything is tagged.
4. It tags the commit v<version>, annotated `Cut release <version>`, and pushes only the tag.
5. On a fresh origin/main it merges the tag keeping main's files, moves the release's entries from ## Unreleased to a
## <version> section below it, commits that titled `Merge release <version> into main`, and lands it through the branch
release-<version> and a pull request as --cut does. Then it checks main holds the tag.
6. It moves <checkout> to the tag as above, and ends stdout as --cut does.
A rerun takes a tag origin holds already, once it checks the tag lists the same changelog entries, and the merge-back's open
pull request. Once the merge-back has merged, the release is cut: where only the move stopped, run a bare deploy-release.
"""
import os
import pathlib
import shlex
import sys
import time
from deploy_release.ci_script import ci_runner, CI_SECONDS, removed_container
from loop_state.paths import CLAUDE_HOME
from deploy_release.cut import cut
from deploy_release.patch import cut_patch
from deploy_release.deploy import deploy
from failure import Failure
from deploy_release import trace
def main(argv: list[str]) -> int:
if argv[:1] in (["-h"], ["--help"]):
print(__doc__.strip())
return 0
cutting, patching = argv[:1] == ["--cut"], argv[:1] == ["--cut-patch"]
commits = argv[1] if patching and len(argv) > 1 else None
rest = argv[2:] if patching else argv[1:] if cutting else argv
if len(rest) > 1 or rest[:1] and rest[0].startswith("-") or patching and (commits is None or commits.startswith("-")):
print("deploy-release: usage: deploy-release [--cut | --cut-patch <commits>] [<checkout>]", file=sys.stderr)
return 1
checkout = rest[0] if rest else str(pathlib.Path.home() / CLAUDE_HOME)
if not cutting and commits is None:
moved = deploy(checkout)
if isinstance(moved, Failure):
print(f"deploy-release: {moved.reason}", file=sys.stderr)
return 1
print(moved)
return 0
clone, now = os.getcwd(), time.time
folder, name = trace.trace_folder(os.environ, pathlib.Path.home()), trace.run_name(now(), os.getpid())
begun = trace.started(folder, name, f"deploy-release {shlex.join([*argv[:2 if patching else 1], checkout])} in {clone}", now)
if isinstance(begun, Failure):
print(f"deploy-release: warning: {begun.reason}", file=sys.stderr)
file = None if isinstance(begun, Failure) else begun
say = trace.saying(file, now, sys.stderr)
try:
if commits is not None:
moved = cut_patch(clone, checkout, commits, time.sleep, say, ci_runner(folder / f"{name}-ci.log", CI_SECONDS, say, f"deploy-release-ci-{name}", removed_container))
else:
moved = cut(clone, checkout, time.sleep, say)
except BaseException as stopped:
# Ctrl-C or a fault nobody foresaw: its traceback reaches only the terminal, so the trace says the run ended here.
trace.kept(file, f"stopped: {stopped!r}", now, sys.stderr)
raise
if isinstance(moved, Failure):
say(moved.reason)
return 1
print(moved)
# The ending is on stdout already, so only the trace takes it.
trace.kept(file, moved.splitlines()[-1], now, sys.stderr)
return 0
+268
View File
@@ -0,0 +1,268 @@
"""`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 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 <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, 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 <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
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 ## <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
# 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)
+23
View File
@@ -0,0 +1,23 @@
"""Opening and merging a cut's pull request, with gh where origin is on GitHub and with tea elsewhere.
merge is pinned to head, the commit origin's release branch points at: the forge merges the pull request only while its head is still that commit, so a push to the branch after its checks passed is never merged.
"""
from failure import Failure
from forge.commands import Forge, gitea, Run
def create_pull(forge: Forge, branch: str, base: str, title: str, body: str, run: Run) -> Failure | None:
described = ["--body" if forge == "gh" else "--description", body]
command = ["gh", "pr"] if forge == "gh" else ["tea", "pulls"]
created = run([*command, "create", "--head", branch, "--base", base, "--title", title, *described])
return created if isinstance(created, Failure) else None
def merge(forge: Forge, number: str, head: str, run: Run) -> Failure | None:
"""Merge pull request number, fast-forward only on Gitea and by rebase on GitHub. The forge refuses where the pull request's head is no longer head."""
if forge == "gh":
# GitHub has no fast-forward-only merge. A rebase merge of a branch already on top of main is the nearest, though it may give the commit a new hash, so the cut finds it on main by its title.
merged = run(["gh", "pr", "merge", number, "--rebase", "--match-head-commit", head])
else:
merged = gitea(run, f"repos/{{owner}}/{{repo}}/pulls/{number}/merge", "Do=fast-forward-only", f"head_commit_id={head}")
return merged if isinstance(merged, Failure) else None
File diff suppressed because it is too large Load Diff
+57
View File
@@ -0,0 +1,57 @@
"""What a cut says as each step finishes: on stderr, and in a file of the run's own, so the steps outlast the terminal."""
import pathlib
import time
import typing
from failure import Failure
from loop_state.paths import state_folder
from text_files import utc_stamp
# Says that one step of a cut finished, as `saying` makes it.
Say = typing.Callable[[str], None]
# The time now, in seconds since the epoch, as time.time gives it.
Clock = typing.Callable[[], float]
def trace_folder(env: typing.Mapping[str, str], home: pathlib.Path) -> pathlib.Path:
"""The folder each cut keeps its trace in, under the state folder as run-heavy finds it."""
return state_folder(env, home) / "deploy-release"
def run_name(began: float, pid: int) -> str:
"""The name of the files one run keeps, which sorts by when it began: that time in UTC, with no colon, so the name is valid on every disk."""
return f"{time.strftime('%Y-%m-%dT%H-%M-%SZ', time.gmtime(began))}-{pid}"
def stamped(at: float, line: str) -> str:
return f"{utc_stamp.utc(at)} {line}\n"
def started(folder: pathlib.Path, name: str, command: str, now: Clock) -> pathlib.Path | Failure:
"""A new trace, <folder>/<name>.log, whose first line is command; a Failure where it can't be written."""
file = folder / f"{name}.log"
try:
folder.mkdir(parents=True, exist_ok=True)
file.write_text(stamped(now(), command), encoding="utf-8")
except OSError as failure:
return Failure(f"the trace {file} could not be started: {failure}")
return file
def kept(trace: pathlib.Path | None, line: str, now: Clock, out: typing.TextIO) -> None:
"""Append line with its time, in UTC, to trace, where there is one. A trace that can't be written only warns on out, since the cut's own steps count."""
if trace is None:
return
try:
with trace.open("a", encoding="utf-8") as file:
file.write(stamped(now(), line))
except OSError as failure:
print(f"deploy-release: warning: the trace {trace} could not be written: {failure}", file=out)
def saying(trace: pathlib.Path | None, now: Clock, out: typing.TextIO) -> Say:
"""Says each step on out, so the human sees how far the cut got before the changelog fills the screen, and keeps it in trace."""
def say(step: str) -> None:
print(f"deploy-release: {step}", file=out)
kept(trace, step, now, out)
return say