mirror of
https://github.com/kevinveenbirkenbach/computer-playbook.git
synced 2026-11-28 22:06:31 +00:00
feat(ci): merge update PRs automatically once CI deployed every changed role
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 <noreply@anthropic.com>
This commit is contained in:
1 parent
5c6b274d52
commit
306382e03d
15 files changed
+1011
-3
No files matched your search
Whitespace-only changes.
@@ -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()
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
Reference in new issue
Block a user