diff --git a/.gitignore b/.gitignore index 729fb625..ca350af0 100644 --- a/.gitignore +++ b/.gitignore @@ -157,8 +157,9 @@ !bin/subagent_rung/*.py !bin/task-bench !bin/task_bench/ -!bin/task_bench/*.py -!bin/task_bench/gather-prompt.md +!bin/task_bench/**/ +!bin/task_bench/**/*.py +!bin/task_bench/figures/gather-prompt.md !bin/test_*.py !bin/text_files/ !bin/text_files/*.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 8aa1d128..8c5c855b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,8 @@ - task-bench leaves out of a fix a change Haiku makes to a Rust test module that stands in the file of the code it tests, and passes over a Rust mutant whose test modules it cannot tell apart. - 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 a release later than the last cut. +- `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 --cut` and `--cut-patch` keep each step, with its time in UTC, in a file under `~/.local/state/deploy-release/`, and `--cut-patch` stops `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 0af7783e..8dd7e6dd 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 UTC, 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: @@ -243,15 +243,12 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a ### Packages under `bin/` -`bin/` is the import root: each launcher puts it on `sys.path`, so a module imports another by its path under `bin/`, such as `from claude_code.entries import parse_entry`. Each tool's package holds its tests. Beside the packages, `bin/`'s root holds only the launchers, the tools of one file with their tests, `test_env.py`, `failure.py` and `setup.cfg`. `failure.py`'s `Failure`, which modules across `bin/` return for a failed step, belongs to no single package. `agent_cycle/`, `atlassian/`, `branch_chunks/`, `chunk_driver/`, `claude_code/`, `command_lines/`, `forge/`, `git_cli/`, `loop_effects/`, `loop_state/`, `machine_load/`, `model_routing/`, `notifier/`, `plan/`, `plan_store/`, `record_store/`, `release_plan/`, `review_rules/`, `rung_replay/`, `text_files/` and `transcript_archive/` serve more than one tool. No package imports one that imports it back, and a package's `doubles.py` holds the test doubles that other packages' tests use, so no module imports a `test_*` module of another package; `repo_checks/test_package_cycles.py` checks both. No Python file of the repo, `workflow-bench/`'s included, uses `mock.patch`, which `repo_checks/test_no_patched_globals.py` checks. +`bin/` is the import root: each launcher puts it on `sys.path`, so a module imports another by its path under `bin/`, such as `from claude_code.entries import parse_entry`. Each tool's package holds its tests. Beside the packages, `bin/`'s root holds only the launchers, the tools of one file with their tests, `test_env.py`, `failure.py` and `setup.cfg`. `failure.py`'s `Failure`, which modules across `bin/` return for a failed step, belongs to no single package. `agent_cycle/`, `atlassian/`, `branch_chunks/`, `chunk_driver/`, `claude_code/`, `command_lines/`, `forge/`, `git_cli/`, `loop_effects/`, `loop_state/`, `machine_load/`, `model_routing/`, `notifier/`, `plan/`, `plan_store/`, `record_store/`, `release_plan/`, `review_rules/`, `rung_replay/`, `text_files/` and `transcript_archive/` serve more than one tool. No package imports one that imports it back, and a package's `doubles.py` holds the test doubles that other packages' tests use, so no module imports a `test_*` module of another package; `repo_checks/test_package_cycles.py` checks both. No Python file of the repo, `workflow-bench/`'s included, uses `mock.patch`, which `repo_checks/test_no_patched_globals.py` checks. Within each group below, the entries are in alphabetical order. + +#### Driving chunks -- `adf_codec/` converts markdown to ADF, the rich text of Jira Cloud and Confluence, and back, in a throwaway container running a pinned `@larvit/adf-codec`. It builds the container's image inside a heavy slot. - `agent_cycle/` runs one cycle (`run.py`): a headless claude worker, then the judge of its transcript. It also holds the interrupt, the tmux window and the routing of the worker's rung. The entry point that runs the cycles supplies the prompts and file names of its own workflow (`worker_prompts.py`), and reads which items a worker took in. `loop_claude` and `do_epic` drive it; `agent_cycle` doesn't import either. -- `atlassian/` holds what the Jira and Confluence backends share (`client.py`): one Atlassian account's credentials, the request both backends send, and each service's error messages. `jira.py` holds what every reader of Jira shares: a search read page by page, the key, fields, links and property of each issue it finds, checked for their shape, and the transition that finishes an issue, for `plan_store` and `do_epic`. -- `branch_chunks/` cuts a default branch into chunks and finds, for each, the items it shipped and the later chunks that fixed its code, for `score_outcomes`, `routing_figures` and `task_bench`. It imports `reading_cost`'s record path. - `chunk_driver/` holds what the entry points share. An entry point is a tool that drives chunks through `agent_cycle`: `loop_claude` and `do_epic` are the two. They share how a cycle starts (`cycle_start.py`) and closes (`chunk_run.py`), the claim on a checkout before a chunk starts in it (`claims.py`), the prompts every worker gets (`prompts.py`), and a checkout's premises, records and saved models (`project/`). It imports neither entry point, and `repo_checks` fails any package that imports one of the two. `agent_cycle` is the layer below it, and `repo_checks` fails `agent_cycle` where it imports `chunk_driver`, tests included. -- `command_lines/` reads a shell command: its simple commands, and a docker call's subcommand and memory limits, for `command_patterns`, `reading_cost`, `routing_figures`, `rule_hook` and `run_heavy`. -- `deploy_release` imports `release_plan`'s `release_standing`. - `do_epic/` holds `do-epic`, the tool that drives one Jira epic: - `main.py` starts the epic's chunks and runs one chunk's cycles in its window, through `agent_cycle`. `epic_run.py` holds what stays the same through one run of do-epic, such as its config, its Jira store and its paths, and starts the chunks that may start now. - `planning.py` settles, before the chunks start, where each open issue is worked, its scores and the order the issues start in, through `split.py`, `repo_pick.py`, `issue_scores.py` and `ranking.py`. @@ -267,29 +264,49 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a - `ranking.py` orders an epic's items by score over one chain of goals, the epic's, then code health, then the item's repo's, through `plan`'s ranking, and re-ranks the tracker's backlog to that order through `backend/`. - `backend/` reads, files and ranks the epic's issues, adds the labels `repo_pick.py` and `split.py` record, posts comments, moves a finished chunk's issue to done, and closes the epic. - `e2e/` holds `do-epic-e2e`. -- `forge/` tells a GitHub origin from a Gitea one, names a repo beside an origin's and runs that forge's CLI (`commands.py`), finds a pull request, lists the ready ones and reads its checks, once or until they settle (`pulls.py`), and reads a pull request's review state (`reviews.py`), for `chunk_preflight`, `chunk_pr`, `deploy_release`, `do_epic` and `larv_review`. -- `git_cli/` runs git for every tool (`git_repo.py`), reads the git calls in a shell command (`git_command.py`), and keeps an epic's working branch level with the default branch (`epic_branch.py`). -- `judge_replay` imports `agent_cycle`'s judge and verdicts, and `chunk_driver`'s premises, records and `ANSWER_DESTINATIONS`. - `loop_claude` runs `chunk-preflight` as a process of its own. - `loop_effects/` holds `Effects`: the processes, terminal, clock and git a tool reaches, injected so its tests can script them. loop-claude, do-epic, both replay tools and `reviewer-merge-trials`' driver use it. - `loop_state/` holds where loop-claude and do-epic keep their files (`paths.py`), which `rung_replay` reads too. -- `machine_load/` takes the machine's heavy slots, its shared lock files, for `run_heavy` and `adf_codec`, and reads the memory share that loop-claude waits for. It also gives `mutate_changes` a slot's CPU count. - `model_routing/` holds the shipped routing ladder (`routing-ladder.json`) and its steps (`ladder.py`), and reads a ladder from that file or a project's own (`ladder_file.py`), for loop-claude, `rule_hook`, `do_epic`, both replay tools and `subagent-rung`. It finds a project's config folder through `project_config`. It also holds the list prices, which `routing_figures` and `transcript_archive` read. - `notifier/` sends the human a DM through the notifier a project's config names, for `notify` and for loop-claude through `loop_effects`. Its backends are `mattermost.py` and `slack.py`. +- `transcript_archive/` stores loop-claude's transcripts. Its `project_key.py` names each project's archive folder, loop-claude session and models-file entry. + +#### The plan, the records and releases + +- `deploy_release` imports `release_plan`'s `release_standing`. - `plan/` is the plan's core, and imports neither `plan_store` nor `release_plan`. It holds an item and the items table's format (`todo_table.py`), releases (`release.py`), the ranking (`ranking.py`, with its score formula in `formula.py` and its blocker order in `blockers.py`), the paths an item's text names (`named_paths.py`), an item's `Touches:` prediction and where two overlap (`touches.py`), and `citations.py`, which holds `todo.md` and `docs/decisions.md` to each other. `goals_file.py` reads the goals file's sections, goals and goal weights, for the ranking and for `loop_claude`'s premises. - `plan_store/` reads and writes a project's plan through the store the project's config names (`stores.py`). Every backend meets `plans.py`'s `PlanStore`: a markdown file (`todo_md.py`, which also ranks and checks the file in place, with its text edits in `markdown_edits.py`) or a Jira epic (`jira_epic.py`). `scoring.py` reads the goal weights that both backends rank by. `contract.py` holds the tests every backend that writes must pass; `jira_epic.py` doesn't yet, and its own tests stand in for Jira. `fakes.py` holds a plan in memory. -- `rank_todo.py`, `settings_filter.py` and `statusline.py` are tools of one file each, tested beside them. - `record_store/` reads and writes a project's records, each through the store the project's config names (`stores.py`): a markdown file, a Confluence Cloud page (`confluence_page.py`), or, for the goals, a Jira epic's description (`jira_description.py`). `contract.py` holds the tests every backend must pass, and `fakes.py` a store in memory that the tests of other tools use. - `release_plan/` says which release is next and whether it is ready to cut (`release_standing.py`), from the plan, the changelog and the tags, picks the item the next chunk takes first (`next_chunk.py`), and marks each item that a ready pull request finishes (`awaiting_merge.py`), for `chunk_preflight` and `loop_claude`. -- `repo_checks/` tests the repo itself. -- `rest_client/` sends a JSON request to a REST API and reads its credentials from an env file, for `notifier`, `atlassian` and `record_store`. - `review_rules/` holds the larv-review rules that several tools apply: its passes, its review folder, its round commit titles and the comprehension history's format. + +#### Git, forges and Atlassian + +- `adf_codec/` converts markdown to ADF, the rich text of Jira Cloud and Confluence, and back, in a throwaway container running a pinned `@larvit/adf-codec`. It builds the container's image inside a heavy slot. +- `atlassian/` holds what the Jira and Confluence backends share (`client.py`): one Atlassian account's credentials, the request both backends send, and each service's error messages. `jira.py` holds what every reader of Jira shares: a search read page by page, the key, fields, links and property of each issue it finds, checked for their shape, and the transition that finishes an issue, for `plan_store` and `do_epic`. +- `forge/` tells a GitHub origin from a Gitea one, names a repo beside an origin's and runs that forge's CLI (`commands.py`), finds a pull request, lists the ready ones and reads its checks, once or until they settle (`pulls.py`), and reads a pull request's review state (`reviews.py`), for `chunk_preflight`, `chunk_pr`, `deploy_release`, `do_epic` and `larv_review`. +- `git_cli/` runs git for every tool (`git_repo.py`), reads the git calls in a shell command (`git_command.py`), and keeps an epic's working branch level with the default branch (`epic_branch.py`). +- `rest_client/` sends a JSON request to a REST API and reads its credentials from an env file, for `notifier`, `atlassian` and `record_store`. + +#### Measuring and replaying + +- `branch_chunks/` cuts a default branch into chunks and finds, for each, the items it shipped and the later chunks that fixed its code, for `score_outcomes`, `routing_figures` and `task_bench`. It imports `reading_cost`'s record path. +- `judge_replay` imports `agent_cycle`'s judge and verdicts, and `chunk_driver`'s premises, records and `ANSWER_DESTINATIONS`. - `routing_figures/` measures loop-claude's archive, and each of its projects' default branches, for loop-claude's routing calls. - `rung_replay/` holds what `judge_replay` and `review_replay` share: the parallel replay runner, the argument reader, the candidate rungs and the exits, and `judge_replay`'s rung search. It reads `agent_cycle`'s retry count and `chunk_driver`'s models file, and finds that file through `loop_state`'s paths. Its `archive.py` keeps each replay's runs and its report in a `replays/` folder of loop-claude's archive. -- `task_bench/` holds `task-bench`, which plants bugs in a project's Go, PHP, Python, Rust, TypeScript and JavaScript files, or takes the project's bench features, its data sources or the features its history shipped, and has Haiku fix, build or add them in containers. -- `test_env.py` serves the tests. +- `task_bench/` holds `task-bench`, which has Haiku fix, build or add a task in containers: a bug planted in a project's Go, PHP, Python, Rust, TypeScript and JavaScript files (`bugs/`), or one of the project's bench features, its data sources or the features its history shipped (`features/`). `figures/` measures the runs and holds `task-bench gather`. + +#### The shell, the machine and text + +- `command_lines/` reads a shell command: its simple commands, and a docker call's subcommand and memory limits, for `command_patterns`, `reading_cost`, `routing_figures`, `rule_hook` and `run_heavy`. +- `machine_load/` takes the machine's heavy slots, its shared lock files, for `run_heavy` and `adf_codec`, and reads the memory share that loop-claude waits for. It also gives `mutate_changes` a slot's CPU count. - `text_files/` reads a Markdown file's `##` sections, quotes a passage and joins names into a list, reads the text piped into a command, stamps times in UTC, replaces a file in one step, private where it is new, and gzips a file beside its plain name, by which it reads it afterwards. -- `transcript_archive/` stores loop-claude's transcripts. Its `project_key.py` names each project's archive folder, loop-claude session and models-file entry. + +#### Tests and tools of one file + +- `rank_todo.py`, `settings_filter.py` and `statusline.py` are tools of one file each, tested beside them. +- `repo_checks/` tests the repo itself. +- `test_env.py` serves the tests. ## Test diff --git a/bin/chunk_preflight/main.py b/bin/chunk_preflight/main.py index c9560eb5..9487ea08 100644 --- a/bin/chunk_preflight/main.py +++ b/bin/chunk_preflight/main.py @@ -28,11 +28,14 @@ and prints that the release reviews and the cuts are the human's to call. It pri that todo.md has named at that cut or since, less a release its ## Renamed section marks renamed. Where nothing is cut, it is the earliest release todo.md has ever named, less those renamed, so a release whose items are all done still reads as next. - Where the next release holds no item, it says so, naming it where todo.md named it since the cut: - its release review due where changes are unreleased (the ## Unreleased entries, or else the - commits since the cut) and no commit titled `Release review of ` followed the tag, - finished and ready to cut once one did, and else to be planned first. On a branch with no tag, - such a commit counts only where its is after the version under the dated heading. + Where the next release holds no item, it says so, and names the release where todo.md named it + since the cut. Where no change is unreleased (the ## Unreleased entries, or else the commits + since the cut), that release is to be planned first. Otherwise its release review is due, and + once the review has landed the release is finished and ready to cut. The review has landed + once a commit titled `Release review of `, where is exactly the next + release, is on the default branch after the newest v* tag, or anywhere on a branch with no + tag. The one exception: where todo.md named no next release since the cut, such a commit + counts whichever release it names. Where todo.md files items under x.y.z or earlier, someone cut a release that still held them: they count as the next release, the earliest after x.y.z that todo.md names or has named since the cut, and a line says to move them there. Where there is no such release, it says todo.md files items under a release diff --git a/bin/chunk_preflight/test_chunk_preflight.py b/bin/chunk_preflight/test_chunk_preflight.py index 2ec1ee14..ed6a98bb 100644 --- a/bin/chunk_preflight/test_chunk_preflight.py +++ b/bin/chunk_preflight/test_chunk_preflight.py @@ -705,7 +705,9 @@ class Plans(unittest.TestCase): def test_names_the_start_as_the_last_cut_where_nothing_is_cut(self): said = planned(EMPTY, LastCut(None, "", 4, [TODO]), "origin/main", BRANCH).why self.assertIn("release 0.2.0, the next after the start, since no release is cut yet,", said) - self.assertIn("has landed yet.", said) + self.assertIn("no commit titled `Release review of 0.2.0` has landed yet.", said) + self.assertIn("`chunk-preflight --help`", said) + self.assertIn("`Release review of ` has landed since the cut.", planned(EMPTY, LastCut("v0.1.0", "", 4, [EMPTY]), "origin/main", BRANCH).why, "todo.md named no release since the cut") self.assertIn("since the cut.", planned(EMPTY, LastCut(None, "## 0.1.0 - 2026-10-03\n", 4, [TODO]), "origin/main", BRANCH).why) def test_finds_the_release_after_the_last_cut_finished_or_to_be_planned_where_the_plan_holds_no_item_for_it(self): @@ -722,7 +724,7 @@ class Plans(unittest.TestCase): ) for todo, commits, todos, reviewed, fact, release in cases: with self.subTest(todo=todo, commits=commits, todos=todos, reviewed=reviewed): - why = planned(todo, LastCut("v0.1.0", "", commits, todos, reviewed), "origin/main", BRANCH).why + why = planned(todo, LastCut("v0.1.0", "", commits, todos, frozenset({(0, 2, 0)} if reviewed else ())), "origin/main", BRANCH).why self.assertIn(fact, why) self.assertIn(release, why) diff --git a/bin/deploy_release/ci_script.py b/bin/deploy_release/ci_script.py new file mode 100644 index 00000000..3e104a27 --- /dev/null +++ b/bin/deploy_release/ci_script.py @@ -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'}" diff --git a/bin/deploy_release/cut.py b/bin/deploy_release/cut.py index b6f795af..9dd22ea6 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 @@ -17,17 +17,26 @@ 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, tagged, UNRELEASED_HEADING, version +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." -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,17 +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 - release = ready_release(clone, ref) - if isinstance(release, Failure): - return release - named = version(release) - if isinstance(patched := patch_refusal(clone, ref, release), Failure): + 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) + 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): @@ -59,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.") @@ -83,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: @@ -134,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): @@ -170,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.""" @@ -188,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 @@ -198,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 @@ -232,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", "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.""" diff --git a/bin/deploy_release/main.py b/bin/deploy_release/main.py index ff665415..43a4bcf7 100644 --- a/bin/deploy_release/main.py +++ b/bin/deploy_release/main.py @@ -18,7 +18,7 @@ memory, stay as they are. --cut runs in the development clone, and refuses where that clone's origin isn't '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 and changes are unreleased. The release names the version; the tool doesn't choose one. It also refuses a +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 @@ -33,6 +33,9 @@ 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 UTC, in the run's trace: a file of its own under +$XDG_STATE_HOME/deploy-release (default ~/.local/state/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 @@ -51,7 +54,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 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, 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 @@ -62,13 +66,16 @@ pull request. Once the merge-back has merged, the release is cut: where only the """ import os import pathlib +import shlex import sys import time +from deploy_release.ci_script import ci_runner, CI_SECONDS, removed_container 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,33 @@ 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 commits is not None: - moved = cut_patch(os.getcwd(), checkout, commits, time.sleep) - else: - moved = cut(os.getcwd(), checkout, time.sleep) if cutting else deploy(checkout) + 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): - 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..d8c874e9 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 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") @@ -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", "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", "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}. Nothing is tagged: fix that and rerun.") + 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, 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) -> 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, 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 = 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 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) diff --git a/bin/deploy_release/test_deploy_release.py b/bin/deploy_release/test_deploy_release.py index c8d2499e..5cf69ada 100644 --- a/bin/deploy_release/test_deploy_release.py +++ b/bin/deploy_release/test_deploy_release.py @@ -1,16 +1,22 @@ +import contextlib +import io import json import os import pathlib +import signal import subprocess import sys import tempfile +import threading +import time +import typing 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 +250,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 +476,77 @@ 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}}Z 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}Z pushed the tag v0\.2\.0$") + self.assertIn("Done: v0.2.0 is cut and pushed", lines[-1]) + [file] = (self.temp / "state" / "deploy-release").glob("*.log") + self.assertRegex(file.name, r"^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}-[0-9]{2}-[0-9]{2}Z-[0-9]+\.log$") + + 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_refuses_a_release_whose_review_has_not_landed_naming_the_commit_title_that_counts(self): + self.assert_cut(self.cut()) + self.git(self.clone, "pull", "-q", "--ff-only", "origin", "main") + self.commit({"CHANGELOG.md": "# Changelog\n\n## Unreleased\n\n- Third.\n\n## 0.2.0\n\n- Second.\n\n## 0.1.0\n\n- First.\n", "todo.md": TODO}, "Ship item 2") + self.git(self.clone, "push", "-q", "origin", "main") + ran = self.cut() + self.assertEqual(ran.returncode, 1) + self.assertIn("the release review of 0.3.0 hasn't landed", ran.stderr) + self.assertIn("`Release review of 0.3.0`", ran.stderr) + self.assertIn("`chunk-preflight --help`", ran.stderr) + + def test_a_cut_stopped_by_ctrl_c_ends_its_trace_saying_so(self): + self.set_checks("pending") + process = subprocess.Popen([sys.executable, str(TOOL), "--cut", str(self.target)], cwd=self.clone, env=self.env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + self.addCleanup(process.kill) + deadline = time.monotonic() + 30 + while not any("waiting for the checks" in kept for kept in self.traces()) and time.monotonic() < deadline: + time.sleep(0.05) + process.send_signal(signal.SIGINT) + self.assertNotEqual(process.wait(timeout=30), 0) + [kept] = self.traces() + self.assertRegex(kept.splitlines()[-1], r"^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9:]{8}Z stopped: KeyboardInterrupt\(\)$") + + 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_says_why_no_release_is_ready_where_nothing_has_landed_or_no_release_is_named_and_reviewed(self): + self.commit({"CHANGELOG.md": "# Changelog\n\n## 0.4.0\n\n- Second.\n\n## 0.1.0\n\n- First.\n", "todo.md": TODO}, "Cut release 0.4.0") + self.git(self.clone, "tag", "-a", "v0.4.0", "-m", "Cut release 0.4.0") + self.git(self.clone, "push", "-q", "origin", "main", "--tags") + self.assertEqual(cut.ready_release(str(self.clone), "origin/main"), Failure("every change is released already: nothing has landed since the last release cut")) + self.commit({"CHANGELOG.md": "# Changelog\n\n## Unreleased\n\n- Third.\n\n## 0.4.0\n\n- Second.\n\n## 0.1.0\n\n- First.\n"}, "Ship a third change") + self.git(self.clone, "push", "-q", "origin", "main") + self.assertEqual(cut.ready_release(str(self.clone), "origin/main"), Failure("the release review of the next release hasn't landed")) + + 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 +755,285 @@ 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 + + +@contextlib.contextmanager +def typed(text: bytes) -> typing.Iterator[None]: + """This process's stdin holding text, as a terminal someone typed it at would, for what a child inherits.""" + kept = os.dup(0) + reading, writing = os.pipe() + os.write(writing, text) + os.close(writing) + os.dup2(reading, 0) + os.close(reading) + try: + yield + finally: + os.dup2(kept, 0) + os.close(kept) + + +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] = [] + self.removed: list[str] = [] + self.remove = lambda container: self.removed.append(container) + + 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; /state/run-ci.log holds its output")) + self.assertEqual(failed, Failure("ci.sh still ran after 30 minutes and was stopped; /state/run-ci.log holds its output. Nothing is tagged: fix that and rerun.")) + + 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, "ci-of-a-test", self.remove)(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, "ci-of-a-test", self.remove, 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_kills_a_stopped_ci_sh_that_ignores_the_interrupt_once_its_grace_has_passed(self): + (self.worktree / "ci.sh").write_text("trap '' INT\necho started\nsleep 60\n") + began = time.monotonic() + ran = ci_script.ci_runner(self.log, 0.5, self.said.append, "ci-of-a-test", self.remove, 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.removed, ["ci-of-a-test"]) + + def test_the_runner_stops_ci_sh_and_removes_its_container_where_the_cut_is_interrupted(self): + (self.worktree / "ci.sh").write_text("trap '' INT\necho started\nsleep 60\n") + def interrupt_once_ci_sh_runs(): + while not (self.log.exists() and self.log.read_bytes()): + time.sleep(0.02) + os.kill(os.getpid(), signal.SIGINT) + began = time.monotonic() + threading.Thread(target=interrupt_once_ci_sh_runs, daemon=True).start() + with self.assertRaises(KeyboardInterrupt): + ci_script.ci_runner(self.log, 30, self.said.append, "ci-of-a-test", self.remove, grace=0.2)(self.worktree) + self.assertLess(time.monotonic() - began, 20) + self.assertEqual(self.removed, ["ci-of-a-test"]) + + def test_stopping_a_ci_sh_that_ended_already_still_removes_its_container(self): + process = subprocess.Popen(["true"], start_new_session=True) + process.wait() + self.assertIsNone(ci_script.stopped(process, 0.2, "ci-of-a-test", self.remove)) + self.assertEqual(self.removed, ["ci-of-a-test"]) + + def test_the_runner_gives_ci_sh_no_input_to_wait_for(self): + (self.worktree / "ci.sh").write_text('read line\necho "read: $line"\n') + with typed(b"typed\n"): + ran = ci_script.ci_runner(self.log, 30, self.said.append, "ci-of-a-test", self.remove)(self.worktree) + self.assertEqual(ran, patch.CiRan(0, "read: \n")) + + def test_the_runner_gives_output_that_is_not_utf_8_with_each_such_byte_replaced(self): + (self.worktree / "ci.sh").write_text("printf 'caf\\351 ok\\n'\n") + ran = ci_script.ci_runner(self.log, 30, self.said.append, "ci-of-a-test", self.remove)(self.worktree) + self.assertEqual(ran, patch.CiRan(0, "caf\ufffd ok\n")) + + def test_the_runner_says_its_bound_in_minutes_from_a_minute_up(self): + (self.worktree / "ci.sh").write_text("exit 0\n") + for seconds, lasting in ((1800, "30 minutes"), (60, "1 minute"), (59, "59 seconds"), (1, "1 second")): + with self.subTest(seconds=seconds): + self.said.clear() + ci_script.ci_runner(self.log, seconds, self.said.append, "ci-of-a-test", self.remove)(self.worktree) + self.assertEqual(self.said, [f"ci.sh's output goes to {self.log}; it is stopped where it still runs after {lasting}"]) + + def test_the_runner_names_ci_shs_container_and_removes_it_where_it_stops_ci_sh(self): + (self.worktree / "ci.sh").write_text('echo "$CI_CONTAINER"\nsleep 60\n') + ran = ci_script.ci_runner(self.log, 0.5, self.said.append, "ci-of-a-test", self.remove, grace=0.2)(self.worktree) + 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(), "ci-of-a-test\n") + self.assertEqual(self.removed, ["ci-of-a-test"]) + + def test_the_runner_says_where_the_container_of_a_stopped_ci_sh_may_still_run(self): + (self.worktree / "ci.sh").write_text("sleep 60\n") + ran = ci_script.ci_runner(self.log, 0.5, self.said.append, "ci-of-a-test", lambda container: Failure("docker rm --force ci-of-a-test failed: no daemon"), grace=0.2)(self.worktree) + self.assertEqual(ran, Failure(f"ci.sh still ran after 0.5 seconds and was stopped, but its container ci-of-a-test may still run: docker rm --force ci-of-a-test failed: no daemon; {self.log} holds its output")) + + def test_the_runner_removes_no_container_where_ci_sh_ends_in_time(self): + (self.worktree / "ci.sh").write_text("exit 0\n") + ci_script.ci_runner(self.log, 30, self.said.append, "ci-of-a-test", self.remove)(self.worktree) + self.assertEqual(self.removed, []) + + def test_removing_a_container_gives_a_failure_where_docker_fails_and_none_where_it_removes(self): + asked: list[list[str]] = [] + def docker(code: int, stderr: str): + return lambda argv, **options: asked.append(argv) or subprocess.CompletedProcess(argv, code, "", stderr) + self.assertIsNone(ci_script.removed_container("ci-of-a-test", docker(0, ""))) + self.assertEqual(asked, [["docker", "rm", "--force", "ci-of-a-test"]]) + self.assertEqual(ci_script.removed_container("ci-of-a-test", docker(1, "Cannot connect to the Docker daemon\n")), Failure("docker rm --force ci-of-a-test failed: Cannot connect to the Docker daemon")) + + def test_removing_a_container_gives_a_failure_where_docker_cannot_start(self): + def no_docker(argv, **options): + raise FileNotFoundError("docker") + self.assertEqual(ci_script.removed_container("ci-of-a-test", no_docker), Failure("docker rm --force ci-of-a-test failed: docker")) + + def test_removing_a_container_gives_dockers_own_error_and_no_input_to_wait_for(self): + fake = self.worktree / "fake-bin" + fake.mkdir() + (fake / "docker").write_text('#!/bin/sh\nread line\necho "no daemon for $*, read: $line" >&2\nexit 1\n') + (fake / "docker").chmod(0o755) + found_first = lambda argv, **options: subprocess.run(argv, env={**os.environ, "PATH": f"{fake}:{os.environ['PATH']}"}, **options) + with typed(b"typed\n"): + left = ci_script.removed_container("ci-of-a-test", found_first) + self.assertEqual(left, Failure("docker rm --force ci-of-a-test failed: no daemon for rm --force ci-of-a-test, read:")) + + def test_removing_a_container_gives_a_failure_where_docker_takes_longer_than_a_minute(self): + def slow_docker(argv, **options): + raise subprocess.TimeoutExpired(argv, options["timeout"]) + left = ci_script.removed_container("ci-of-a-test", slow_docker) + self.assertIsInstance(left, Failure) + self.assertTrue(left.reason.startswith("docker rm --force ci-of-a-test failed: "), left.reason) + self.assertIn("timed out after 60 seconds", left.reason) + + def test_ci_sh_names_its_container_only_where_it_is_given_a_name(self): + script = (pathlib.Path(__file__).resolve().parents[2] / "ci.sh").read_text() + self.assertIn('${CI_CONTAINER:+--name "$CI_CONTAINER"}', script) + + def test_the_runner_gives_a_failure_where_ci_sh_cannot_start(self): + ran = ci_script.ci_runner(self.log, 30, self.said.append, "ci-of-a-test", self.remove)(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, "ci-of-a-test", self.remove)(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)]) + # 2026-11-27T09:30:05Z, in seconds since the epoch. + self.now = lambda: 1795771805.0 + + 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-05Z-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:05Z deploy-release --cut\n2026-11-27T09:30:05Z pushed the tag v0.2.0\n2026-11-27T09:30:05Z merged pull request 3\n") + + def test_starts_a_later_runs_trace_beside_the_earlier_one(self): + folder = self.temp / "state" / "deploy-release" + first = trace.started(folder, "first", "deploy-release --cut", self.now) + second = trace.started(folder, "second", "deploy-release --cut-patch a..b", self.now) + self.assertEqual((first, second), (folder / "first.log", folder / "second.log")) + self.assertEqual(second.read_text(), "2026-11-27T09:30:05Z deploy-release --cut-patch a..b\n") + self.assertEqual(first.read_text(), "2026-11-27T09:30:05Z deploy-release --cut\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", "Nothing is tagged.", lambda text: f"{text!r} new\n")) + self.assertEqual(file.read_text(), "None new\n") + self.assertIsNone(cut.rewritten(file, "head CHANGELOG.md", "Nothing is tagged.", 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", "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: "), failed.reason) + self.assertEqual(failed.reason.count(str(file)), 1, failed.reason) + self.assertTrue(failed.reason.endswith(f"'{file}'. Nothing is tagged."), failed.reason) + + def test_a_file_that_is_not_utf_8_is_a_failure_naming_the_step_and_the_file(self): + file = self.temp / "CHANGELOG.md" + file.write_bytes(b"caf\xe9\n") + failed = cut.rewritten(file, "head CHANGELOG.md", "Nothing is tagged.", lambda text: "new\n") + self.assertIsInstance(failed, Failure) + self.assertTrue(failed.reason.startswith("could not head CHANGELOG.md: "), failed.reason) + self.assertTrue(failed.reason.endswith(f" ({file}). Nothing is tagged."), failed.reason) + self.assertEqual(failed.reason.count(str(file)), 1, failed.reason) + self.assertEqual(file.read_bytes(), b"caf\xe9\n") + + 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", "y", 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.""" @@ -689,14 +1045,17 @@ class PatchChangelog(unittest.TestCase): def test_moves_the_patchs_entries_from_unreleased_to_a_section_after_it(self): changelog = "# Changelog\n\n## Unreleased\n\n- Second.\n- Fixed.\n\n## 0.1.0\n\n- First.\n" - self.assertEqual(patch.moved_entries(changelog, ["- Fixed."], "0.1.1"), "# Changelog\n\n## Unreleased\n\n- Second.\n\n## 0.1.1\n\n- Fixed.\n\n## 0.1.0\n\n- First.\n") + self.assertEqual(patch.moved_entries(changelog, ["- Fixed."], "0.1.1", "origin/main"), "# Changelog\n\n## Unreleased\n\n- Second.\n\n## 0.1.1\n\n- Fixed.\n\n## 0.1.0\n\n- First.\n") def test_leaves_an_older_section_entry_that_reads_the_same(self): changelog = "# Changelog\n\n## Unreleased\n\n- Fixed.\n\n## 0.1.0\n\n- Fixed.\n" - self.assertEqual(patch.moved_entries(changelog, ["- Fixed."], "0.1.1"), "# Changelog\n\n## Unreleased\n\n## 0.1.1\n\n- Fixed.\n\n## 0.1.0\n\n- Fixed.\n") + self.assertEqual(patch.moved_entries(changelog, ["- Fixed."], "0.1.1", "origin/main"), "# Changelog\n\n## Unreleased\n\n## 0.1.1\n\n- Fixed.\n\n## 0.1.0\n\n- Fixed.\n") 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") + self.assertEqual(patch.moved_entries("# Changelog\n\n## Unreleased\n\n- Fixed.\n", ["- Fixed."], "0.1.1", "origin/main"), "# 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", "origin/main"), Failure("CHANGELOG.md on origin/main has no ## Unreleased heading to move the entries of 0.1.1 from")) if __name__ == "__main__": diff --git a/bin/deploy_release/trace.py b/bin/deploy_release/trace.py new file mode 100644 index 00000000..c164b8be --- /dev/null +++ b/bin/deploy_release/trace.py @@ -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 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.""" + state = env.get("XDG_STATE_HOME") or str(home / ".local" / "state") + return pathlib.Path(state) / "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, /.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 diff --git a/bin/do_epic/backend/jira.py b/bin/do_epic/backend/jira.py index 2a664a84..948a16e5 100644 --- a/bin/do_epic/backend/jira.py +++ b/bin/do_epic/backend/jira.py @@ -8,11 +8,10 @@ from atlassian.client import basic_auth, Http, jira_json, ToAdf, ToMarkdown from plan_store.jira_epic import BLOCKS, FILED_BY, scores as held_scores, PROPERTY from project_config.settings import DEFAULT_ISSUE_TYPE, Epic, Finish, JIRA_FINDING_TYPE, JIRA_FINISH_STATUS, JIRA_FINISH_TRANSITION, JIRA_REVIEW_TYPE from atlassian.jira import DONE, edit_issue, entry_of, finishing_transition, ISSUE_KEY, issue_type_refusal, issue_types_of, MAX_PAGES, move_refusal, PERHAPS_FILED, PERHAPS_MOVED, project_of, rank_refusal, searched, SHAPE, status_category, unshaped -from do_epic.backend.protocol import EpicIssue, no_blocker, no_child, no_parent, no_scores, no_words, unfit, unfit_label +from do_epic.backend.protocol import EpicIssue, no_blocker, no_child, no_parent, no_scores, no_words, REVIEW_LABEL, unfit, unfit_label from failure import Failure from do_epic.backend.jira_status import moved_by, moved_to from plan.todo_table import MOVES -from do_epic.repo_pick import REVIEW_LABEL from do_epic.backend.jira_start import Start, started FIELDS = ["summary", "description", "labels", "assignee", "status", "parent", "issuelinks"] diff --git a/bin/do_epic/backend/protocol.py b/bin/do_epic/backend/protocol.py index 367a006b..ba831e23 100644 --- a/bin/do_epic/backend/protocol.py +++ b/bin/do_epic/backend/protocol.py @@ -9,6 +9,8 @@ from plan.todo_table import Exempt, item_fields, ItemFields, Moves, MOVES from failure import Failure from plan_store.jira_epic import SET_SCORES +# Marks the issue that asks for a repo's release review, beside the label that names the repo (finish.py). Not `release-review`, which could pass for the team's own release process: three readers, seated as the human, as a chunk's worker and as one of the client's team, picked this one 3-0 from four. +REVIEW_LABEL = "do-epic-release-review" # What a tracker accepts as a label: Jira refuses a label holding white space. LABEL = re.compile(r"\S+") diff --git a/bin/do_epic/backend/test_jira.py b/bin/do_epic/backend/test_jira.py index 68840910..f46fed52 100644 --- a/bin/do_epic/backend/test_jira.py +++ b/bin/do_epic/backend/test_jira.py @@ -13,7 +13,7 @@ from do_epic.backend.contract import EpicStoreContract from failure import Failure from do_epic.backend.jira import JiraEpic from adf_codec.convert import Refused -from do_epic.repo_pick import REVIEW_LABEL +from do_epic.backend.protocol import REVIEW_LABEL from do_epic.backend.jira_start import Start SITE = "https://acme.atlassian.net" diff --git a/bin/do_epic/config.py b/bin/do_epic/config.py index bd680d45..6a83ae8b 100644 --- a/bin/do_epic/config.py +++ b/bin/do_epic/config.py @@ -34,8 +34,8 @@ import types from project_config.settings import anywhere, CONFIG, DEFAULT_ISSUE_TYPE, DO_EPIC, ENV_FILE, Finish, finish_faults, finish_of, JIRA_FINDING_TYPE, JIRA_FINISH, JIRA_REVIEW_TYPE, LANGUAGE, language_fault, lies_in, name_of, parsed, PROJECTS, SITE, type_fault from failure import Failure -from do_epic.backend.protocol import LABEL -from do_epic.repo_pick import LabelRepos, of_label, REPO_NAME, REVIEW_LABEL +from do_epic.backend.protocol import LABEL, REVIEW_LABEL +from do_epic.repo_pick import LabelRepos, of_label, REPO_NAME from text_files.markdown_text import listed from model_routing.ladder_file import read_ladder, SHIPPED from do_epic.split import SPLIT_LABEL diff --git a/bin/do_epic/findings.py b/bin/do_epic/findings.py index 7a87bf2a..cb37b3a8 100644 --- a/bin/do_epic/findings.py +++ b/bin/do_epic/findings.py @@ -7,8 +7,8 @@ import fcntl import pathlib import typing -from do_epic.repo_pick import CLAUDE_LABEL, HUMAN_LABEL, label_of, LabelRepos, of_label, REPO_PREFIX, REVIEW_LABEL, team_label -from do_epic.backend.protocol import EpicIssue, EpicStore +from do_epic.repo_pick import CLAUDE_LABEL, HUMAN_LABEL, label_of, LabelRepos, of_label, REPO_PREFIX, team_label +from do_epic.backend.protocol import EpicIssue, EpicStore, REVIEW_LABEL from do_epic.epic_record import EpicRecord from failure import Failure from text_files.markdown_text import listed diff --git a/bin/do_epic/finish.py b/bin/do_epic/finish.py index 5dd4416c..c4b74f9f 100644 --- a/bin/do_epic/finish.py +++ b/bin/do_epic/finish.py @@ -12,13 +12,14 @@ import pathlib import typing from do_epic.chunk_prompt import DRIVER -from do_epic.backend.protocol import EpicIssue, EpicStore +from do_epic.backend.protocol import EpicIssue, EpicStore, REVIEW_LABEL from failure import Failure from do_epic import findings from do_epic.split import finished -from do_epic.repo_pick import label_of, LabelRepos, recorded, Repo, REVIEW_LABEL +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}