From 306382e03d8d16fbf171871aa537e63e49c1d8ba Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Sat, 21 Nov 2026 09:12:56 +0000 Subject: [PATCH] feat(ci): merge update PRs automatically once CI deployed every changed role MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit entry-pr-green-update-merge.yml runs on a successful pull_request run of the PR pipeline for update/* and dependabot/* branches. cli.contributing.update.merge merges only when the updater App or Dependabot opened the PR from its own branch against the default branch, it carries the update label, every check run and status on its head is green, and the role-runtimes artifacts of that run list every role the PR changes. The gate reads with the read-only GITHUB_TOKEN; the App token is minted only after it passes and merges through the REST API pinned to the tested head SHA. entry-pr-change-dependabot-label.yml gives Dependabot PRs the same update plus level labels, and dependabot.yml adds the update label to every active ecosystem. Both workflows stay off unless CI_ENABLE_AUTO_UPDATES is true. ๐ŸŽฏ Fix: 82 % ๐Ÿ’ฅ Break: 3 % ๐Ÿ’ธ Tokens: โ€“ โฑ๏ธ Velocity: โ€“ ๐Ÿ›ก๏ธ Security: 100 % ๐Ÿ† Score: 80 ๐Ÿšฆ Gate: โ›” fix 82 % < 90 MEDUSA accepted false positives: RH005 cli/contributing/update/merge/__main__.py (standard CLI entry), WEB-PATH-002 cli/contributing/update/merge/github.py (zip read in memory with size caps, never extracted), B603 cli/contributing/update/merge/github.py (list-form gh subprocess, no shell). Created-with: https://s.veen.world/skills Co-Authored-By: Claude Opus 5.5 --- .github/dependabot.yml | 8 + .../entry-pr-change-dependabot-label.yml | 40 +++ .../workflows/entry-pr-green-update-merge.yml | 69 ++++++ cli/contributing/update/merge/__init__.py | 1 + cli/contributing/update/merge/__main__.py | 99 ++++++++ cli/contributing/update/merge/gate.py | 154 ++++++++++++ cli/contributing/update/merge/github.py | 137 ++++++++++ docs/contributing/artefact/git/pipeline.md | 2 + .../tools/github/actions/configuration.md | 15 +- .../tools/github/actions/secrets.md | 6 +- .../tools/github/actions/workflows.md | 2 + .../cli/contributing/update/merge/__init__.py | 0 .../contributing/update/merge/test_gate.py | 130 ++++++++++ .../contributing/update/merge/test_github.py | 118 +++++++++ .../contributing/update/merge/test_main.py | 233 ++++++++++++++++++ 15 files changed, 1011 insertions(+), 3 deletions(-) create mode 100644 .github/workflows/entry-pr-change-dependabot-label.yml create mode 100644 .github/workflows/entry-pr-green-update-merge.yml create mode 100644 cli/contributing/update/merge/__init__.py create mode 100644 cli/contributing/update/merge/__main__.py create mode 100644 cli/contributing/update/merge/gate.py create mode 100644 cli/contributing/update/merge/github.py create mode 100644 tests/unit/python/cli/contributing/update/merge/__init__.py create mode 100644 tests/unit/python/cli/contributing/update/merge/test_gate.py create mode 100644 tests/unit/python/cli/contributing/update/merge/test_github.py create mode 100644 tests/unit/python/cli/contributing/update/merge/test_main.py diff --git a/.github/dependabot.yml b/.github/dependabot.yml index f4e2da25b6..b51f38680d 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -15,6 +15,7 @@ updates: rebase-strategy: "auto" labels: - "dependencies" + - "update" - "python" # ------------------------------------------------------------ @@ -29,6 +30,7 @@ updates: time: "00:00" labels: - "dependencies" + - "update" - "ci" # ------------------------------------------------------------ @@ -43,6 +45,7 @@ updates: time: "00:00" labels: - "dependencies" + - "update" - "docker" # ------------------------------------------------------------ @@ -57,6 +60,7 @@ updates: time: "00:00" labels: - "dependencies" + - "update" - "docker" # ------------------------------------------------------------ @@ -75,6 +79,7 @@ updates: time: "00:00" labels: - "dependencies" + - "update" - "ci" # ------------------------------------------------------------ @@ -90,6 +95,7 @@ updates: time: "00:00" labels: - "dependencies" + - "update" - "javascript" # ------------------------------------------------------------ @@ -104,6 +110,7 @@ updates: time: "00:00" labels: - "dependencies" + - "update" - "php" # ------------------------------------------------------------ @@ -188,6 +195,7 @@ updates: time: "00:00" labels: - "dependencies" + - "update" - "ruby" # cargo: no Cargo.toml found diff --git a/.github/workflows/entry-pr-change-dependabot-label.yml b/.github/workflows/entry-pr-change-dependabot-label.yml new file mode 100644 index 0000000000..8acf9116bc --- /dev/null +++ b/.github/workflows/entry-pr-change-dependabot-label.yml @@ -0,0 +1,40 @@ +name: "๐Ÿ”„ Dependabot: Label update level" + +on: + pull_request_target: + types: [opened, reopened, synchronize] + +permissions: {} + +jobs: + label: + name: ๐Ÿท๏ธ Label the Dependabot PR + if: github.event.pull_request.user.login == 'dependabot[bot]' && vars.CI_ENABLE_AUTO_UPDATES == 'true' + runs-on: ubuntu-26.04 + timeout-minutes: 10 + permissions: + contents: read + pull-requests: write + steps: + - name: ๐Ÿ”Ž Read Dependabot metadata + id: metadata + uses: dependabot/fetch-metadata@25dd0e34f4fe68f24cc83900b1fe3fe149efef98 # v3.1.0 + + - name: โฌ‡๏ธ Checkout the base branch + uses: actions/checkout@v7.0.0 + with: + ref: ${{ github.event.repository.default_branch }} + persist-credentials: false + + - name: ๐Ÿ”ง Set up Python + uses: actions/setup-python@v6 + with: + python-version: "3.12" + + - name: ๐Ÿท๏ธ Label update and semver level + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + REPOSITORY: ${{ github.repository }} + PR_NUMBER: ${{ github.event.pull_request.number }} + UPDATE_TYPE: ${{ steps.metadata.outputs.update-type }} + run: python3 -m cli.contributing.update.label --repo "$REPOSITORY" --pr "$PR_NUMBER" --update-type "$UPDATE_TYPE" diff --git a/.github/workflows/entry-pr-green-update-merge.yml b/.github/workflows/entry-pr-green-update-merge.yml new file mode 100644 index 0000000000..9091ebb92b --- /dev/null +++ b/.github/workflows/entry-pr-green-update-merge.yml @@ -0,0 +1,69 @@ +name: "๐Ÿ”„ Update: Merge proven PRs" +run-name: "๐Ÿ”„ Merge check for ${{ github.event.workflow_run.head_branch }}" + +on: + workflow_run: + workflows: ["๐Ÿ”€ Pull Request"] + types: [completed] + +permissions: {} + +jobs: + merge: + name: ๐Ÿ”€ Merge a proven update PR + if: >- + vars.CI_ENABLE_AUTO_UPDATES == 'true' + && github.event.workflow_run.event == 'pull_request' + && github.event.workflow_run.conclusion == 'success' + && (startsWith(github.event.workflow_run.head_branch, 'update/') + || startsWith(github.event.workflow_run.head_branch, 'dependabot/')) + runs-on: ubuntu-26.04 + timeout-minutes: 15 + permissions: + actions: read + checks: read + contents: read + pull-requests: read + statuses: read + steps: + - name: โฌ‡๏ธ Checkout + uses: actions/checkout@v7.0.0 + with: + ref: ${{ github.event.repository.default_branch }} + persist-credentials: false + + - name: ๐Ÿ”ง Set up Python + uses: actions/setup-python@v6 + with: + python-version: "3.12" + + - name: ๐Ÿ”Ž Check the merge gate + id: gate + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + REPOSITORY: ${{ github.repository }} + HEAD_SHA: ${{ github.event.workflow_run.head_sha }} + RUN_ID: ${{ github.event.workflow_run.id }} + OWN_RUN_ID: ${{ github.run_id }} + BASE_BRANCH: ${{ github.event.repository.default_branch }} + run: >- + python3 -m cli.contributing.update.merge + --repo "$REPOSITORY" --sha "$HEAD_SHA" --run-id "$RUN_ID" + --own-run-id "$OWN_RUN_ID" --base "$BASE_BRANCH" --output "$GITHUB_OUTPUT" + + - name: โš™๏ธ Generate app token + if: steps.gate.outputs.merge == 'true' + id: app-token + uses: actions/create-github-app-token@v3 + with: + client-id: ${{ secrets.BOT_APP_CLIENT_ID }} + private-key: ${{ secrets.BOT_APP_PRIVATE_KEY }} + + - name: ๐Ÿ”€ Merge the update PR at its tested head + if: steps.gate.outputs.merge == 'true' + env: + GH_TOKEN: ${{ steps.app-token.outputs.token }} + REPOSITORY: ${{ github.repository }} + PR_NUMBER: ${{ steps.gate.outputs.pr }} + HEAD_SHA: ${{ steps.gate.outputs.sha }} + run: gh api --method PUT "repos/${REPOSITORY}/pulls/${PR_NUMBER}/merge" -f merge_method=merge -f sha="${HEAD_SHA}" diff --git a/cli/contributing/update/merge/__init__.py b/cli/contributing/update/merge/__init__.py new file mode 100644 index 0000000000..cad4397f40 --- /dev/null +++ b/cli/contributing/update/merge/__init__.py @@ -0,0 +1 @@ +"""Merge gate of update pull requests: green checks plus a deploy of every changed role.""" diff --git a/cli/contributing/update/merge/__main__.py b/cli/contributing/update/merge/__main__.py new file mode 100644 index 0000000000..3733277479 --- /dev/null +++ b/cli/contributing/update/merge/__main__.py @@ -0,0 +1,99 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import re +from pathlib import Path +from typing import TYPE_CHECKING, Any + +from . import gate, github + +if TYPE_CHECKING: + from collections.abc import Sequence + + from .github import Gh + +_SHA = re.compile(r"[0-9a-f]{40}") + + +def evaluate( + gh: Gh, repo: str, sha: str, run_id: int, own_run_id: int, base: str +) -> tuple[dict[str, Any] | None, list[str]]: + """Judge the update pull request whose CI run *run_id* went green on *sha*. + + Args: + gh: runs ``gh`` with the given arguments and returns its stdout. + repo: ``owner/name``. + sha: the head commit the run tested. + run_id: the green ``๐Ÿ”€ Pull Request`` run of that commit. + own_run_id: the run deciding the merge. + base: the branch an update pull request must target. + + Returns: + the pull request, ``None`` unless exactly one open pull request has + that head, and the reasons refusing the merge, empty when it may + merge. The stages run in order and stop at the first that refuses: + pull request, checks, deployed roles. + """ + prs = github.open_pull_requests(gh, repo, sha) + if len(prs) != 1: + return None, [f"{len(prs)} open pull requests have head {sha}, not one"] + pr = prs[0] + refusals = gate.pull_request_refusals(pr, repo, base) + if refusals: + return pr, refusals + refusals = gate.check_refusals( + github.check_runs(gh, repo, sha), github.statuses(gh, repo, sha), own_run_id + ) + if refusals: + return pr, refusals + changed = gate.changed_roles(github.changed_paths(gh, repo, pr["number"])) + csv_texts = github.role_runtime_csvs(gh, repo, run_id) if changed else [] + return pr, gate.role_refusals(changed, csv_texts) + + +def main(argv: Sequence[str] | None = None) -> int: + parser = argparse.ArgumentParser( + description=( + "Decide whether an update pull request merges itself: a bot opened " + "it, it carries the update label, every check on its head is green " + "and CI deployed every role it changes." + ) + ) + parser.add_argument("--repo", required=True, help="owner/name") + parser.add_argument("--sha", required=True, help="Head commit the CI run tested") + parser.add_argument("--run-id", required=True, type=int, help="Green CI run id") + parser.add_argument( + "--own-run-id", required=True, type=int, help="Run id deciding the merge" + ) + parser.add_argument("--base", required=True, help="Branch the PR must target") + parser.add_argument( + "--output", + required=True, + type=Path, + help="File the merge, pr and sha step outputs are appended to", + ) + args = parser.parse_args(argv) + if not _SHA.fullmatch(args.sha): + parser.error(f"--sha is no full commit SHA: {args.sha!r}") + + pr, refusals = evaluate( + github.run_gh, args.repo, args.sha, args.run_id, args.own_run_id, args.base + ) + merge = pr is not None and not refusals + label = f"#{pr['number']}" if pr is not None else args.sha + if merge: + print(f"{label} merges: checks green, every changed role deployed.") + else: + print(f"{label} stays open for a manual merge:") + for reason in refusals: + print(f"- {reason}") + with args.output.open("a", encoding="utf-8") as handle: + handle.write(f"merge={'true' if merge else 'false'}\n") + if merge: + handle.write(f"pr={pr['number']}\nsha={args.sha}\n") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/cli/contributing/update/merge/gate.py b/cli/contributing/update/merge/gate.py new file mode 100644 index 0000000000..7bc0051116 --- /dev/null +++ b/cli/contributing/update/merge/gate.py @@ -0,0 +1,154 @@ +"""Decide whether an update pull request has earned an automatic merge. + +Each check returns the reasons that refuse the merge; an empty list passes it. +""" + +from __future__ import annotations + +import csv +import io +import re +from typing import TYPE_CHECKING, Any + +from cli.contributing.update.label import UPDATE + +if TYPE_CHECKING: + from collections.abc import Iterable, Mapping + +BOT_BRANCH_PREFIXES = { + "infinito-nexus-updater[bot]": "update/", + "dependabot[bot]": "dependabot/", +} +GREEN_CONCLUSIONS = frozenset({"success", "skipped", "neutral"}) +ROLE_COLUMN = "role" +_ROLE_PATH = re.compile(r"^roles/(?P[^/]+)/") + + +def pull_request_refusals(pr: Mapping[str, Any], repo: str, base: str) -> list[str]: + """Why *pr* is no update pull request a bot may merge. + + Args: + pr: the pull request as the REST API returns it. + repo: ``owner/name`` the head branch must live in. + base: the branch the pull request must target. + + Returns: + one line per unmet condition: an author outside the update bots, a + head branch outside that bot's prefix or repository, a draft, another + base branch, a missing ``update`` label. + """ + refusals: list[str] = [] + author = pr["user"]["login"] + head = pr["head"]["ref"] + prefix = BOT_BRANCH_PREFIXES.get(author) + if prefix is None: + refusals.append(f"author {author} is no update bot") + elif not head.startswith(prefix): + refusals.append(f"branch {head} lacks the {prefix} prefix of {author}") + head_repo = pr["head"]["repo"] + if head_repo is None or head_repo["full_name"] != repo: + refusals.append(f"head branch {head} lives outside {repo}") + if pr["draft"]: + refusals.append("pull request is a draft") + if pr["base"]["ref"] != base: + refusals.append(f"base branch is {pr['base']['ref']}, not {base}") + if UPDATE.name not in {label["name"] for label in pr["labels"]}: + refusals.append(f"label {UPDATE.name} is missing") + return refusals + + +def check_refusals( + check_runs: Iterable[Mapping[str, Any]], + statuses: Iterable[Mapping[str, Any]], + own_run_id: int, +) -> list[str]: + """Why the checks on the head commit are not all green. + + Args: + check_runs: the commit's latest check runs, each with ``name``, + ``status``, ``conclusion`` and ``details_url``. + statuses: the commit's latest status per context, each with + ``context`` and ``state``. + own_run_id: the run deciding the merge; its own check runs are still + in progress and do not count. + + Returns: + one line per check run that has not completed as success, skipped or + neutral, one per status that is not success, and one when no check + run is left to judge. + """ + own = f"/actions/runs/{own_run_id}/" + refusals: list[str] = [] + judged = 0 + for run in check_runs: + if own in (run["details_url"] or ""): + continue + judged += 1 + if run["status"] != "completed": + refusals.append(f"check {run['name']} is {run['status']}") + elif run["conclusion"] not in GREEN_CONCLUSIONS: + refusals.append(f"check {run['name']} concluded {run['conclusion']}") + if not judged: + refusals.append("no check run on the head commit") + refusals.extend( + f"status {status['context']} is {status['state']}" + for status in statuses + if status["state"] != "success" + ) + return refusals + + +def changed_roles(paths: Iterable[str]) -> set[str]: + """The roles whose files *paths* touch. + + Args: + paths: repository-relative paths, old names of renamed files included. + + Returns: + ```` of every ``roles//...`` path. + """ + return {match["role"] for path in paths if (match := _ROLE_PATH.match(path))} + + +def deployed_roles(csv_texts: Iterable[str]) -> set[str]: + """The roles the deploy rows ran, read from ``role-runtimes-*`` CSVs. + + The CSVs come out of a pull request's CI run, so they are parsed as data + and their values only ever compared, never executed or used as paths. + + Args: + csv_texts: the text of each CSV ``cli.meta.ci.roles.runtime`` wrote. + + Returns: + every non-empty value of the ``role`` column, dependencies included. + """ + roles: set[str] = set() + for text in csv_texts: + for row in csv.DictReader(io.StringIO(text)): + role = (row.get(ROLE_COLUMN) or "").strip() + if role: + roles.add(role) + return roles + + +def role_refusals(changed: set[str], csv_texts: list[str]) -> list[str]: + """Why the deploy rows do not prove every changed role. + + Args: + changed: the roles the pull request changes. + csv_texts: the ``role-runtimes-*`` CSVs of the pull request's CI run. + + Returns: + nothing when no role changed; one line when no CSV was uploaded, + since an upload that found no file is silent; otherwise one line per + changed role no deploy row ran. + """ + if not changed: + return [] + if not csv_texts: + return [f"no role-runtimes artifact proves {', '.join(sorted(changed))}"] + deployed = deployed_roles(csv_texts) + return [ + f"role {role} changed, but no deploy row ran it" + for role in sorted(changed - deployed) + ] diff --git a/cli/contributing/update/merge/github.py b/cli/contributing/update/merge/github.py new file mode 100644 index 0000000000..b8fba0b6b2 --- /dev/null +++ b/cli/contributing/update/merge/github.py @@ -0,0 +1,137 @@ +"""Read what the merge gate judges from the GitHub REST API through ``gh``.""" + +from __future__ import annotations + +import io +import json +import subprocess +import zipfile +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from collections.abc import Callable, Sequence + + Gh = Callable[[Sequence[str]], bytes] + +GH_TIMEOUT_SECONDS = 120 +ROLE_RUNTIMES_PREFIX = "role-runtimes-" +MAX_ARTIFACT_BYTES = 16 * 1024 * 1024 +MAX_CSV_BYTES = 4 * 1024 * 1024 + + +def run_gh(args: Sequence[str]) -> bytes: + return subprocess.run( + ["gh", *args], + capture_output=True, + check=True, + timeout=GH_TIMEOUT_SECONDS, + ).stdout + + +def items(gh: Gh, path: str, jq: str) -> list[dict[str, Any]]: + """Every object a paginated REST list yields through *jq*. + + Args: + gh: runs ``gh`` with the given arguments and returns its stdout. + path: the REST path, query string included. + jq: a filter emitting one JSON object per item. + + Returns: + the objects, across all pages. + """ + out = gh(["api", "--paginate", path, "--jq", jq]).decode("utf-8") + return [json.loads(line) for line in out.splitlines() if line.strip()] + + +def open_pull_requests(gh: Gh, repo: str, sha: str) -> list[dict[str, Any]]: + """The open pull requests whose head commit is *sha*.""" + return [ + pr + for pr in items(gh, f"repos/{repo}/commits/{sha}/pulls?per_page=100", ".[]") + if pr["state"] == "open" and pr["head"]["sha"] == sha + ] + + +def check_runs(gh: Gh, repo: str, sha: str) -> list[dict[str, Any]]: + """The latest check run per name on *sha*.""" + return items( + gh, + f"repos/{repo}/commits/{sha}/check-runs?filter=latest&per_page=100", + ".check_runs[] | {name, status, conclusion, details_url}", + ) + + +def statuses(gh: Gh, repo: str, sha: str) -> list[dict[str, Any]]: + """The latest commit status per context on *sha*.""" + return items( + gh, + f"repos/{repo}/commits/{sha}/status?per_page=100", + ".statuses[] | {context, state}", + ) + + +def changed_paths(gh: Gh, repo: str, number: int) -> list[str]: + """Every path pull request *number* touches, old names of renamed files included.""" + paths: list[str] = [] + for entry in items( + gh, + f"repos/{repo}/pulls/{number}/files?per_page=100", + ".[] | {filename, previous_filename}", + ): + paths.append(entry["filename"]) + if entry["previous_filename"]: + paths.append(entry["previous_filename"]) + return paths + + +def csv_members(blob: bytes) -> list[str]: + """The CSV files inside an artifact zip, read in memory. + + The zip is never extracted to disk, so its member names cannot reach a + path, and a member larger than ``MAX_CSV_BYTES`` is left out. + + Args: + blob: the artifact zip as the REST API serves it. + + Returns: + the text of each ``*.csv`` member. + """ + texts: list[str] = [] + with zipfile.ZipFile(io.BytesIO(blob)) as archive: + for member in archive.infolist(): + if member.is_dir() or not member.filename.endswith(".csv"): + continue + if member.file_size > MAX_CSV_BYTES: + continue + with archive.open(member) as handle: + data = handle.read(MAX_CSV_BYTES + 1) + if len(data) <= MAX_CSV_BYTES: + texts.append(data.decode("utf-8", errors="replace")) + return texts + + +def role_runtime_csvs(gh: Gh, repo: str, run_id: int) -> list[str]: + """The ``role-runtimes-*`` CSVs workflow run *run_id* uploaded. + + Args: + gh: runs ``gh`` with the given arguments and returns its stdout. + repo: ``owner/name``. + run_id: the pull request run whose deploy rows uploaded them. + + Returns: + the text of every CSV in every unexpired ``role-runtimes-*`` artifact + of at most ``MAX_ARTIFACT_BYTES``. + """ + texts: list[str] = [] + for artifact in items( + gh, + f"repos/{repo}/actions/runs/{run_id}/artifacts?per_page=100", + ".artifacts[] | {id, name, expired, size_in_bytes}", + ): + if not artifact["name"].startswith(ROLE_RUNTIMES_PREFIX): + continue + if artifact["expired"] or artifact["size_in_bytes"] > MAX_ARTIFACT_BYTES: + continue + blob = gh(["api", f"repos/{repo}/actions/artifacts/{artifact['id']}/zip"]) + texts.extend(csv_members(blob)) + return texts diff --git a/docs/contributing/artefact/git/pipeline.md b/docs/contributing/artefact/git/pipeline.md index 1bbe1b25a9..865aebd255 100644 --- a/docs/contributing/artefact/git/pipeline.md +++ b/docs/contributing/artefact/git/pipeline.md @@ -127,6 +127,8 @@ The `test-workspace` stage runs the workspace workflow listed in the `Infrastruc The final `done` job aggregates all deploy, install, and development gates. CI is considered green only when this job succeeds. +A green `done` does not prove a deploy, since a skipped chunk passes it too. For an update PR the green run therefore hands over to [entry-pr-green-update-merge.yml](../../../../.github/workflows/entry-pr-green-update-merge.yml), which merges only when the run's `role-runtimes-*` artifacts list every role the PR changes; see the automatic merge section of [configuration.md](../../tools/github/actions/configuration.md). + ## Concurrency ๐Ÿ”€ - PR pipelines use `cancel-in-progress: true` so only the newest run per PR and event type is active. The group does not always reap a long orchestrator sweep, which then leaves the newer run parked on `pending`; [entry-cancel-superseded.yml](../../../../.github/workflows/entry-cancel-superseded.yml) cancels those leftovers through the API, see [cancel/README.md](../../../../scripts/github/cancel/README.md). diff --git a/docs/contributing/tools/github/actions/configuration.md b/docs/contributing/tools/github/actions/configuration.md index 18fd9633bd..59cf0068ac 100644 --- a/docs/contributing/tools/github/actions/configuration.md +++ b/docs/contributing/tools/github/actions/configuration.md @@ -10,7 +10,7 @@ Repository variables are set under **Settings โ†’ Secrets and variables โ†’ Acti |---|---|---|---| | `CI_SYNC_MAIN_SOURCE_REPOSITORY` | [entry-push-latest.yml](../../../../../.github/workflows/entry-push-latest.yml) | Syncs `main` from `infinito-nexus/core` before CI scope discovery | `/` to use another source, or `false`, empty, or the current repository to skip | | `CI_RUN_ON_MAIN` | [entry-push-latest.yml](../../../../../.github/workflows/entry-push-latest.yml) | Pushes to `main` skip CI | `true` to run CI on `main` pushes too | -| `CI_ENABLE_AUTO_UPDATES` | [cron-update.yml](../../../../../.github/workflows/cron-update.yml), [entry-pr-open-dependabot-close.yml](../../../../../.github/workflows/entry-pr-open-dependabot-close.yml) | Update jobs skipped; Dependabot PRs auto-closed | `true` to allow update PRs (workflow-driven and Dependabot) | +| `CI_ENABLE_AUTO_UPDATES` | [cron-update.yml](../../../../../.github/workflows/cron-update.yml), [entry-pr-open-dependabot-close.yml](../../../../../.github/workflows/entry-pr-open-dependabot-close.yml), [entry-pr-change-dependabot-label.yml](../../../../../.github/workflows/entry-pr-change-dependabot-label.yml), [entry-pr-green-update-merge.yml](../../../../../.github/workflows/entry-pr-green-update-merge.yml) | Update jobs skipped; Dependabot PRs auto-closed; no update PR is labelled or merged automatically | `true` to allow update PRs (workflow-driven and Dependabot) and their automatic merge | | `CI_ENABLE_AUTO_TRANSLATIONS` | [entry-pr-translate.yml](../../../../../.github/workflows/entry-pr-translate.yml) | Pull requests against `main` open no translation PRs | `true` to machine-translate the entries a PR leaves empty or fuzzy, one PR per language | | `PLAYWRIGHT_KEEP_ALL` | [call-test-deploy.yml](../../../../../.github/workflows/call-test-deploy.yml) | Playwright keeps trace, screenshot and video only when a test fails | `true` to keep them for every test (passing runs included); the workflow forwards it as `INFINITO_PLAYWRIGHT_KEEP` | | `API_OPENAI_KEY` | [call-test-deploy.yml](../../../../../.github/workflows/call-test-deploy.yml) | The gateway publishes no `openai/*` model, and the CLI test asserts their absence | An OpenAI key, to deploy and test the route | @@ -160,6 +160,19 @@ Dependabot cannot read repository variables itself, so [entry-pr-open-dependabot | `true` | Run โœ“ | Stay open โœ“ | | any other value | Skipped โœ“ | Auto-closed on open โœ“ | +The same guard sits on [entry-pr-change-dependabot-label.yml](../../../../../.github/workflows/entry-pr-change-dependabot-label.yml), which labels Dependabot PRs `update` plus `major`, `minor` or `patch`, and on [entry-pr-green-update-merge.yml](../../../../../.github/workflows/entry-pr-green-update-merge.yml), which merges an update PR once CI proved it. With the variable unset, neither labels nor merges anything. + +### Automatic merge ๐Ÿ”€ + +An update PR merges itself only when all of these hold; otherwise the job prints the failing condition and the PR waits for a manual merge: + +1. Its `๐Ÿ”€ Pull Request` run of the `pull_request` event concluded `success`. +2. `infinito-nexus-updater[bot]` opened it from `update/*`, or `dependabot[bot]` from `dependabot/*`, in this repository, against the default branch, not as a draft, and it carries the `update` label. +3. Every latest check run on its head commit completed as `success`, `skipped` or `neutral`, and every commit status is `success`. A check still running counts as not green; no later run retries the merge. +4. Every role under `roles//` the PR changes appears in the `role` column of a `role-runtimes-*` artifact of that run. A PR that changes no role needs no artifact; a missing artifact proves nothing. + +The merge goes through `PUT /repos/{owner}/{repo}/pulls/{number}/merge` with `merge_method=merge` and the tested head `sha`, so a commit pushed after the run makes it fail instead of merging untested code. `gh pr merge` is not used because it refuses a PR the ruleset still blocks before the server can apply the App's bypass. The App MUST be a bypass actor of the `Main` ruleset in `pull_request` mode; without that the merge step fails and the PR stays open. + ## `INFINITO_PLAYWRIGHT_KEEP` ๐ŸŽฌ Controls whether Playwright keeps trace, screenshot, and video for every test or only for failing tests in the deploy-test workflow ([call-test-deploy.yml](../../../../../.github/workflows/call-test-deploy.yml)). diff --git a/docs/contributing/tools/github/actions/secrets.md b/docs/contributing/tools/github/actions/secrets.md index 25a0d0398a..816df5a001 100644 --- a/docs/contributing/tools/github/actions/secrets.md +++ b/docs/contributing/tools/github/actions/secrets.md @@ -8,8 +8,8 @@ Repository secrets MUST be set under **Settings โ†’ Secrets and variables โ†’ Ac | Secret | Workflow | Purpose | Required when | |---|---|---|---| -| `BOT_APP_CLIENT_ID` | [cron-update.yml](../../../../../.github/workflows/cron-update.yml) | GitHub App Client ID (OAuth-style `Ivโ€ฆ` identifier shown on the App's General page) used to mint a short-lived installation token for the update PR. | `CI_ENABLE_AUTO_UPDATES == 'true'` | -| `BOT_APP_PRIVATE_KEY` | [cron-update.yml](../../../../../.github/workflows/cron-update.yml) | PEM-encoded private key of the same GitHub App. Used to sign the JWT that exchanges for the installation token. | `CI_ENABLE_AUTO_UPDATES == 'true'` | +| `BOT_APP_CLIENT_ID` | [cron-update.yml](../../../../../.github/workflows/cron-update.yml), [entry-pr-green-update-merge.yml](../../../../../.github/workflows/entry-pr-green-update-merge.yml) | GitHub App Client ID (OAuth-style `Ivโ€ฆ` identifier shown on the App's General page) used to mint a short-lived installation token for the update PR and for its automatic merge. | `CI_ENABLE_AUTO_UPDATES == 'true'` | +| `BOT_APP_PRIVATE_KEY` | [cron-update.yml](../../../../../.github/workflows/cron-update.yml), [entry-pr-green-update-merge.yml](../../../../../.github/workflows/entry-pr-green-update-merge.yml) | PEM-encoded private key of the same GitHub App. Used to sign the JWT that exchanges for the installation token. | `CI_ENABLE_AUTO_UPDATES == 'true'` | | `API_OPENAI_KEY` | [call-test-deploy.yml](../../../../../.github/workflows/call-test-deploy.yml) | Publishes the `openai/*` models on the LiteLLM gateway and lets the CLI test exercise the route. | Never. Unset leaves the route unpublished. | | `API_ANTHROPIC_KEY` | [call-test-deploy.yml](../../../../../.github/workflows/call-test-deploy.yml) | Publishes the `anthropic/*` models. | Never. | | `API_OPENROUTER_KEY` | [call-test-deploy.yml](../../../../../.github/workflows/call-test-deploy.yml) | Publishes `openrouter/auto`. | Never. | @@ -99,6 +99,8 @@ A classic personal access token MAY be used as a fallback for unrelated automati Each PR-opening job in [cron-update.yml](../../../../../.github/workflows/cron-update.yml) runs an `actions/create-github-app-token@v2` step gated on `steps.diff.outputs.changed == 'true'`, then forwards the minted token as `GH_TOKEN` and the resolved `APP_SLUG` to the subsequent PR step. The job's `permissions:` block keeps the workflow-provided `GITHUB_TOKEN` read-only; write access is provided exclusively by the App token, scoped to the App's repository permissions. +[entry-pr-green-update-merge.yml](../../../../../.github/workflows/entry-pr-green-update-merge.yml) mints the App token only after its merge gate passed, and uses it for the merge call alone; the gate itself reads with the read-only `GITHUB_TOKEN`. Merging needs the App's `Contents` and `Pull requests` write permissions plus a bypass of the `Main` ruleset; a PR that changes `.github/workflows/` additionally needs `Workflows`: **Read and write**, or its merge fails and it stays open. + ### Commit identity propagation ๐Ÿชช [pr.sh](../../../../../scripts/github/update/open/pr.sh) reads `APP_SLUG` from the environment and resolves the App's bot user via `gh api /users/[bot]`. The resolved login and numeric user ID are written into `git config user.name` and `git config user.email` in the `+[bot]@users.noreply.github.com` form that GitHub accepts for verified commits. When `APP_SLUG` is unset, the script falls back to the `github-actions[bot]` identity. That branch is reached only when the script is invoked outside the workflow, for example a local smoke test where the caller has set `GH_TOKEN` to something other than an App token. diff --git a/docs/contributing/tools/github/actions/workflows.md b/docs/contributing/tools/github/actions/workflows.md index 5a826a3a23..d3063aa350 100644 --- a/docs/contributing/tools/github/actions/workflows.md +++ b/docs/contributing/tools/github/actions/workflows.md @@ -86,6 +86,8 @@ Trigger column legend: **auto** = fires automatically (push, pull_request, sched | [cron-update.yml](../../../../../.github/workflows/cron-update.yml): `๐Ÿ”„ Update versions` | Updates Docker image versions and other pinned dependencies; opens an update PR via a GitHub App installation token so PR-lifecycle events fire on the resulting PR. Both jobs are gated behind the `CI_ENABLE_AUTO_UPDATES` repository variable, see [configuration.md](configuration.md). Requires the `BOT_APP_CLIENT_ID` and `BOT_APP_PRIVATE_KEY` repository secrets, see [secrets.md](secrets.md). | auto (`push` to `main`, `schedule`: daily 00:30 UTC), manual | none | | [entry-pr-translate.yml](../../../../../.github/workflows/entry-pr-translate.yml): `๐ŸŒ Translate catalogs` | Merges the source strings of the `core` and `docs` domains into `locale/`, then machine-translates what a pull request leaves empty or fuzzy, one runner per language LibreTranslate supports. Each runner opens its own PR against the head branch of the triggering PR. Gated behind the `CI_ENABLE_AUTO_TRANSLATIONS` repository variable, see [configuration.md](configuration.md); pull requests from a fork are skipped. Requires the `BOT_APP_CLIENT_ID` and `BOT_APP_PRIVATE_KEY` repository secrets, see [secrets.md](secrets.md). | auto (`pull_request` against `main`: opened, synchronize, reopened) | none | | [entry-pr-open-dependabot-close.yml](../../../../../.github/workflows/entry-pr-open-dependabot-close.yml): `๐Ÿšซ Dependabot: Close while auto-updates disabled` | Auto-closes Dependabot PRs while `CI_ENABLE_AUTO_UPDATES` is not set to `true`, so Dependabot honours the same gate as the workflow-driven update jobs. See [configuration.md](configuration.md). | auto (`pull_request_target`: opened, reopened) | none | +| [entry-pr-change-dependabot-label.yml](../../../../../.github/workflows/entry-pr-change-dependabot-label.yml): `๐Ÿ”„ Dependabot: Label update level` | Labels every Dependabot PR `update` plus exactly one of `major`, `minor` and `patch`, read from the `update-type` of `dependabot/fetch-metadata`; a type that names no semver level counts as `major`. Creates a missing label, adds only labels the PR lacks and checks out the base branch only. Gated behind `CI_ENABLE_AUTO_UPDATES`, see [configuration.md](configuration.md). | auto (`pull_request_target`: opened, reopened, synchronize) | none | +| [entry-pr-green-update-merge.yml](../../../../../.github/workflows/entry-pr-green-update-merge.yml): `๐Ÿ”„ Update: Merge proven PRs` | Runs when a `๐Ÿ”€ Pull Request` run of the `pull_request` event succeeds on an `update/*` or `dependabot/*` branch. [cli.contributing.update.merge](../../../../../cli/contributing/update/merge/__main__.py) merges the PR only when the `infinito-nexus-updater[bot]` App or `dependabot[bot]` opened it, it carries `update`, every check run and commit status on its head is green, and the run's `role-runtimes-*` artifacts list every role the PR changes. Otherwise it prints why and the PR stays open for a manual merge. The merge pins the tested head and uses the App token, so the App MUST be a bypass actor of the `Main` ruleset. Gated behind `CI_ENABLE_AUTO_UPDATES`, see [configuration.md](configuration.md); requires the `BOT_APP_CLIENT_ID` and `BOT_APP_PRIVATE_KEY` repository secrets, see [secrets.md](secrets.md). | auto (`workflow_run` of `๐Ÿ”€ Pull Request`: completed) | none | ## Changing workflows โœ๏ธ diff --git a/tests/unit/python/cli/contributing/update/merge/__init__.py b/tests/unit/python/cli/contributing/update/merge/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/cli/contributing/update/merge/test_gate.py b/tests/unit/python/cli/contributing/update/merge/test_gate.py new file mode 100644 index 0000000000..41c4da4627 --- /dev/null +++ b/tests/unit/python/cli/contributing/update/merge/test_gate.py @@ -0,0 +1,130 @@ +from __future__ import annotations + +import unittest + +from cli.contributing.update.merge import gate + +REPO = "infinito-nexus/core" + + +def pull_request(**overrides): + pr = { + "draft": False, + "user": {"login": "dependabot[bot]"}, + "head": {"ref": "dependabot/npm/left-pad-1.3.0", "repo": {"full_name": REPO}}, + "base": {"ref": "main"}, + "labels": [{"name": "update"}], + } + pr.update(overrides) + return pr + + +def check(**overrides): + run = { + "name": "๐Ÿงน Lint", + "status": "completed", + "conclusion": "success", + "details_url": "https://github.com/o/r/actions/runs/1/job/2", + } + run.update(overrides) + return run + + +class TestPullRequestRefusals(unittest.TestCase): + def test_an_update_bot_pull_request_passes(self): + self.assertEqual(gate.pull_request_refusals(pull_request(), REPO, "main"), []) + + def test_a_bot_outside_its_branch_prefix_is_refused(self): + head = {"ref": "update/sneaky", "repo": {"full_name": REPO}} + self.assertEqual( + gate.pull_request_refusals(pull_request(head=head), REPO, "main"), + ["branch update/sneaky lacks the dependabot/ prefix of dependabot[bot]"], + ) + + def test_a_head_in_another_repository_is_refused(self): + head = {"ref": "dependabot/npm/x", "repo": {"full_name": "fork/core"}} + refusals = gate.pull_request_refusals(pull_request(head=head), REPO, "main") + self.assertEqual( + refusals, [f"head branch dependabot/npm/x lives outside {REPO}"] + ) + + def test_a_deleted_head_repository_is_refused(self): + head = {"ref": "dependabot/npm/x", "repo": None} + refusals = gate.pull_request_refusals(pull_request(head=head), REPO, "main") + self.assertEqual(len(refusals), 1) + + def test_a_draft_is_refused(self): + refusals = gate.pull_request_refusals(pull_request(draft=True), REPO, "main") + self.assertEqual(refusals, ["pull request is a draft"]) + + def test_another_base_branch_is_refused(self): + base = {"ref": "release"} + refusals = gate.pull_request_refusals(pull_request(base=base), REPO, "main") + self.assertEqual(refusals, ["base branch is release, not main"]) + + +class TestCheckRefusals(unittest.TestCase): + def test_skipped_and_neutral_count_as_green(self): + runs = [check(conclusion="skipped"), check(conclusion="neutral")] + self.assertEqual(gate.check_refusals(runs, [], own_run_id=9), []) + + def test_no_check_run_at_all_refuses(self): + self.assertEqual( + gate.check_refusals([], [], own_run_id=9), + ["no check run on the head commit"], + ) + + def test_only_the_own_run_left_refuses(self): + own = check(details_url="https://github.com/o/r/actions/runs/9/job/3") + self.assertEqual( + gate.check_refusals([own], [], own_run_id=9), + ["no check run on the head commit"], + ) + + def test_a_pending_status_refuses(self): + statuses = [{"context": "ci/external", "state": "pending"}] + self.assertEqual( + gate.check_refusals([check()], statuses, own_run_id=9), + ["status ci/external is pending"], + ) + + +class TestRoles(unittest.TestCase): + def test_changed_roles_reads_the_role_directory(self): + paths = [ + "roles/web-app-nextcloud/meta/services.yml", + "roles/sys-lint/meta/services.yml", + "pyproject.toml", + "docs/roles/web-app-matomo.md", + ] + self.assertEqual(gate.changed_roles(paths), {"web-app-nextcloud", "sys-lint"}) + + def test_deployed_roles_unions_the_role_column(self): + first = "role,seconds\nweb-app-nextcloud,3.0\nsvc-db-postgres,1.0\n" + second = "round,role,seconds\n1,web-app-matomo,2.0\n1,,0.5\n" + self.assertEqual( + gate.deployed_roles([first, second]), + {"web-app-nextcloud", "svc-db-postgres", "web-app-matomo"}, + ) + + def test_a_csv_without_a_role_column_proves_nothing(self): + self.assertEqual(gate.deployed_roles(["name,seconds\nweb-app-x,1\n"]), set()) + + def test_no_changed_role_needs_no_proof(self): + self.assertEqual(gate.role_refusals(set(), []), []) + + def test_every_missing_role_is_named(self): + csv_text = "role,seconds\nweb-app-nextcloud,1.0\n" + self.assertEqual( + gate.role_refusals( + {"web-app-nextcloud", "web-app-a", "web-app-b"}, [csv_text] + ), + [ + "role web-app-a changed, but no deploy row ran it", + "role web-app-b changed, but no deploy row ran it", + ], + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/cli/contributing/update/merge/test_github.py b/tests/unit/python/cli/contributing/update/merge/test_github.py new file mode 100644 index 0000000000..a15e6d5297 --- /dev/null +++ b/tests/unit/python/cli/contributing/update/merge/test_github.py @@ -0,0 +1,118 @@ +from __future__ import annotations + +import io +import json +import unittest +import zipfile +from unittest import mock + +from cli.contributing.update.merge import github + +REPO = "infinito-nexus/core" +SHA = "b" * 40 + + +def lines(*objects): + return "\n".join(json.dumps(item) for item in objects).encode() + + +def archive(members): + buffer = io.BytesIO() + with zipfile.ZipFile(buffer, "w") as zipped: + for name, data in members.items(): + zipped.writestr(name, data) + return buffer.getvalue() + + +class TestReads(unittest.TestCase): + def test_items_paginates_and_parses_one_object_per_line(self): + gh = mock.Mock(return_value=lines({"a": 1}, {"a": 2}) + b"\n") + self.assertEqual(github.items(gh, "repos/x", ".[]"), [{"a": 1}, {"a": 2}]) + gh.assert_called_once_with(["api", "--paginate", "repos/x", "--jq", ".[]"]) + + def test_open_pull_requests_drop_closed_ones_and_other_heads(self): + prs = [ + {"number": 1, "state": "open", "head": {"sha": SHA}}, + {"number": 2, "state": "closed", "head": {"sha": SHA}}, + {"number": 3, "state": "open", "head": {"sha": "c" * 40}}, + ] + gh = mock.Mock(return_value=lines(*prs)) + found = github.open_pull_requests(gh, REPO, SHA) + self.assertEqual([pr["number"] for pr in found], [1]) + + def test_changed_paths_keep_the_old_name_of_a_rename(self): + files = [ + { + "filename": "roles/web-app-new/meta/main.yml", + "previous_filename": "roles/web-app-old/meta/main.yml", + }, + {"filename": "pyproject.toml", "previous_filename": None}, + ] + gh = mock.Mock(return_value=lines(*files)) + self.assertEqual( + github.changed_paths(gh, REPO, 5), + [ + "roles/web-app-new/meta/main.yml", + "roles/web-app-old/meta/main.yml", + "pyproject.toml", + ], + ) + + +class TestCsvMembers(unittest.TestCase): + def test_only_csv_members_are_read(self): + blob = archive({"a.csv": "role\nx\n", "notes.txt": "role\ny\n"}) + self.assertEqual(github.csv_members(blob), ["role\nx\n"]) + + def test_an_oversized_member_is_left_out(self): + big = "role\n" + "x" * (github.MAX_CSV_BYTES + 1) + blob = archive({"big.csv": big, "small.csv": "role\nx\n"}) + self.assertEqual(github.csv_members(blob), ["role\nx\n"]) + + def test_a_traversing_member_name_is_only_read_in_memory(self): + blob = archive({"../../etc/evil.csv": "role\nx\n"}) + self.assertEqual(github.csv_members(blob), ["role\nx\n"]) + + +class TestRoleRuntimeCsvs(unittest.TestCase): + def test_only_unexpired_role_runtimes_artifacts_are_downloaded(self): + artifacts = [ + { + "id": 1, + "name": "role-runtimes-web-app-a", + "expired": False, + "size_in_bytes": 10, + }, + { + "id": 2, + "name": "role-runtimes-web-app-b", + "expired": True, + "size_in_bytes": 10, + }, + { + "id": 3, + "name": "inventory-web-app-a", + "expired": False, + "size_in_bytes": 10, + }, + { + "id": 4, + "name": "role-runtimes-web-app-c", + "expired": False, + "size_in_bytes": github.MAX_ARTIFACT_BYTES + 1, + }, + ] + downloads = [] + + def gh(args): + if args[1] == "--paginate": + return lines(*artifacts) + downloads.append(args[1]) + return archive({"r.csv": "role\nweb-app-a\n"}) + + self.assertEqual(github.role_runtime_csvs(gh, REPO, 77), ["role\nweb-app-a\n"]) + self.assertEqual(downloads, [f"repos/{REPO}/actions/artifacts/1/zip"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/cli/contributing/update/merge/test_main.py b/tests/unit/python/cli/contributing/update/merge/test_main.py new file mode 100644 index 0000000000..fb2ab75bec --- /dev/null +++ b/tests/unit/python/cli/contributing/update/merge/test_main.py @@ -0,0 +1,233 @@ +from __future__ import annotations + +import io +import json +import tempfile +import unittest +import zipfile +from contextlib import redirect_stderr, redirect_stdout +from pathlib import Path +from unittest import mock + +import cli.contributing.update.merge.__main__ as merge_main +from cli.contributing.update.merge import github + +REPO = "infinito-nexus/core" +SHA = "a" * 40 +RUN_ID = 111 +OWN_RUN_ID = 222 +CSV_HEADER = "round,rounds_total,pass,pass_mode,role,seconds,hosts\n" + + +def pull_request(**overrides): + pr = { + "number": 7, + "state": "open", + "draft": False, + "user": {"login": "infinito-nexus-updater[bot]"}, + "head": { + "sha": SHA, + "ref": "update/docker-image-versions-20261121-abc1234", + "repo": {"full_name": REPO}, + }, + "base": {"ref": "main"}, + "labels": [{"name": "update"}, {"name": "minor"}], + } + pr.update(overrides) + return pr + + +def check(name="๐Ÿ”€ Pull Request / ๐Ÿ Finish pipeline", **overrides): + run = { + "name": name, + "status": "completed", + "conclusion": "success", + "details_url": f"https://github.com/{REPO}/actions/runs/{RUN_ID}/job/1", + } + run.update(overrides) + return run + + +def role_runtimes(*roles): + rows = "".join(f",,,,{role},1.00,localhost=executed\n" for role in roles) + buffer = io.BytesIO() + with zipfile.ZipFile(buffer, "w") as archive: + archive.writestr("role-runtimes-web-app-nextcloud.csv", CSV_HEADER + rows) + return buffer.getvalue() + + +class FakeGh: + """Answers the REST paths the merge gate reads, recording every call. + + Args: + prs: pull requests associated with ``SHA``. + checks: check runs on ``SHA``. + statuses: commit statuses on ``SHA``. + files: ``filename`` paths the pull request touches. + artifacts: ``{name: zip bytes}`` of the CI run's artifacts. + """ + + def __init__(self, prs, checks, statuses, files, artifacts): + self.routes = { + f"repos/{REPO}/commits/{SHA}/pulls": prs, + f"repos/{REPO}/commits/{SHA}/check-runs": checks, + f"repos/{REPO}/commits/{SHA}/status": statuses, + f"repos/{REPO}/pulls/7/files": [ + {"filename": path, "previous_filename": None} for path in files + ], + f"repos/{REPO}/actions/runs/{RUN_ID}/artifacts": [ + {"id": index, "name": name, "expired": False, "size_in_bytes": 512} + for index, name in enumerate(artifacts) + ], + } + self.blobs = dict(enumerate(artifacts.values())) + self.calls = [] + + def __call__(self, args): + self.calls.append(list(args)) + if args[1] == "--paginate": + route = args[2].split("?")[0] + return "\n".join(json.dumps(item) for item in self.routes[route]).encode() + artifact_id = int(args[1].split("/")[-2]) + return self.blobs[artifact_id] + + +def green_gh(**overrides): + fields = { + "prs": [pull_request()], + "checks": [check()], + "statuses": [{"context": "codecov", "state": "success"}], + "files": ["roles/web-app-nextcloud/meta/services.yml"], + "artifacts": { + "role-runtimes-web-app-nextcloud": role_runtimes( + "web-app-nextcloud", "svc-db-postgres" + ) + }, + } + fields.update(overrides) + return FakeGh(**fields) + + +def evaluate(gh): + return merge_main.evaluate(gh, REPO, SHA, RUN_ID, OWN_RUN_ID, "main") + + +class TestEvaluate(unittest.TestCase): + def test_all_green_and_every_changed_role_deployed_merges(self): + pr, refusals = evaluate(green_gh()) + self.assertEqual((pr["number"], refusals), (7, [])) + + def test_a_dependabot_pull_request_merges_like_the_updater(self): + dependabot = pull_request( + user={"login": "dependabot[bot]"}, + head={ + "sha": SHA, + "ref": "dependabot/pip/roles/web-app-nextcloud/files/requests-2.32.0", + "repo": {"full_name": REPO}, + }, + ) + self.assertEqual(evaluate(green_gh(prs=[dependabot]))[1], []) + + def test_a_non_bot_author_is_refused(self): + human = pull_request(user={"login": "octocat"}) + refusals = evaluate(green_gh(prs=[human]))[1] + self.assertEqual(refusals, ["author octocat is no update bot"]) + + def test_a_missing_update_label_is_refused(self): + unlabeled = pull_request(labels=[{"name": "minor"}]) + refusals = evaluate(green_gh(prs=[unlabeled]))[1] + self.assertEqual(refusals, ["label update is missing"]) + + def test_a_pending_check_refuses(self): + pending = check("๐ŸŒ Translate catalogs", status="in_progress", conclusion=None) + refusals = evaluate(green_gh(checks=[check(), pending]))[1] + self.assertEqual(refusals, ["check ๐ŸŒ Translate catalogs is in_progress"]) + + def test_a_failed_check_refuses(self): + failed = check("๐Ÿ” CodeQL", conclusion="failure") + refusals = evaluate(green_gh(checks=[check(), failed]))[1] + self.assertEqual(refusals, ["check ๐Ÿ” CodeQL concluded failure"]) + + def test_a_failed_commit_status_refuses(self): + statuses = [{"context": "codecov", "state": "failure"}] + refusals = evaluate(green_gh(statuses=statuses))[1] + self.assertEqual(refusals, ["status codecov is failure"]) + + def test_the_deciding_run_own_check_does_not_count(self): + own = check( + "๐Ÿ”€ Merge a proven update PR", + status="in_progress", + conclusion=None, + details_url=f"https://github.com/{REPO}/actions/runs/{OWN_RUN_ID}/job/9", + ) + self.assertEqual(evaluate(green_gh(checks=[check(), own]))[1], []) + + def test_a_changed_role_absent_from_role_runtimes_refuses(self): + artifacts = {"role-runtimes-web-app-matomo": role_runtimes("web-app-matomo")} + refusals = evaluate(green_gh(artifacts=artifacts))[1] + self.assertEqual( + refusals, ["role web-app-nextcloud changed, but no deploy row ran it"] + ) + + def test_no_role_runtimes_artifact_refuses(self): + artifacts = {"inventory-web-app-nextcloud": role_runtimes("web-app-nextcloud")} + refusals = evaluate(green_gh(artifacts=artifacts))[1] + self.assertEqual( + refusals, ["no role-runtimes artifact proves web-app-nextcloud"] + ) + + def test_a_pull_request_touching_no_role_needs_no_artifact(self): + gh = green_gh(files=[".github/workflows/call-lint.yml"], artifacts={}) + self.assertEqual(evaluate(gh)[1], []) + self.assertFalse(any("artifacts" in " ".join(call) for call in gh.calls)) + + def test_no_open_pull_request_for_the_head_refuses(self): + closed = pull_request(state="closed") + pr, refusals = evaluate(green_gh(prs=[closed])) + self.assertIsNone(pr) + self.assertEqual(refusals, [f"0 open pull requests have head {SHA}, not one"]) + + +class TestMain(unittest.TestCase): + def run_main(self, gh, sha=SHA): + with tempfile.TemporaryDirectory() as tmp: + output = Path(tmp) / "github_output" + argv = [ + "--repo", + REPO, + "--sha", + sha, + "--run-id", + str(RUN_ID), + "--own-run-id", + str(OWN_RUN_ID), + "--base", + "main", + "--output", + str(output), + ] + stdout = io.StringIO() + with mock.patch.object(github, "run_gh", gh), redirect_stdout(stdout): + code = merge_main.main(argv) + with output.open(encoding="utf-8") as handle: + return code, handle.read(), stdout.getvalue() + + def test_a_merge_verdict_writes_pr_and_sha(self): + code, outputs, _ = self.run_main(green_gh()) + self.assertEqual((code, outputs), (0, f"merge=true\npr=7\nsha={SHA}\n")) + + def test_a_refusal_writes_merge_false_and_exits_zero(self): + gh = green_gh(checks=[check(conclusion="cancelled")]) + code, outputs, printed = self.run_main(gh) + self.assertEqual((code, outputs), (0, "merge=false\n")) + self.assertIn("stays open for a manual merge", printed) + + def test_a_short_sha_is_rejected_before_any_call(self): + gh = green_gh() + with self.assertRaises(SystemExit), redirect_stderr(io.StringIO()): + self.run_main(gh, sha="abc1234") + self.assertEqual(gh.calls, []) + + +if __name__ == "__main__": + unittest.main()