"""Open the chunk's pull request as a draft, mark it ready, or merge it, with gh where origin is on GitHub and tea elsewhere; then clean up after it. usage: chunk-pr open [<body>] chunk-pr ready chunk-pr merge --gate-passed chunk-pr clean Run it in the chunk's worktree, on the chunk's branch. ready and merge act on the branch's open pull request only while its head is the commit checked out, so push before you run them. open pushes the branch, setting its upstream, and opens a draft pull request into origin's default branch. <title> is one line, as ~/.claude/CLAUDE.md → "Git, commits, and PRs" says, and <body> is the pull request's summary. Where the branch's pull request is open already, it opens no second one. On origin's default branch it refuses, pushing nothing. ready marks the pull request ready for review. On Gitea a draft is a pull request whose title starts with `WIP: `, so there it drops that prefix. merge merges the pull request, and only while its head is still the commit checked out, so a push after the gate is never merged. It takes the first method the repository allows of: a merge commit, fast-forward only, a rebase followed by a merge commit, a rebase, a squash. GitHub offers only the merge commit, the rebase and the squash. --gate-passed says the merge gate passed on that commit; without it, chunk-pr refuses. clean fetches origin and, once origin's default branch holds the commit checked out, removes the chunk's worktree and its branch, then fast-forwards the main checkout to origin's default branch. It leaves the main checkout as it was where that has uncommitted or untracked files or another branch checked out, and fails saying so: a dirty checkout is for its owner to look at. A worktree with uncommitted changes git keeps, branch and all. It prints what it did, exit 0, or why it failed, exit 1. """ import json import os import sys from failure import Failure from chunk_preflight.gathered import Forge from chunk_preflight.choices import forge_of from deploy_release.forge import gitea, open_pull, Run, runner USAGE = "usage: chunk-pr open <title> [<body>] | chunk-pr ready | chunk-pr merge --gate-passed | chunk-pr clean" # Each forge's merge methods in the order merge prefers them, as the repository setting that allows the method and the method's name in the forge's merge call. A merge commit and a fast-forward keep the branch's commits as they are; a rebase or a squash rewrites them. METHODS: dict[Forge, tuple[tuple[str, str], ...]] = { "gh": (("mergeCommitAllowed", "--merge"), ("rebaseMergeAllowed", "--rebase"), ("squashMergeAllowed", "--squash")), "tea": (("allow_merge_commits", "merge"), ("allow_fast_forward_only_merge", "fast-forward-only"), ("allow_rebase_explicit", "rebase-merge"), ("allow_rebase", "rebase"), ("allow_squash_merge", "squash")), } def main(argv: list[str]) -> int: if argv[:1] in (["-h"], ["--help"]): print(__doc__.strip()) return 0 done = step(argv, runner(os.getcwd())) if isinstance(done, Failure): print(f"chunk-pr: {done.reason}", file=sys.stderr) return 1 print(done) return 0 def step(argv: list[str], run: Run) -> str | Failure: """Run the step argv names: the line to print, or a Failure. A malformed argv runs nothing.""" match argv: case ["open", title, *body] if len(body) <= 1: if not title.strip() or "\n" in title: return Failure("give a title of one line") return opened(title, body[0] if body else "", run) case ["ready"]: return marked_ready(run) case ["merge", "--gate-passed"]: return merged(run) case ["merge"]: return Failure("merge only once the gate has passed, and say so with --gate-passed") case ["clean"]: return cleaned(run) return Failure(USAGE) def checkout(run: Run) -> tuple[Forge, str, str] | Failure: """The forge, the branch checked out and its head commit.""" answers = [run(["git", *args]) for args in (["remote", "get-url", "origin"], ["symbolic-ref", "--short", "HEAD"], ["rev-parse", "HEAD"])] failed = next((answer for answer in answers if isinstance(answer, Failure)), None) if failed is not None: return failed origin, branch, head = (str(answer).strip() for answer in answers) return forge_of(origin), branch, head def pull(run: Run) -> tuple[Forge, str, str] | Failure: """The forge, the number of the branch's open pull request at its head, and that head.""" found = checkout(run) if isinstance(found, Failure): return found forge, branch, head = found number = open_pull(forge, branch, head, run) if number is None: return Failure(f"no pull request from origin's {branch} is open at {head[:12]}; push the branch, or open one with chunk-pr open") return number if isinstance(number, Failure) else (forge, number, head) def opened(title: str, body: str, run: Run) -> str | Failure: found = checkout(run) if isinstance(found, Failure): return found forge, branch, head = found default = run(["git", "symbolic-ref", "--short", "refs/remotes/origin/HEAD"]) if isinstance(default, Failure): return Failure(f"origin records no default branch; set it with `git remote set-head origin --auto`: {default.reason}") base = default.strip().removeprefix("origin/") if branch == base: return Failure(f"{branch} is origin's default branch; open the pull request from the chunk's branch") pushed = run(["git", "push", "--quiet", "--set-upstream", "origin", branch]) if isinstance(pushed, Failure): return pushed number = open_pull(forge, branch, head, run) if isinstance(number, str): return f"Pull request #{number} is open already." if isinstance(number, Failure): return number command = ["gh", "pr", "create"] if forge == "gh" else ["tea", "pulls", "create"] created = run([*command, "--draft", "--head", branch, "--base", base, "--title", title, "--body" if forge == "gh" else "--description", body]) if isinstance(created, Failure): return created number = open_pull(forge, branch, head, run) if number is None: return Failure(f"{command[0]} created the pull request, but no pull request from origin's {branch} is listed open at {head[:12]}") return number if isinstance(number, Failure) else f"Opened draft pull request #{number}." def marked_ready(run: Run) -> str | Failure: found = pull(run) if isinstance(found, Failure): return found forge, number, _ = found ready = run(["gh", "pr", "ready", number] if forge == "gh" else ["tea", "pulls", "edit", number, "--ready"]) return ready if isinstance(ready, Failure) else f"Marked pull request #{number} ready." def merged(run: Run) -> str | Failure: found = pull(run) if isinstance(found, Failure): return found forge, number, head = found method = merge_method(forge, run) if isinstance(method, Failure): return method if forge == "gh": done = run(["gh", "pr", "merge", number, method, "--match-head-commit", head]) else: done = gitea(run, f"repos/{{owner}}/{{repo}}/pulls/{number}/merge", f"Do={method}", f"head_commit_id={head}") return done if isinstance(done, Failure) else f"Merged pull request #{number} ({method.removeprefix('--')})." def merge_method(forge: Forge, run: Run) -> str | Failure: """The first of METHODS[forge] that the repository's settings allow.""" if forge == "gh": viewed = run(["gh", "repo", "view", "--json", ",".join(setting for setting, _ in METHODS["gh"])]) try: settings = viewed if isinstance(viewed, Failure) else json.loads(viewed) except ValueError: return Failure(f"gh repo view printed no JSON: {str(viewed).strip()[:200]}") else: settings = gitea(run, "repos/{owner}/{repo}") if isinstance(settings, Failure): return settings allowed = next((method for setting, method in METHODS[forge] if isinstance(settings, dict) and settings.get(setting) is True), None) return allowed if allowed is not None else Failure(f"the repository allows none of the merge methods chunk-pr knows: {', '.join(method for _, method in METHODS[forge])}") def cleaned(run: Run) -> str | Failure: found = checkout(run) if isinstance(found, Failure): return found _, branch, head = found answers = [run(["git", *args]) for args in (["symbolic-ref", "--short", "refs/remotes/origin/HEAD"], ["worktree", "list", "--porcelain"], ["rev-parse", "--show-toplevel"])] failed = next((answer for answer in answers if isinstance(answer, Failure)), None) if failed is not None: return failed base, listed, worktree = (str(answer).strip() for answer in answers) # git lists the main checkout first. main = listed.splitlines()[0].removeprefix("worktree ") if worktree == main: return Failure(f"{main} is the main checkout; run clean in the chunk's worktree") fetched = run(["git", "fetch", "--quiet", "origin"]) if isinstance(fetched, Failure): return fetched if isinstance(run(["git", "merge-base", "--is-ancestor", head, base]), Failure): return Failure(f"{base} doesn't hold {head[:12]}: {branch} is not merged, so its worktree and branch stay") at_main = runner(main) left = kept_as_it_was(at_main, base.removeprefix("origin/")) if left is None: forwarded = at_main(["git", "merge", "--quiet", "--ff-only", base]) if isinstance(forwarded, Failure): return forwarded removed = at_main(["git", "worktree", "remove", worktree]) if isinstance(removed, Failure): return removed # Not -d: the check above already found the branch merged, and -d would compare it with the main checkout's HEAD or a stale upstream instead. deleted = at_main(["git", "branch", "--quiet", "-D", branch]) if isinstance(deleted, Failure): return deleted done = f"Removed worktree {worktree} and branch {branch}" if left is not None: return Failure(f"{done}, but left {main} as it was: {left}") return f"{done}, and fast-forwarded {main} to {base}." def kept_as_it_was(at_main: Run, default: str) -> str | None: """Why the main checkout must not move, or None where it may fast-forward.""" branch = at_main(["git", "symbolic-ref", "--quiet", "--short", "HEAD"]) if isinstance(branch, Failure) or branch.strip() != default: return f"it has {'no branch' if isinstance(branch, Failure) else branch.strip()} checked out, not {default}" status = at_main(["git", "status", "--porcelain"]) if isinstance(status, Failure): return status.reason return f"it has uncommitted or untracked files:\n{status.rstrip()}" if status.strip() else None