"""The human approval that `chunk-pr merge` waits for where the project's config sets `wait-for-approval`.""" import json import pathlib import time import typing from chunk_preflight.gathered import Forge from deploy_release.forge import Run from failure import Failure BIN = pathlib.Path(__file__).resolve().parents[1] # A human answers in hours, so merge polls once a minute. It gives up after 2 hours, the longest a background command may run: whoever asked for the merge runs it again once the pull request is approved. POLL_SECONDS = 60 WAIT_SECONDS = 2 * 60 * 60 def awaited(forge: Forge, run: Run) -> bool | Failure: """Whether merge waits for an approval: the project config's `wait-for-approval`. A config that cannot be read fails, so that no unreadable config merges without the approval it may require. Only GitHub reports approvals, so a Gitea project that sets it fails too.""" answer = run([str(BIN / "project-config"), "wait-for-approval"]) if isinstance(answer, Failure): return answer if answer.strip() not in ("true", "false"): return Failure(f"project-config wait-for-approval printed {answer.strip()[:80]!r}, not true or false") if answer.strip() == "true" and forge != "gh": return Failure("the project's config sets wait-for-approval, which chunk-pr can read on GitHub only; set it to false and approve this pull request by hand") return answer.strip() == "true" def approved(number: str, run: Run, sleep: typing.Callable[[float], None] = time.sleep) -> Failure | None: """None once GitHub reports pull request number approved, as its branch protection asks; a Failure where a reviewer requested changes, where the protection asks for no review, or where no approval came within WAIT_SECONDS.""" for waited in range(0, WAIT_SECONDS + 1, POLL_SECONDS): viewed = run(["gh", "pr", "view", number, "--json", "reviewDecision"]) try: decision = viewed if isinstance(viewed, Failure) else json.loads(viewed)["reviewDecision"] except (ValueError, KeyError, TypeError): return Failure(f"gh pr view printed no review decision: {str(viewed).strip()[:200]}") if isinstance(decision, Failure): return decision if decision == "APPROVED": return None if decision == "CHANGES_REQUESTED": return Failure(f"a reviewer requested changes on pull request {number}") if not decision: return Failure("wait-for-approval is set, but the branch protection requires no review, so GitHub reports no decision; require a review in the protection, or set wait-for-approval to false") if decision != "REVIEW_REQUIRED": return Failure(f"GitHub reports the review decision {decision!r} on pull request {number}, which chunk-pr doesn't know") if waited < WAIT_SECONDS: sleep(POLL_SECONDS) return Failure(f"pull request {number} wasn't approved within {WAIT_SECONDS // 3600} hours; run chunk-pr merge again once it is")