diff --git a/.github/workflows/check_gcode_comment.yml b/.github/workflows/check_gcode_comment.yml
new file mode 100644
index 0000000000..96c0a49bd9
--- /dev/null
+++ b/.github/workflows/check_gcode_comment.yml
@@ -0,0 +1,55 @@
+name: Post sliced G-code comparison
+
+# Posts the comparison that the Slice check of build_all.yml wrote into its gcode-fingerprints
+# artifact, on an open pull request with the check-gcode label. Woken by both workflows below,
+# whichever finishes last; scripts/ci_check_gcode.py then starts from each pull request's
+# current head.
+#
+# Its token can write, so it never checks out, unpacks or runs anything from a pull request.
+# The artifact is read in memory, and its text only appears inside a fence in the comment.
+#
+# The names in 'workflows' must match the 'name' fields of build_all.yml and
+# check_gcode_label.yml exactly.
+on:
+ workflow_run:
+ workflows: ["Build all", "check-gcode label"]
+ types:
+ - completed
+
+permissions:
+ actions: read
+ contents: read
+ pull-requests: write
+ # Needed to delete outdated bot comments through the issues/comments endpoint.
+ issues: write
+
+# One handler at a time per source branch, so two wakes cannot race delete-and-post.
+concurrency:
+ group: ${{ github.workflow }}-${{ github.event.workflow_run.head_repository.full_name }}-${{ github.event.workflow_run.head_branch }}
+ cancel-in-progress: false
+
+jobs:
+ post_comment:
+ name: Post the comparison comment
+ runs-on: ubuntu-24.04
+ timeout-minutes: 10
+ # A label workflow run for any other label is skipped and has nothing to wake.
+ if: ${{ github.event.workflow_run.event == 'pull_request' && github.event.workflow_run.conclusion != 'skipped' }}
+ steps:
+ - name: Checkout the scripts from the default branch
+ uses: actions/checkout@v7
+ with:
+ sparse-checkout: |
+ scripts/ci_check_gcode.py
+ scripts/gcode_fingerprint.py
+ sparse-checkout-cone-mode: false
+ persist-credentials: false
+
+ - name: Update the comment
+ # A failure would leave a red check on the pull request, which blocks pr-merge-bot.
+ continue-on-error: true
+ env:
+ GH_TOKEN: ${{ github.token }}
+ HEAD_REPO: ${{ github.event.workflow_run.head_repository.full_name }}
+ HEAD_BRANCH: ${{ github.event.workflow_run.head_branch }}
+ run: python3 scripts/ci_check_gcode.py comment --repo "$GITHUB_REPOSITORY" --head-repo "$HEAD_REPO" --head-branch "$HEAD_BRANCH"
diff --git a/.github/workflows/check_gcode_label.yml b/.github/workflows/check_gcode_label.yml
new file mode 100644
index 0000000000..a09779ff3e
--- /dev/null
+++ b/.github/workflows/check_gcode_label.yml
@@ -0,0 +1,25 @@
+name: check-gcode label
+
+# Wakes check_gcode_comment.yml when the check-gcode label is added after the pull request's
+# build finished. It runs no pull request code and needs no token. A pull_request run cannot post
+# on a pull request from a fork, and pull_request_target is blocked by default in public
+# repositories, so the comment is posted by a workflow_run workflow instead.
+#
+# The workflow name is matched in check_gcode_comment.yml. No branches filter: a pull request
+# into another branch is told why it gets no report.
+on:
+ pull_request:
+ types:
+ - labeled
+
+permissions: {}
+
+jobs:
+ wake:
+ name: Wake the comparison comment
+ if: ${{ github.event.label.name == 'check-gcode' }}
+ runs-on: ubuntu-24.04
+ timeout-minutes: 5
+ steps:
+ - name: Note the label
+ run: echo "check_gcode_comment.yml posts the comparison when this run completes."
diff --git a/scripts/ci_check_gcode.py b/scripts/ci_check_gcode.py
index 5afb799419..5061bb0d12 100644
--- a/scripts/ci_check_gcode.py
+++ b/scripts/ci_check_gcode.py
@@ -7,6 +7,10 @@ The Slice check job of build_all.yml fingerprints the G-code of every shipped pr
pull request's base commit, and writes report.txt into the same artifact. Pushes and the
nightly build are the baselines; they upload only fingerprints.tsv and made_with.txt.
+`comment` runs from check_gcode_comment.yml with a token that can write, so it treats the
+artifact as hostile: it reads it in memory, posts its text only inside a fence, and never
+prints it.
+
Environment: GH_TOKEN, and optionally GITHUB_API_URL.
"""
@@ -46,6 +50,15 @@ BASELINE_LINE = "Baseline: "
# A comment holds at most 65,536 characters; the report inside it is cut well before.
FENCE_LIMIT = 50000
FENCE = "````"
+LABEL = "check-gcode"
+MARKER = ""
+HEADING = "## Sliced G-code comparison"
+BOT_LOGIN = "github-actions[bot]"
+REPORT_LIMIT = 256 * 1024
+NO_BUILD = ("This commit has no `Build all` run, so there is nothing to compare. Either the pull request "
+ "changes no file that is built, or its base branch is not `main` or a `release/` branch.")
+NO_COMPARISON = ("The build of this commit made no comparison: its slice check failed or did not run, "
+ "the build predates the comparison, or its artifact expired.")
# Only these are bounded by a capped read; bzip2 and LZMA decompress a whole block at once.
READABLE_COMPRESSION = (zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED)
@@ -77,6 +90,10 @@ class Api:
with urllib.request.urlopen(self._request("GET", path, params), timeout=30) as response:
return json.load(response)
+ def send(self, method, path, body=None):
+ with urllib.request.urlopen(self._request(method, path, body=body), timeout=30) as response:
+ response.read()
+
def get_bytes(self, path, limit):
"""The body of a download, read up to `limit` bytes. The redirect to storage is followed
without the token, which the storage host must not see."""
@@ -249,6 +266,94 @@ def report_main(args, api):
return build_report(baseline, base_rows, head_rows, base_made_with, head_made_with, args.branch)
+def _stable(body):
+ """The part of a comment that a new commit or a new baseline with the same result leaves alone:
+ all but the last line, without the baseline paragraph inside the fence."""
+ kept, skipping = [], False
+ for line in body.splitlines()[:-1]:
+ if line.startswith(BASELINE_LINE):
+ skipping = True
+ elif line == FENCE:
+ skipping = False
+ if not skipping:
+ kept.append(line)
+ return kept
+
+
+def _bot_comments(api, repo, number):
+ found, page = [], 1
+ while True:
+ batch = api.get(f"repos/{repo}/issues/{number}/comments", per_page=100, page=page)
+ found += [c for c in batch if c["user"]["login"] == BOT_LOGIN and c["body"].startswith(MARKER)]
+ if len(batch) < 100:
+ return found
+ page += 1
+
+
+def post_comment(api, repo, number, body):
+ """Keeps an identical comment, edits one whose result is the same, else replaces them all."""
+ old = _bot_comments(api, repo, number)
+ if len(old) == 1 and old[0]["body"] == body:
+ return
+ if len(old) == 1 and _stable(old[0]["body"]) == _stable(body):
+ api.send("PATCH", f"repos/{repo}/issues/comments/{old[0]['id']}", {"body": body})
+ return
+ for c in old:
+ api.send("DELETE", f"repos/{repo}/issues/comments/{c['id']}")
+ api.send("POST", f"repos/{repo}/issues/{number}/comments", {"body": body})
+
+
+def comment_body(sha, report=None, note=None):
+ middle = (f"Made by this pull request's own build, so a change to the workflow or the scripts "
+ f"changes the report too.\n\n{fence(report)}" if report is not None else f"{note}\n")
+ return f"{MARKER}\n{HEADING}\n\n{middle}\nFor commit {sha}.\n"
+
+
+def find_report(api, repo, pr):
+ """The report of the pull request's newest finished build, NO_BUILD or NO_COMPARISON as a note,
+ or None while its newest build is not finished (that build's completion comes back here)."""
+ head = pr["head"]
+ runs = api.get(f"repos/{repo}/actions/workflows/{WORKFLOW}/runs", event="pull_request",
+ head_sha=head["sha"], per_page=100)["workflow_runs"]
+ # The head commit alone proves nothing: another fork can open a pull request at the same commit.
+ runs = sorted((r for r in runs if r["head_repository"] and r["head_repository"]["full_name"] == head["repo"]["full_name"]
+ and r["head_branch"] == head["ref"]), key=lambda r: r["id"], reverse=True)
+ if not runs:
+ return None, NO_BUILD
+ if runs[0]["status"] != "completed" or runs[0]["conclusion"] == "action_required":
+ return None, None
+ for run in runs:
+ if run["status"] != "completed":
+ continue
+ art = find_artifact(api, repo, run["id"])
+ if not art:
+ continue
+ files = read_artifact(api, repo, art, ["pr_number.txt", "report.txt"], REPORT_LIMIT)
+ if files.get("pr_number.txt", b"").strip() == str(pr["number"]).encode() and "report.txt" in files:
+ return files["report.txt"], None
+ return None, NO_COMPARISON
+
+
+def comment(api, repo, head_repo, head_branch):
+ owner = head_repo.split("/")[0]
+ pulls = api.get(f"repos/{repo}/pulls", state="open", head=f"{owner}:{head_branch}", per_page=100)
+ for pr in pulls:
+ if not pr["head"]["repo"] or pr["head"]["repo"]["full_name"] != head_repo:
+ continue
+ if LABEL not in {label["name"] for label in pr["labels"]}:
+ continue
+ base = pr["base"]["ref"]
+ if base == "main" or base.startswith("release/"):
+ report, note = find_report(api, repo, pr)
+ else:
+ report, note = None, NO_BUILD
+ if report is None and note is None:
+ print(f"#{pr['number']}: its newest build has not finished.")
+ continue
+ post_comment(api, repo, pr["number"], comment_body(pr["head"]["sha"], report, note))
+ print(f"#{pr['number']}: comment up to date.")
+
+
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
commands = parser.add_subparsers(dest="command", required=True)
@@ -261,6 +366,10 @@ def main(argv=None):
report.add_argument("--head-dir", required=True)
report.add_argument("--out", required=True)
report.add_argument("--summary", help="a job summary file to append the report to")
+ post = commands.add_parser("comment", help="post the report on the pull requests from a branch")
+ post.add_argument("--repo", required=True)
+ post.add_argument("--head-repo", required=True)
+ post.add_argument("--head-branch", required=True)
args = parser.parse_args(argv)
if args.command == "made-with":
@@ -270,6 +379,14 @@ def main(argv=None):
return 0
api = Api(os.environ.get("GH_TOKEN", ""), os.environ.get("GITHUB_API_URL", "https://api.github.com"))
+ if args.command == "comment":
+ try:
+ comment(api, args.repo, args.head_repo, args.head_branch)
+ except Exception as error: # noqa: BLE001 - a failure must not leave a red check
+ # The type and HTTP status only: the message can hold the artifact's text.
+ status = f", HTTP {error.code}" if isinstance(error, urllib.error.HTTPError) else ""
+ print(f"Could not update the comment ({type(error).__name__}{status}).")
+ return 0
try:
text = report_main(args, api)
except (ArtifactError, urllib.error.URLError, OSError, ValueError, KeyError, TypeError) as error:
diff --git a/scripts/tests/test_ci_check_gcode.py b/scripts/tests/test_ci_check_gcode.py
index ee8a4315fd..76022ad0fb 100644
--- a/scripts/tests/test_ci_check_gcode.py
+++ b/scripts/tests/test_ci_check_gcode.py
@@ -10,6 +10,7 @@ import os
import sys
import tempfile
import unittest
+import urllib.error
import zipfile
from unittest import mock
@@ -251,6 +252,150 @@ class BuildReportTest(unittest.TestCase):
self.assertIn("nothing was compared", text)
+HEAD_REPO = "someone/repo"
+SHA = "d" * 40
+BOT = {"login": "github-actions[bot]"}
+
+
+def pull(number=5, labels=(cc.LABEL,), base="main", head_repo=HEAD_REPO, sha=SHA):
+ return {"number": number, "labels": [{"name": name} for name in labels], "base": {"ref": base},
+ "head": {"sha": sha, "ref": "fix", "repo": {"full_name": head_repo}}}
+
+
+def pr_run(run_id, status="completed", conclusion="success", head_repo=HEAD_REPO, branch="fix"):
+ return {"id": run_id, "status": status, "conclusion": conclusion, "head_branch": branch,
+ "head_repository": {"full_name": head_repo}}
+
+
+class CommentFake(FakeApi):
+ """A repository with pull requests, Build all runs, artifacts and the pull request's comments."""
+
+ def __init__(self, pulls, runs=(), artifacts=None, comments=()):
+ super().__init__()
+ self.comments = [dict(c) for c in comments]
+ self.sent = []
+ self.gets[f"repos/{REPO}/pulls"] = list(pulls)
+ self.gets[f"repos/{REPO}/actions/workflows/build_all.yml/runs"] = {"workflow_runs": list(runs)}
+ for run_id, (members, size) in (artifacts or {}).items():
+ self.gets[f"repos/{REPO}/actions/runs/{run_id}/artifacts"] = {"artifacts": [artifact(run_id * 10, size)]}
+ self.blobs[f"repos/{REPO}/actions/artifacts/{run_id * 10}/zip"] = make_zip(members)
+ for run in runs:
+ self.gets.setdefault(f"repos/{REPO}/actions/runs/{run['id']}/artifacts", {"artifacts": []})
+ self.gets[f"repos/{REPO}/issues/5/comments"] = lambda params: (
+ self.comments if params.get("page", 1) == 1 else [])
+
+ def send(self, method, path, body=None):
+ self.sent.append((method, path, body))
+
+
+def report_artifact(report="G-code changed for 1 of 2 compared slices\n", number="5\n"):
+ return ({"report.txt": report, "pr_number.txt": number}, 500)
+
+
+def comment(comment_id, body):
+ return {"id": comment_id, "user": BOT, "body": body}
+
+
+class CommentTest(unittest.TestCase):
+ def run_comment(self, api, head_repo=HEAD_REPO):
+ cc.comment(api, REPO, head_repo, "fix")
+ return api.sent
+
+ def posted(self, sent):
+ self.assertEqual(len(sent), 1)
+ method, path, body = sent[0]
+ self.assertEqual((method, path), ("POST", f"repos/{REPO}/issues/5/comments"))
+ return body["body"]
+
+ def test_no_open_pull_request_from_the_branch_does_nothing(self):
+ self.assertEqual(self.run_comment(CommentFake([])), [])
+
+ def test_a_pull_request_from_another_repository_with_the_same_branch_name_is_ignored(self):
+ api = CommentFake([pull(head_repo="other/repo")], [pr_run(1)], {1: report_artifact()})
+ self.assertEqual(self.run_comment(api), [])
+
+ def test_a_pull_request_without_the_label_gets_no_comment(self):
+ api = CommentFake([pull(labels=("bug-fix",))], [pr_run(1)], {1: report_artifact()})
+ self.assertEqual(self.run_comment(api), [])
+
+ def test_a_pull_request_into_another_branch_is_told_why_there_is_no_report(self):
+ body = self.posted(self.run_comment(CommentFake([pull(base="feature/x")])))
+ self.assertIn("no `Build all` run", body)
+
+ def test_a_commit_without_a_build_is_told_why(self):
+ body = self.posted(self.run_comment(CommentFake([pull()])))
+ self.assertIn("no `Build all` run", body)
+ self.assertTrue(body.startswith(cc.MARKER))
+
+ def test_a_build_still_running_waits_for_its_own_completion(self):
+ api = CommentFake([pull()], [pr_run(2, status="in_progress"), pr_run(1)], {1: report_artifact()})
+ self.assertEqual(self.run_comment(api), [])
+
+ def test_a_build_waiting_for_approval_is_not_finished(self):
+ api = CommentFake([pull()], [pr_run(2, conclusion="action_required")], {})
+ self.assertEqual(self.run_comment(api), [])
+
+ def test_a_build_without_the_artifact_is_told_why(self):
+ body = self.posted(self.run_comment(CommentFake([pull()], [pr_run(1)], {})))
+ self.assertIn("made no comparison", body)
+
+ def test_a_run_from_another_repository_at_the_same_commit_is_not_used(self):
+ api = CommentFake([pull()], [pr_run(2, head_repo="other/repo")], {2: report_artifact("forged\n")})
+ body = self.posted(self.run_comment(api))
+ self.assertNotIn("forged", body)
+ self.assertIn("no `Build all` run", body)
+
+ def test_an_artifact_naming_another_pull_request_is_not_used(self):
+ api = CommentFake([pull()], [pr_run(1)], {1: report_artifact(number="6\n")})
+ self.assertIn("made no comparison", self.posted(self.run_comment(api)))
+
+ def test_the_report_is_posted_in_a_fence_for_the_current_head(self):
+ body = self.posted(self.run_comment(CommentFake([pull()], [pr_run(1)], {1: report_artifact()})))
+ self.assertIn(cc.HEADING, body)
+ self.assertIn("own build", body)
+ self.assertIn("````\nG-code changed for 1 of 2 compared slices\n````", body)
+ self.assertTrue(body.rstrip().endswith(f"For commit {SHA}."))
+
+ def test_each_pull_request_from_the_branch_is_handled(self):
+ api = CommentFake([pull(base="main"), pull(base="release/2.5")], [pr_run(1)], {1: report_artifact()})
+ self.assertEqual(len(self.run_comment(api)), 2)
+
+ def body_for(self, report, sha=SHA):
+ api = CommentFake([pull(sha=sha)], [pr_run(1)], {1: report_artifact(report)})
+ return self.posted(self.run_comment(api))
+
+ def test_the_same_comment_is_kept(self):
+ old = self.body_for("same\n")
+ api = CommentFake([pull()], [pr_run(1)], {1: report_artifact("same\n")}, [comment(9, old)])
+ self.assertEqual(self.run_comment(api), [])
+
+ def test_a_new_commit_or_baseline_with_the_same_result_edits_in_place(self):
+ old = self.body_for("same\nBaseline: compared with aaaa\n", sha="e" * 40)
+ api = CommentFake([pull()], [pr_run(1)], {1: report_artifact("same\nBaseline: compared with bbbb\n")},
+ [comment(9, old)])
+ sent = self.run_comment(api)
+ self.assertEqual([(m, p) for m, p, _ in sent], [("PATCH", f"repos/{REPO}/issues/comments/9")])
+
+ def test_a_changed_result_replaces_the_comment(self):
+ old = self.body_for("before\n")
+ api = CommentFake([pull()], [pr_run(1)], {1: report_artifact("after\n")},
+ [comment(9, old), {"id": 8, "user": {"login": "someone"}, "body": cc.MARKER}])
+ sent = self.run_comment(api)
+ self.assertEqual([(m, p) for m, p, _ in sent],
+ [("DELETE", f"repos/{REPO}/issues/comments/9"), ("POST", f"repos/{REPO}/issues/5/comments")])
+
+
+class CommentCommandTest(unittest.TestCase):
+ def test_an_error_prints_its_type_and_status_only_and_exits_zero(self):
+ error = urllib.error.HTTPError("https://x", 502, "line from the artifact", {}, None)
+ stdout = io.StringIO()
+ with mock.patch.object(cc, "comment", side_effect=error), contextlib.redirect_stdout(stdout):
+ code = cc.main(["comment", "--repo", REPO, "--head-repo", HEAD_REPO, "--head-branch", "fix"])
+ self.assertEqual(code, 0)
+ self.assertNotIn("line from the artifact", stdout.getvalue())
+ self.assertIn("502", stdout.getvalue())
+
+
class ReportCommandTest(unittest.TestCase):
def run_report(self, folder, error=None, text="report\n"):
out, summary = os.path.join(folder, "report.txt"), os.path.join(folder, "summary.md")