"""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 failure import Failure from chunk_preflight.gathered import Forge from deploy_release.forge import Run BIN = pathlib.Path(__file__).resolve().parents[1] # A human answers in hours, so merge polls once a minute and gives up after 90 minutes, which leaves room for the checks wait inside the 2 hours a background command may run, so that the give-up message prints. POLL_SECONDS = 60 WAIT_SECONDS = 90 * 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 merge never skips an approval the config may require. chunk-pr reads approvals on GitHub only, 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, but chunk-pr reads approvals on GitHub only, so it cannot merge this pull request; ask the human to merge it") 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; ask the human to require a review in the protection or to set wait-for-approval to false") if decision != "REVIEW_REQUIRED": return Failure(f"GitHub reports the review decision {decision!r} on pull request {number}, and chunk-pr doesn't know that decision") if waited < WAIT_SECONDS: sleep(POLL_SECONDS) return Failure(f"pull request {number} wasn't approved within {WAIT_SECONDS // 60} minutes; run chunk-pr merge again once it is")