|
| 1 | +"""Revert — undo a published contribution (issue #158). |
| 2 | +
|
| 3 | +``pdca revert <id>`` reads the bundle's recorded ``publish.json`` and undoes the |
| 4 | +contribution: |
| 5 | +
|
| 6 | +- the PR is **MERGED** → open a **revert PR** that reverse-applies the bundle's own |
| 7 | + ``patch.diff`` onto the base (``git apply --reverse``) — deterministic, no guessing the |
| 8 | + merge commit or the ``-m`` mainline — pushed as a fresh **draft** PR. |
| 9 | +- the PR is **OPEN** (never landed) → **withdraw** it: ``gh pr close --delete-branch``. |
| 10 | +- the PR is already **CLOSED** → nothing to do. |
| 11 | +
|
| 12 | +Records ``revert.json`` in the bundle. ``--dry-run`` prints the git/gh plan without |
| 13 | +mutating anything (it still reads the PR state). Fail-closed and loud, like publish/merge; |
| 14 | +STOP discipline holds — a revert PR opens as a draft for the human to merge. The mechanics |
| 15 | +are deterministic ``git``/``gh`` subprocesses (no model), reusing the publish helpers. |
| 16 | +""" |
| 17 | + |
| 18 | +from __future__ import annotations |
| 19 | + |
| 20 | +import datetime |
| 21 | +import json |
| 22 | +import shlex |
| 23 | +import subprocess |
| 24 | +import sys |
| 25 | +from pathlib import Path |
| 26 | + |
| 27 | +from . import publish |
| 28 | +from .config import Config |
| 29 | + |
| 30 | +REVERT_JSON = "revert.json" |
| 31 | + |
| 32 | + |
| 33 | +def revert(cfg: Config, issue_id: str, *, dry_run: bool = False, by: str = "", |
| 34 | + today: str | None = None) -> int: |
| 35 | + """Undo the bundle's published contribution; return a process code.""" |
| 36 | + d = cfg.bundle(issue_id) |
| 37 | + today = today or datetime.date.today().isoformat() |
| 38 | + rec = publish._publish_record(d) |
| 39 | + pr_url = rec.get("pr_url") if rec else None |
| 40 | + if not pr_url: |
| 41 | + print(f"revert: {d.name} has no recorded PR (nothing published to revert)", |
| 42 | + file=sys.stderr) |
| 43 | + return 1 |
| 44 | + pr_state = _pr_state(pr_url) |
| 45 | + if pr_state is None: |
| 46 | + print(f"revert: could not read PR state for {pr_url}; aborting", file=sys.stderr) |
| 47 | + return 1 |
| 48 | + if pr_state == "MERGED": |
| 49 | + return _revert_merged(cfg, d, issue_id, rec, pr_url, dry_run=dry_run, by=by, today=today) |
| 50 | + if pr_state == "OPEN": |
| 51 | + # ``mode: "stacked"`` (Onto branch, #54) means the harness appended a commit to a |
| 52 | + # PRE-EXISTING PR it did NOT create. Withdrawing it would `gh pr close |
| 53 | + # --delete-branch` that collaborator's whole PR branch — never do that. (The merged |
| 54 | + # path is still safe: it opens a *new* revert PR, leaving the original alone.) |
| 55 | + if rec.get("mode") == "stacked": |
| 56 | + print(f"revert: {d.name} was published as a commit onto an existing PR " |
| 57 | + f"({pr_url}, mode=stacked) the harness did not create — refusing to close " |
| 58 | + "it. Revert just that commit on the PR branch by hand.", file=sys.stderr) |
| 59 | + return 1 |
| 60 | + return _withdraw(cfg, d, pr_url, dry_run=dry_run, by=by, today=today) |
| 61 | + print(f"revert: {d.name}'s PR is {pr_state} — nothing to revert ({pr_url}).") |
| 62 | + return 0 |
| 63 | + |
| 64 | + |
| 65 | +def _pr_state(pr_url: str) -> str | None: |
| 66 | + """The recorded PR's state via ``gh pr view`` (``MERGED`` / ``OPEN`` / ``CLOSED``), or |
| 67 | + None on a gh failure (the caller aborts — never reverts blind).""" |
| 68 | + r = subprocess.run(["gh", "pr", "view", str(pr_url), "--json", "state"], |
| 69 | + capture_output=True, text=True) |
| 70 | + if r.returncode != 0: |
| 71 | + print(r.stderr, file=sys.stderr) |
| 72 | + return None |
| 73 | + try: |
| 74 | + return json.loads(r.stdout or "{}").get("state") |
| 75 | + except ValueError: |
| 76 | + return None |
| 77 | + |
| 78 | + |
| 79 | +def _commit_summary(d: Path, issue_id: str) -> str: |
| 80 | + """The contribution's commit subject (for the revert title), or a fallback.""" |
| 81 | + msg = d / publish.COMMIT_MSG |
| 82 | + if msg.is_file(): |
| 83 | + lines = msg.read_text(encoding="utf-8").splitlines() |
| 84 | + if lines and lines[0].strip(): |
| 85 | + return lines[0].strip() |
| 86 | + return f"contribution for {issue_id}" |
| 87 | + |
| 88 | + |
| 89 | +def _record(d: Path, rec: dict) -> None: |
| 90 | + (d / REVERT_JSON).write_text(json.dumps(rec, indent=2) + "\n", encoding="utf-8") |
| 91 | + |
| 92 | + |
| 93 | +def _revert_merged(cfg: Config, d: Path, issue_id: str, pub: dict, pr_url: str, *, |
| 94 | + dry_run: bool, by: str, today: str) -> int: |
| 95 | + """Open a draft revert PR that reverse-applies the bundle's patch.diff onto the base.""" |
| 96 | + patch = d / "patch.diff" |
| 97 | + if not patch.is_file() or not patch.read_text(encoding="utf-8").strip(): |
| 98 | + print(f"revert: {d.name} has no patch.diff to reverse (close/no-fix had nothing to " |
| 99 | + "land) — nothing to revert.", file=sys.stderr) |
| 100 | + return 1 |
| 101 | + repo_spec = pub.get("repo", "") |
| 102 | + base = pub.get("base", "") |
| 103 | + repo = publish._checkout_path(cfg, repo_spec) |
| 104 | + base_remote = cfg.base_remote |
| 105 | + rev_branch = f"revert/{issue_id}" |
| 106 | + summary = _commit_summary(d, issue_id) |
| 107 | + git = lambda *a: ["git", "-C", str(repo), *a] |
| 108 | + steps = [ |
| 109 | + git("fetch", base_remote), |
| 110 | + git("checkout", "-B", rev_branch, f"{base_remote}/{base}"), |
| 111 | + git("apply", "--reverse", str(patch.resolve())), |
| 112 | + git("add", "--all"), |
| 113 | + git("commit", "-s", "-m", |
| 114 | + f"Revert: {summary}\n\nReverts the change contributed for {issue_id} ({pr_url})."), |
| 115 | + git("push", "--force-with-lease", "-u", "origin", rev_branch), |
| 116 | + ] |
| 117 | + if dry_run: |
| 118 | + print(f"revert --dry-run — {d.name}: open a draft revert PR on {repo_spec} " |
| 119 | + f"({rev_branch} → {base}):") |
| 120 | + for c in steps: |
| 121 | + print(" " + " ".join(shlex.quote(x) for x in c)) |
| 122 | + print(f" gh pr create --draft --repo {repo_spec} --base {base} " |
| 123 | + f"--head <fork-owner>:{rev_branch} --title {shlex.quote('Revert: ' + summary)}") |
| 124 | + return 0 |
| 125 | + |
| 126 | + rc = publish._check_repo(repo, repo_spec, required_remotes={base_remote, "origin"}) |
| 127 | + if rc != 0: |
| 128 | + return rc |
| 129 | + orig = publish._current_ref(repo) |
| 130 | + stashed = publish._stash_worktree(repo) |
| 131 | + try: |
| 132 | + for c in steps: |
| 133 | + print("→ " + " ".join(c[3:])) |
| 134 | + if subprocess.run(c).returncode != 0: |
| 135 | + print(f"revert: step failed: {' '.join(c)}", file=sys.stderr) |
| 136 | + return 1 |
| 137 | + finally: |
| 138 | + publish._restore_worktree(repo, orig, stashed) |
| 139 | + |
| 140 | + head = f"{publish._fork_owner(repo) or repo_spec.split('/')[0]}:{rev_branch}" |
| 141 | + pr_cmd = ["gh", "pr", "create", "--draft", "--repo", repo_spec, "--base", base, |
| 142 | + "--head", head, "--title", f"Revert: {summary}", |
| 143 | + "--body", f"Reverts the contribution for {issue_id} ({pr_url}) by " |
| 144 | + f"reverse-applying the recorded patch onto `{base}`."] |
| 145 | + r = subprocess.run(pr_cmd, capture_output=True, text=True) |
| 146 | + if r.returncode != 0: |
| 147 | + print(r.stderr, file=sys.stderr) |
| 148 | + print("revert: branch pushed but `gh pr create` FAILED — open the revert PR by " |
| 149 | + "hand. This is NOT done.", file=sys.stderr) |
| 150 | + return 1 |
| 151 | + revert_pr = ((r.stdout or "").strip().splitlines() or [""])[-1] |
| 152 | + _record(d, {"action": "revert-pr", "reverts": pr_url, "branch": rev_branch, |
| 153 | + "revert_pr": revert_pr, "base": base, "repo": repo_spec, |
| 154 | + "by": by or cfg.author or "unknown", "date": today}) |
| 155 | + print(f"\nDraft revert PR opened on {repo_spec} ({rev_branch} → {base}).\n {revert_pr}") |
| 156 | + print(" STOP: review CI, then mark it ready / merge yourself — the human's step.") |
| 157 | + return 0 |
| 158 | + |
| 159 | + |
| 160 | +def _withdraw(cfg: Config, d: Path, pr_url: str, *, dry_run: bool, by: str, |
| 161 | + today: str) -> int: |
| 162 | + """Withdraw an unmerged contribution: close the PR and delete its branch.""" |
| 163 | + cmd = ["gh", "pr", "close", str(pr_url), "--delete-branch"] |
| 164 | + if dry_run: |
| 165 | + print(f"revert --dry-run — {d.name}: withdraw the unmerged PR: {' '.join(cmd)}") |
| 166 | + return 0 |
| 167 | + print(f"→ gh pr close {pr_url} --delete-branch") |
| 168 | + r = subprocess.run(cmd, capture_output=True, text=True) |
| 169 | + if r.returncode != 0: |
| 170 | + print(r.stderr, file=sys.stderr) |
| 171 | + print(f"revert: could not close {pr_url} — close it by hand.", file=sys.stderr) |
| 172 | + return 1 |
| 173 | + _record(d, {"action": "withdraw", "reverts": pr_url, |
| 174 | + "by": by or cfg.author or "unknown", "date": today}) |
| 175 | + print(f"Withdrew the unmerged PR {pr_url} (closed + branch deleted).") |
| 176 | + return 0 |
0 commit comments