diff --git a/CHANGELOG.md b/CHANGELOG.md index bf14af88..a2b2e8b7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ - loop-claude starts a chunk on a fresh session where its session's transcript is empty, in place of resuming a session claude cannot find, which failed three times and waited for the human. - larv-review's prose pass takes a second round after a fix that rewrites a claim a command or a source file can check, such as generated output, a number or a licence term. - `deploy-release --cut-patch ` cuts the newest tag's next patch release, such as 0.15.2 after v0.15.1, holding only the commits named, for a fix that must ship before main's other unreleased work. It runs `ci.sh` on the patch, tags and pushes it, merges the tag back into main through a pull request, and moves `~/.claude` to it. Plain `--cut` now refuses a patch release, and a release review counts only for the release its title names: `Release review of 0.16.0` reviews 0.16.0 and no other. +- `deploy-release` keeps each run's steps, with their times, in a file under `~/.local/state/deploy-release/`, and stops a patch cut's `ci.sh` after 30 minutes, naming the log that holds its output. - `task-bench` plants bugs in Rust files too, from the mutants cargo-mutants catches, and tells Haiku the panic message `cargo test` prints. - `task-bench --tasks shipped-features` benches rebuilding features the project shipped: it takes each one's change out of the code, tells Haiku the tagline of its plan item, and checks the build with the tests that change holds. `--shipped ` sets how many it takes, and a feature whose branch landed by fast-forward starts after the latest earlier chunk that shipped an item or landed by a merge or a rebase, and is passed over where none comes before it or its branch merged the default branch into itself. - `task-bench` plants a Python mutant in a file whose lines end in CRLF, which it could not re-apply before, and a Go mutant there keeps applying. diff --git a/README.md b/README.md index 7a884dae..fa11ae69 100644 --- a/README.md +++ b/README.md @@ -196,7 +196,7 @@ Once the next release holds no item in `todo.md` and its release review has land bin/deploy-release --cut ``` -It renames `## Unreleased` in `CHANGELOG.md` to the version and merges that through a pull request, since nobody can push to `main`. Then it tags the merged commit `v`, pushes the tag, and moves this machine's `~/.claude` to it. Where a step fails it stops with the reason, and a rerun continues where it stopped. `deploy-release --help` lists the steps. Each other machine takes the release with Update. +It renames `## Unreleased` in `CHANGELOG.md` to the version and merges that through a pull request, since nobody can push to `main`. Then it tags the merged commit `v`, pushes the tag, and moves this machine's `~/.claude` to it. Where a step fails it stops with the reason, and a rerun continues where it stopped. A cut keeps each step it finished, with its time, in a file of its own under `~/.local/state/deploy-release/`. `deploy-release --help` lists the steps. Each other machine takes the release with Update. A fix that must ship before `main`'s other unreleased work goes out as a patch release, such as 0.15.2 after v0.15.1. File its item under that release, merge its chunk, then cut it at once with the commits the chunk merged, as a range or one commit. A range leaves out its first commit, as git's `..` does, so start it at the commit before the chunk's first: diff --git a/bin/deploy_release/ci_script.py b/bin/deploy_release/ci_script.py new file mode 100644 index 00000000..1e1e7fe2 --- /dev/null +++ b/bin/deploy_release/ci_script.py @@ -0,0 +1,55 @@ +"""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 + +from deploy_release.patch import Ci, CiRan +from failure import Failure +from deploy_release.trace import Say + +# As long as forge.pulls waits for a pull request's checks, which run the same ci.sh. +CI_SECONDS = 30 * 60 +# How long a stopped ci.sh has to end on SIGINT, which a container's CLI passes on to its container, before it is killed. +GRACE_SECONDS = 10 + + +def ci_runner(log: pathlib.Path, seconds: float, say: Say, grace: float = GRACE_SECONDS) -> Ci: + """Runs ci.sh in a worktree with its output in log, as it comes. A Failure where it can't start, where log can't be written, or where it still runs after seconds, which stops it and each process it started.""" + 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("w", encoding="utf-8") 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) + try: + code = process.wait(timeout=seconds) + except subprocess.TimeoutExpired: + stopped(process, grace) + return Failure(f"ci.sh still ran after {lasting(seconds)} and was stopped; {log} holds its output") + except BaseException: + # The cut is ending, as on Ctrl-C, which reaches only this process's group. + stopped(process, grace) + 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) -> None: + """End process's whole group: SIGINT first, then SIGKILL once grace seconds have passed.""" + 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() + + +def lasting(seconds: float) -> str: + return f"{seconds / 60:g} minutes" if seconds >= 60 else f"{seconds:g} seconds" diff --git a/bin/deploy_release/cut.py b/bin/deploy_release/cut.py index 13aba90e..5aff1434 100644 --- a/bin/deploy_release/cut.py +++ b/bin/deploy_release/cut.py @@ -3,9 +3,9 @@ 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 sys import tempfile import typing @@ -20,14 +20,23 @@ from forge.commands import forge_of, runner from plan.release import newest_tag, Release, 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." -def cut(clone: str, checkout: str, sleep: typing.Callable[[float], None]) -> 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.""" +@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): @@ -37,20 +46,20 @@ def cut(clone: str, checkout: str, sleep: typing.Callable[[float], None]) -> str 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. - release = ready_release(clone, ref, review=False) - if isinstance(release, Failure): - return release - named = version(release) - if isinstance(patched := patch_refusal(clone, ref, release), Failure): + if isinstance(patched := patch_refusal(clone, ref, ready.release), Failure): return patched - if isinstance(reviewed := ready_release(clone, ref), Failure): - return reviewed + if not ready.reviewed: + return Failure(f"the release review of {named} hasn't landed") 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) + 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): @@ -62,13 +71,13 @@ def cut(clone: str, checkout: str, sleep: typing.Callable[[float], None]) -> str return merged if isinstance(made := git("tag", "--annotate", "--message", title, tag, merged, cwd=clone), Failure): return made - said(f"tagged {merged[:12]} {tag}") + 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 - said(f"pushed the tag {tag}") - delete_release_branch(clone, branch) + 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.") @@ -86,21 +95,16 @@ def patch_refusal(clone: str, ref: str, release: Release) -> Failure | None: return None -def said(step: str) -> None: - """Say on stderr that step finished, so the human sees how far the cut got before the changelog fills the screen.""" - print(f"deploy-release: {step}", file=sys.stderr) - - -def delete_release_branch(clone: str, branch: str) -> 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): - said(f"warning: the branch {branch} stays on origin: {deleted.reason}") + say(f"warning: the branch {branch} stays on origin: {deleted.reason}") else: - said(f"deleted the branch {branch} on origin") + say(f"deleted the branch {branch} on origin") def drop_unpushed_cut_tags(clone: str) -> Failure | None: @@ -137,23 +141,23 @@ def clone_plan(clone: str) -> FilePlan: return FilePlan(pathlib.Path(clone, "todo.md"), "todo.md", goals, decisions, history, DEFAULT_FLOOR) -def ready_release(clone: str, ref: str, review: bool = True) -> Release | Failure: - """The next release, as chunk-preflight works it out, where it is ready to cut: it holds no item in todo.md, its release review has landed, unless review is False, and changes are unreleased.""" +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 release + 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 not review and release is not None: - return release - case ReviewDue(release=release): - return Failure(f"the release review of {version(release) if release else 'the next release'} hasn't landed") + 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): @@ -173,7 +177,7 @@ def commit_titled(title: str, ref: str, clone: str) -> str | None | Failure: 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]) -> Failure | 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.""" @@ -191,7 +195,7 @@ def land(clone: str, ref: str, branch: str, title: str, body: str, build: typing # 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 - said(f"pushed the branch {branch}") + 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 @@ -201,19 +205,19 @@ def land(clone: str, ref: str, branch: str, title: str, body: str, build: typing 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): - said(f"opened pull request {number}") + 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 - said(f"waiting for the checks of pull request {number}" + (f"; {base} requires {', '.join(sorted(required))}" if required else "")) + 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 - said(f"the checks of pull request {number} passed") + say(f"the checks of pull request {number} passed") if isinstance(merged := release_pull.merge(on, number, head, run), Failure): return merged - said(f"merged pull request {number}") + say(f"merged pull request {number}") return None @@ -235,16 +239,28 @@ def push_cut_commit(clone: str, ref: str, branch: str, named: str, title: str, r with scratch_worktree(clone, ref) as worktree: if isinstance(worktree, Failure): return worktree - changelog = worktree / "CHANGELOG.md" - renamed, count = UNRELEASED_HEADING.subn(f"## {named}", changelog.read_text() if changelog.exists() else "", count=1) - if not count: - return Failure(f"CHANGELOG.md on {ref} has no ## Unreleased section to rename") - changelog.write_text(renamed) + 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, so 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, 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. A Failure where rewrite gives one, which leaves the file, or where the file can't be read or written: that one says doing, the step that stopped, and names the file.""" + 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})")) + 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.""" diff --git a/bin/deploy_release/main.py b/bin/deploy_release/main.py index 5260c6ad..9ec0d0fb 100644 --- a/bin/deploy_release/main.py +++ b/bin/deploy_release/main.py @@ -33,6 +33,8 @@ with --cut-patch. deletes the branch on origin, then moves 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 is cut and pushed, and is on it.` +It keeps each of those lines, with its time, in a file of the run's own under $XDG_STATE_HOME/deploy-release +(default ~/.local/state/deploy-release), and so does --cut-patch. 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 @@ -51,7 +53,8 @@ doesn't hold, and on a GitHub origin, whose rebase merge would drop the tag from 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 `. 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 stops where it fails, before anything is tagged. +3. It runs ci.sh on that commit, with its output in a file beside the run's trace, which it names on stderr. It stops + where ci.sh fails or still runs after 30 minutes, before anything is tagged. 4. It tags the commit v, annotated `Cut release `, 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 ## section below it, commits that titled `Merge release into main`, and lands it through the branch @@ -60,15 +63,19 @@ doesn't hold, and on a GitHub origin, whose rebase merge would drop the tag from 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 datetime import os import pathlib +import shlex import sys import time +from deploy_release.ci_script import ci_runner, CI_SECONDS 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: @@ -82,12 +89,28 @@ def main(argv: list[str]) -> int: print("deploy-release: usage: deploy-release [--cut | --cut-patch ] []", file=sys.stderr) return 1 checkout = rest[0] if rest else str(pathlib.Path.home() / ".claude") + 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(), datetime.datetime.now + 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) if commits is not None: - moved = cut_patch(os.getcwd(), checkout, commits, time.sleep) + moved = cut_patch(clone, checkout, commits, time.sleep, say, ci_runner(folder / f"{name}-ci.log", CI_SECONDS, say)) else: - moved = cut(os.getcwd(), checkout, time.sleep) if cutting else deploy(checkout) + moved = cut(clone, checkout, time.sleep, say) if isinstance(moved, Failure): - print(f"deploy-release: {moved.reason}", file=sys.stderr) + 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 diff --git a/bin/deploy_release/patch.py b/bin/deploy_release/patch.py index 4f349905..3c34ea48 100644 --- a/bin/deploy_release/patch.py +++ b/bin/deploy_release/patch.py @@ -5,15 +5,15 @@ A rerun takes the tag an earlier run pushed, once it checks the tag lists the sa 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.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. @@ -36,29 +36,42 @@ class Patch: 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.""" +@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) - said(f"ships {'' if isinstance(subject, Failure) else subject.strip()}") + 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) + 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), Failure): + 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) + 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.") @@ -88,12 +101,12 @@ def planned(clone: str, checkout: str, commits: str) -> Patch | Failure: 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}") + 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 @@ -118,7 +131,7 @@ def patch_commits(clone: str, ref: str, base: str, commits: str) -> list[str] | 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.""" + """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) @@ -128,7 +141,11 @@ def changelog_entries(clone: str, ref: str, commits: list[str]) -> list[str] | F 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] + unreleased = section(changelog, UNRELEASED_TITLE) + # The merge-back finds the heading with unreleased_start, after the tag is pushed, so that is asked here too. + 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") @@ -143,7 +160,7 @@ def tagged_entries(clone: str, patch: Patch) -> Failure | None: return None -def tag_patch(clone: str, patch: Patch) -> Failure | 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: @@ -152,21 +169,22 @@ def tag_patch(clone: str, patch: Patch) -> Failure | None: 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)) + 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, so nothing is tagged", head), Failure): + return written 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): + 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 - said("ci.sh passed") + 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 - said(f"pushed the tag {tag}") + say(f"pushed the tag {tag}") return None @@ -187,7 +205,8 @@ def apply_commit(clone: str, worktree: pathlib.Path, commit: str, patch: Patch) if not diff: return None patch_file = worktree.parent / "commit.patch" - patch_file.write_text(diff) + if isinstance(written := rewritten(patch_file, f"write {commit[:12]}'s changes to a file to apply, so 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( @@ -199,14 +218,16 @@ def apply_commit(clone: str, worktree: pathlib.Path, commit: str, patch: Patch) 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.""" +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 = subprocess.run(["sh", "ci.sh"], capture_output=True, cwd=worktree, text=True, errors="replace") - if ran.returncode == 0: + ran = ci(worktree) + if isinstance(ran, Failure): + return Failure(f"{ran.reason}, so nothing is tagged. Rerun once that is fixed.") + if ran.code == 0: return None - tail = "\n".join((ran.stdout + ran.stderr).strip().splitlines()[-30:]) + 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}") @@ -217,19 +238,31 @@ def push_merge_back(clone: str, patch: Patch, replacing: str | None) -> 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)) + # 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) + return Failure(f"{moved.reason}, on {patch.ref}: 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) -> str: - """changelog with entries taken out of its ## Unreleased section and put in a ## named section right below that section.""" +def moved_entries(changelog: str, entries: list[str], named: str) -> str | Failure: + """changelog 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 = next(index for index, line in enumerate(lines) if re.fullmatch(f"## {UNRELEASED_TITLE}", line)) + start = unreleased_start(lines) + if start is None: + return Failure(f"CHANGELOG.md 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) diff --git a/bin/deploy_release/test_deploy_release.py b/bin/deploy_release/test_deploy_release.py index c8d2499e..30c88b6d 100644 --- a/bin/deploy_release/test_deploy_release.py +++ b/bin/deploy_release/test_deploy_release.py @@ -1,16 +1,19 @@ +import datetime +import io import json import os import pathlib import subprocess import sys import tempfile +import time import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) +from deploy_release import ci_script, cut, patch, trace from failure import Failure from test_env import isolated_env -from deploy_release import patch TOOL = pathlib.Path(__file__).resolve().parents[1] / "deploy-release" @@ -244,7 +247,7 @@ class Cut(unittest.TestCase): (fake / name).write_text(FAKE_FORGE) (fake / name).chmod(0o755) (self.temp / "gitconfig").write_text("[user]\n\tname = t\n\temail = t@t\n") - self.env = {**isolated_env(), "GIT_CONFIG_GLOBAL": str(self.temp / "gitconfig"), "GIT_CONFIG_NOSYSTEM": "1", "PATH": f"{fake}:{os.environ['PATH']}"} + self.env = {**isolated_env(), "GIT_CONFIG_GLOBAL": str(self.temp / "gitconfig"), "GIT_CONFIG_NOSYSTEM": "1", "PATH": f"{fake}:{os.environ['PATH']}", "XDG_STATE_HOME": str(self.temp / "state")} self.forge_state({"origin": str(self.origin), "pulls": [], "checks": "none", "calls": []}) self.git(self.temp, "init", "-q", "--bare", "-b", "main", str(self.origin)) self.clone = self.temp / "claude-config" @@ -470,6 +473,43 @@ class Cut(unittest.TestCase): self.assertEqual(self.cut().returncode, 1, "0.2.0 is cut, so a second run refuses") self.assertEqual(self.git(self.clone, "tag", "-l", "v0.2.0", "v9.9.9").split(), ["v0.2.0", "v9.9.9"]) + def traces(self) -> list[str]: + """The text of each run's trace, oldest first.""" + return [file.read_text() for file in sorted((self.temp / "state" / "deploy-release").glob("*.log")) if not file.name.endswith("-ci.log")] + + def test_keeps_each_step_of_a_cut_with_its_time_in_a_file_of_the_run(self): + self.assert_cut(self.cut()) + [kept] = self.traces() + lines = kept.splitlines() + self.assertRegex(lines[0], rf"^[0-9]{{4}}-[0-9]{{2}}-[0-9]{{2}}T[0-9:]{{8}}\S* deploy-release --cut {self.target} in {self.clone}$") + self.assertRegex(kept, r"(?m)^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9:]{8}\S* pushed the tag v0\.2\.0$") + self.assertIn("Done: v0.2.0 is cut and pushed", lines[-1]) + + def test_keeps_the_reason_a_cut_stopped_in_its_trace_and_a_rerun_writes_its_own(self): + self.assert_cut(self.cut()) + self.assertEqual(self.cut().returncode, 1) + first, second = self.traces() + self.assertTrue(second.endswith(" release 0.3.0 still holds items in todo.md\n"), second) + self.assertNotIn("still holds items", first) + + def test_reads_whether_the_next_releases_review_landed_beside_the_release(self): + self.assertEqual(cut.ready_release(str(self.clone), "origin/main"), cut.Ready((0, 2, 0), reviewed=True)) + self.plan_patch() + self.assertEqual(cut.ready_release(str(self.clone), "origin/main"), cut.Ready((0, 1, 1), reviewed=False)) + + def test_refuses_before_any_change_where_mains_changelog_has_no_unreleased_heading(self): + ran = self.cut_patch(self.plan_patch({"CHANGELOG.md": "# Changelog\n\n- Second.\n- Fixed.\n\n## 0.1.0\n\n- First.\n"})) + self.assertEqual(ran.returncode, 1) + self.assertIn("CHANGELOG.md on origin/main has no ## Unreleased section", ran.stderr) + self.assertEqual(self.origin_git("tag", "-l", "v0.1.1"), "") + + def test_says_where_ci_shs_output_goes_and_keeps_it_there(self): + ran = self.cut_patch(self.plan_patch({"ci.sh": "echo the suite ran\nexit 0\n"})) + self.assertEqual(ran.returncode, 0, ran.stderr) + [log] = (self.temp / "state" / "deploy-release").glob("*-ci.log") + self.assertEqual(log.read_text(), "the suite ran\n") + self.assertIn(f"ci.sh's output goes to {log}", ran.stderr) + def plan_patch(self, fix: dict[str, str] | None = None) -> str: """On top of setUp's main: a feature no patch may ship, item 3 filed under 0.1.1, then the commit that fixes tool.txt and finishes item 3, pushed. The revision range that names only the fix.""" self.commit({"feature.txt": "new\n"}, "Add a feature") @@ -678,6 +718,149 @@ class Cut(unittest.TestCase): +def still_runs(pid: int) -> bool: + """Whether the process pid runs: one that ended and that nobody has waited for yet doesn't.""" + try: + return pathlib.Path(f"/proc/{pid}/stat").read_text().rsplit(")", 1)[1].split()[0] != "Z" + except OSError: + return False + + +class PatchCi(unittest.TestCase): + """The patch's ci.sh run, read in-process with the runner handed in, and the runner itself on a real ci.sh.""" + + def setUp(self): + self.worktree = pathlib.Path(tempfile.mkdtemp()) + self.addCleanup(subprocess.run, ["rm", "-rf", str(self.worktree)]) + self.log = self.worktree / "ci.log" + self.said: list[str] = [] + + def test_passes_where_ci_sh_exits_zero(self): + (self.worktree / "ci.sh").write_text("exit 0\n") + seen: list[pathlib.Path] = [] + self.assertIsNone(patch.run_ci(self.worktree, "origin/main", lambda worktree: seen.append(worktree) or patch.CiRan(0, "fine\n"))) + self.assertEqual(seen, [self.worktree]) + + def test_a_failed_ci_sh_gives_the_last_30_lines_of_its_output(self): + (self.worktree / "ci.sh").write_text("exit 1\n") + failed = patch.run_ci(self.worktree, "origin/main", lambda worktree: patch.CiRan(1, "".join(f"line {number}\n" for number in range(1, 41)))) + self.assertIsInstance(failed, Failure) + self.assertIn("ci.sh failed on the patch, so nothing is tagged. Fix it on origin/main", failed.reason) + self.assertTrue(failed.reason.endswith("\nline 11\n" + "\n".join(f"line {number}" for number in range(12, 41))), failed.reason) + self.assertNotIn("line 10\n", failed.reason) + + def test_a_ci_sh_that_could_not_run_or_was_stopped_tags_nothing_and_gives_the_runners_reason(self): + (self.worktree / "ci.sh").write_text("exit 0\n") + failed = patch.run_ci(self.worktree, "origin/main", lambda worktree: Failure("ci.sh still ran after 30 minutes and was stopped")) + self.assertEqual(failed, Failure("ci.sh still ran after 30 minutes and was stopped, so nothing is tagged. Rerun once that is fixed.")) + + def test_refuses_a_patch_without_ci_sh_before_running_anything(self): + self.assertEqual(patch.run_ci(self.worktree, "origin/main", lambda worktree: self.fail("ran")), Failure("the patch holds no ci.sh to test it with")) + + def test_the_runner_writes_ci_shs_output_to_the_log_as_it_runs_and_gives_its_exit_code(self): + (self.worktree / "ci.sh").write_text("echo out\necho err >&2\nexit 3\n") + ran = ci_script.ci_runner(self.log, 30, self.said.append)(self.worktree) + self.assertEqual(ran, patch.CiRan(3, "out\nerr\n")) + self.assertEqual(self.log.read_text(), "out\nerr\n") + self.assertEqual(self.said, [f"ci.sh's output goes to {self.log}; it is stopped where it still runs after 30 seconds"]) + + def test_the_runner_stops_a_ci_sh_that_hangs_with_what_it_started_and_says_so(self): + (self.worktree / "ci.sh").write_text("echo started\nsleep 60 &\necho $! >child.pid\nwait\n") + began = time.monotonic() + ran = ci_script.ci_runner(self.log, 0.5, self.said.append, grace=0.2)(self.worktree) + self.assertLess(time.monotonic() - began, 20) + self.assertEqual(ran, Failure(f"ci.sh still ran after 0.5 seconds and was stopped; {self.log} holds its output")) + self.assertEqual(self.log.read_text(), "started\n") + child = int((self.worktree / "child.pid").read_text()) + deadline = time.monotonic() + 5 + while still_runs(child) and time.monotonic() < deadline: + time.sleep(0.05) + self.assertFalse(still_runs(child), "the process ci.sh started still runs") + + def test_the_runner_gives_a_failure_where_ci_sh_cannot_start(self): + ran = ci_script.ci_runner(self.log, 30, self.said.append)(self.worktree / "gone") + self.assertIsInstance(ran, Failure) + self.assertIn("ci.sh could not run: ", ran.reason) + self.assertIn(str(self.worktree / "gone"), ran.reason) + + def test_the_runner_gives_a_failure_where_the_log_cannot_be_written(self): + (self.worktree / "ci.sh").write_text("exit 0\n") + ran = ci_script.ci_runner(self.worktree / "no-folder" / "ci.log", 30, self.said.append)(self.worktree) + self.assertIsInstance(ran, Failure) + self.assertIn(str(self.worktree / "no-folder" / "ci.log"), ran.reason) + + +class Trace(unittest.TestCase): + """What a cut says, in-process, with the clock and stderr handed in.""" + + def setUp(self): + self.temp = pathlib.Path(tempfile.mkdtemp()) + self.addCleanup(subprocess.run, ["rm", "-rf", str(self.temp)]) + self.now = lambda: datetime.datetime(2026, 11, 27, 9, 30, 5) + + def test_keeps_traces_under_the_state_folder_xdg_names_else_under_homes(self): + self.assertEqual(trace.trace_folder({"XDG_STATE_HOME": "/x/state"}, pathlib.Path("/home/u")), pathlib.Path("/x/state/deploy-release")) + self.assertEqual(trace.trace_folder({}, pathlib.Path("/home/u")), pathlib.Path("/home/u/.local/state/deploy-release")) + + def test_names_a_run_by_its_start_and_its_process(self): + self.assertEqual(trace.run_name(self.now(), 4711), "2026-11-27T09-30-05-4711") + + def test_starts_a_trace_with_the_command_then_appends_each_step_with_its_time_and_says_it(self): + file = trace.started(self.temp / "state" / "deploy-release", "run", "deploy-release --cut", self.now) + self.assertEqual(file, self.temp / "state" / "deploy-release" / "run.log") + out = io.StringIO() + say = trace.saying(file, self.now, out) + say("pushed the tag v0.2.0") + say("merged pull request 3") + self.assertEqual(out.getvalue(), "deploy-release: pushed the tag v0.2.0\ndeploy-release: merged pull request 3\n") + self.assertEqual(file.read_text(), "2026-11-27T09:30:05 deploy-release --cut\n2026-11-27T09:30:05 pushed the tag v0.2.0\n2026-11-27T09:30:05 merged pull request 3\n") + + def test_a_trace_that_cannot_be_started_is_a_failure_naming_the_file(self): + (self.temp / "state").write_text("a file where the folder goes\n") + made = trace.started(self.temp / "state" / "deploy-release", "run", "deploy-release --cut", self.now) + self.assertIsInstance(made, Failure) + self.assertIn(str(self.temp / "state" / "deploy-release" / "run.log"), made.reason) + + def test_still_says_each_step_where_there_is_no_trace_or_it_cannot_be_written(self): + out = io.StringIO() + trace.saying(None, self.now, out)("pushed the tag v0.2.0") + trace.saying(self.temp / "gone" / "run.log", self.now, out)("merged pull request 3") + self.assertEqual(out.getvalue().splitlines()[:2], ["deploy-release: pushed the tag v0.2.0", "deploy-release: merged pull request 3"]) + self.assertIn(f"warning: the trace {self.temp / 'gone' / 'run.log'} could not be written", out.getvalue().splitlines()[2]) + + +class Rewritten(unittest.TestCase): + """A cut's file edits, where the filesystem refuses one.""" + + def setUp(self): + self.temp = pathlib.Path(tempfile.mkdtemp()) + self.addCleanup(subprocess.run, ["rm", "-rf", str(self.temp)]) + + def test_replaces_a_files_text_and_hands_none_for_a_file_that_is_not_there(self): + file = self.temp / "CHANGELOG.md" + self.assertIsNone(cut.rewritten(file, "head CHANGELOG.md", lambda text: f"{text!r} new\n")) + self.assertEqual(file.read_text(), "None new\n") + self.assertIsNone(cut.rewritten(file, "head CHANGELOG.md", lambda text: text.upper())) + self.assertEqual(file.read_text(), "NONE NEW\n") + + def test_a_file_that_cannot_be_read_or_written_is_a_failure_naming_the_step_and_the_file(self): + folder = self.temp / "CHANGELOG.md" + folder.mkdir() + # A folder can't be read as a file, and a file in a folder that isn't there can't be written. + for file in (folder, self.temp / "gone" / "commit.patch"): + with self.subTest(file=file): + failed = cut.rewritten(file, "head CHANGELOG.md with ## 0.1.1, so nothing is tagged", lambda text: "new\n") + self.assertIsInstance(failed, Failure) + self.assertTrue(failed.reason.startswith("could not head CHANGELOG.md with ## 0.1.1, so nothing is tagged: "), failed.reason) + self.assertIn(str(file), failed.reason) + + def test_gives_the_rewrites_own_failure_and_leaves_the_file(self): + file = self.temp / "CHANGELOG.md" + file.write_text("old\n") + self.assertEqual(cut.rewritten(file, "x", lambda text: Failure("no heading")), Failure("no heading")) + self.assertEqual(file.read_text(), "old\n") + + class PatchChangelog(unittest.TestCase): """The changelog edits of a patch cut, read in-process, so a mutation tester reaches them.""" @@ -698,6 +881,9 @@ class PatchChangelog(unittest.TestCase): def test_puts_the_section_last_where_unreleased_is_the_last_section(self): self.assertEqual(patch.moved_entries("# Changelog\n\n## Unreleased\n\n- Fixed.\n", ["- Fixed."], "0.1.1"), "# Changelog\n\n## Unreleased\n\n## 0.1.1\n\n- Fixed.\n") + def test_a_changelog_without_an_unreleased_heading_is_a_failure_that_names_it(self): + self.assertEqual(patch.moved_entries("# Changelog\n\n## 0.1.0\n\n- First.\n", ["- Fixed."], "0.1.1"), Failure("CHANGELOG.md has no ## Unreleased heading to move the entries of 0.1.1 from")) + if __name__ == "__main__": unittest.main() diff --git a/bin/deploy_release/trace.py b/bin/deploy_release/trace.py new file mode 100644 index 00000000..c97397dd --- /dev/null +++ b/bin/deploy_release/trace.py @@ -0,0 +1,55 @@ +"""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 datetime +import pathlib +import typing + +from failure import Failure + +# Says that one step of a cut finished, as `saying` makes it. +Say = typing.Callable[[str], None] +Clock = typing.Callable[[], datetime.datetime] + + +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.""" + state = env.get("XDG_STATE_HOME") or str(home / ".local" / "state") + return pathlib.Path(state) / "deploy-release" + + +def run_name(began: datetime.datetime, pid: int) -> str: + """The name of the files one run keeps, which sorts by when it began.""" + return f"{began:%Y-%m-%dT%H-%M-%S}-{pid}" + + +def stamped(at: datetime.datetime, line: str) -> str: + return f"{at.isoformat(timespec='seconds')} {line}\n" + + +def started(folder: pathlib.Path, name: str, command: str, now: Clock) -> pathlib.Path | Failure: + """A new trace, /.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 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 diff --git a/bin/do_epic/finish.py b/bin/do_epic/finish.py index 5452d53c..c4b74f9f 100644 --- a/bin/do_epic/finish.py +++ b/bin/do_epic/finish.py @@ -19,6 +19,7 @@ from do_epic.split import finished from do_epic.repo_pick import label_of, LabelRepos, recorded, Repo from text_files.markdown_text import listed from text_files.piped_text import piped +from plan.release import REVIEW_TITLE # Not `--close`, which reads as closing the run or one issue: three readers, seated as the human, as a chunk's worker and as one of the client's team, picked this one from four, 2-1 over it. CLOSE = "--close-epic" @@ -67,7 +68,7 @@ def task(epic: str, issues: list[EpicIssue], team: LabelRepos, launcher: pathlib f"{opening} Each repo the epic changed takes a release review first, and {listed(lacking, 'and')} {'has' if len(lacking) == 1 else 'have'} none. " f"File one issue per such repo, with `{launcher} {epic} {findings.FILE} \"\" {findings.LABEL}