mirror of
https://gitee.com/mirrors_PX4/PX4-Autopilot.git
synced 2026-04-14 10:07:39 +08:00
* ci(pr-review-poster): add line-anchored review poster and migrate clang-tidy Adds a generic PR review-comment poster as a sibling of the issue-comment poster from #27021. Replaces platisd/clang-tidy-pr-comments@v1 in the Static Analysis workflow with an in-tree, fork-friendly producer + poster pair so fork PRs get inline clang-tidy annotations on the Files changed tab without trusting a third-party action with a write token. Architecture mirrors pr-comment-poster: a producer (clang-tidy.yml) runs inside the px4-dev container and writes a `pr-review` artifact containing manifest.json and a baked comments.json. A separate workflow_run-triggered poster runs on ubuntu-latest with the base-repo write token, validates the artifact, dismisses any stale matching review, and posts a fresh review on the target PR. The poster never checks out PR code and only ever reads two opaque JSON files from the artifact. Stale-review dismissal is restricted to reviews authored by github-actions[bot] AND whose body contains the producer's marker. A fork cannot impersonate the bot login or inject the marker into a human reviewer's body, so the poster can never dismiss a human review. APPROVE events are explicitly forbidden so a bot cannot approve a pull request. To avoid duplicating ~120 lines of HTTP plumbing between the two posters, the GitHub REST helpers (single-request, pagination, error handling) are extracted into Tools/ci/_github_helpers.py with a small GitHubClient class. The existing pr-comment-poster.py is refactored to use it; net change is roughly -80 lines on that script. The shared module is sparse-checked-out alongside each poster script and is stdlib only. The clang-tidy producer reuses MIT-licensed translation logic from platisd/clang-tidy-pr-comments (generate_review_comments, reorder_diagnostics, get_diff_line_ranges_per_file and helpers) under a preserved attribution header. The HTTP layer is rewritten on top of _github_helpers so the producer does not pull in `requests`. Conversation resolution (the GraphQL path) is intentionally dropped for v1. clang-tidy.yml now produces the pr-review artifact in the same job as the build, so the cross-runner compile_commands.json hand-off and workspace-path rewriting are no longer needed and the post_clang_tidy_comments job is removed. Signed-off-by: Ramon Roche <mrpollo@gmail.com> * ci(workflows): bump action versions to clear Node 20 deprecation GitHub has deprecated the Node 20 runtime for Actions as of September 16, 2026. Bump the pinned action versions in the three poster workflows to the latest majors, all of which run on Node 24: actions/checkout v4 -> v6 actions/github-script v7 -> v8 actions/upload-artifact v4 -> v7 No behavior changes on our side: upload-artifact v5/v6/v7 only added an optional direct-file-upload mode we do not use, and checkout v5/v6 are runtime-only bumps. The security-invariant comment headers in both poster workflows are updated to reference the new version so they stay accurate. Signed-off-by: Ramon Roche <mrpollo@gmail.com> * ci(pr-posters): skip job when producer was not a pull_request event Both poster workflows previously ran on every workflow_run completion of their listed producers and then silently no-oped inside the script when the triggering producer run was a push-to-main (or any other non-PR event). That made the UI ambiguous: the job was always green, never showed the reason it did nothing, and looked like a failure whenever someone clicked in looking for the comment that was never there. Gate the job at the workflow level on github.event.workflow_run.event == 'pull_request'. Non-PR producer runs now surface as a clean "Skipped" entry in the run list, which is self-explanatory and needs no in-script summary plumbing. Signed-off-by: Ramon Roche <mrpollo@gmail.com> --------- Signed-off-by: Ramon Roche <mrpollo@gmail.com>
173 lines
6.6 KiB
Python
173 lines
6.6 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
Shared GitHub REST helpers for PX4 CI scripts.
|
|
|
|
This module is imported by the PR poster scripts under Tools/ci/. It is
|
|
NOT an executable entry point; do not run it directly.
|
|
|
|
Provides:
|
|
- fail(msg) terminates the caller with a clear error
|
|
- GitHubClient(token) thin stdlib-only GitHub REST client with
|
|
single-request and paginated helpers
|
|
|
|
Python stdlib only. No third-party dependencies.
|
|
|
|
History: extracted from Tools/ci/pr-comment-poster.py so that
|
|
pr-comment-poster.py and pr-review-poster.py share the same HTTP plumbing
|
|
without duplicating ~100 lines of request/pagination/error-handling code.
|
|
"""
|
|
|
|
import json
|
|
import sys
|
|
import typing
|
|
import urllib.error
|
|
import urllib.request
|
|
|
|
|
|
GITHUB_API = 'https://api.github.com'
|
|
DEFAULT_USER_AGENT = 'px4-ci'
|
|
API_VERSION = '2022-11-28'
|
|
|
|
|
|
def fail(msg: str) -> typing.NoReturn:
|
|
"""Print an error to stderr and exit with status 1.
|
|
|
|
Annotated NoReturn so static checkers understand control does not
|
|
continue past a fail() call.
|
|
"""
|
|
print('error: {}'.format(msg), file=sys.stderr)
|
|
sys.exit(1)
|
|
|
|
|
|
def _parse_next_link(link_header):
|
|
"""Return the URL for rel="next" from an RFC 5988 Link header, or None.
|
|
|
|
The Link header is comma-separated entries of the form:
|
|
<https://...?page=2>; rel="next", <https://...?page=5>; rel="last"
|
|
We walk each entry and return the URL of the one whose rel attribute is
|
|
"next". Accept single-quoted rel values for robustness even though
|
|
GitHub always emits double quotes.
|
|
"""
|
|
if not link_header:
|
|
return None
|
|
for part in link_header.split(','):
|
|
segs = part.strip().split(';')
|
|
if len(segs) < 2:
|
|
continue
|
|
url_seg = segs[0].strip()
|
|
if not (url_seg.startswith('<') and url_seg.endswith('>')):
|
|
continue
|
|
url = url_seg[1:-1]
|
|
for attr in segs[1:]:
|
|
attr = attr.strip()
|
|
if attr == 'rel="next"' or attr == "rel='next'":
|
|
return url
|
|
return None
|
|
|
|
|
|
class GitHubClient:
|
|
"""Minimal GitHub REST client backed by the Python stdlib.
|
|
|
|
Each instance holds a token and a user-agent so callers do not have to
|
|
thread them through every call. Methods return parsed JSON (or None for
|
|
empty responses) and raise RuntimeError with the server response body on
|
|
HTTP errors, so CI logs show what the API actually objected to.
|
|
|
|
Usage:
|
|
client = GitHubClient(token, user_agent='px4-pr-comment-poster')
|
|
body, headers = client.request('GET', 'repos/{o}/{r}/pulls/123')
|
|
for item in client.paginated('repos/{o}/{r}/pulls/123/reviews'):
|
|
...
|
|
"""
|
|
|
|
def __init__(self, token, user_agent=DEFAULT_USER_AGENT):
|
|
if not token:
|
|
raise ValueError('GitHub token is required')
|
|
self._token = token
|
|
self._user_agent = user_agent
|
|
|
|
def request(self, method, path_or_url, json_body=None):
|
|
"""GET/POST/PATCH/PUT/DELETE a single API path or absolute URL.
|
|
|
|
`path_or_url` may be either a relative API path (e.g.
|
|
"repos/PX4/PX4-Autopilot/pulls/123") or an absolute URL such as the
|
|
next-page URL returned from paginated results. Relative paths are
|
|
prefixed with the GitHub API base.
|
|
|
|
Returns (parsed_json_or_none, headers_dict). Raises RuntimeError
|
|
on HTTP or transport errors.
|
|
"""
|
|
url = self._resolve(path_or_url)
|
|
return self._do_request(method, url, json_body)
|
|
|
|
def paginated(self, path, per_page=100):
|
|
"""GET a path and follow rel="next" Link headers.
|
|
|
|
Yields items from each page's JSON array. Bumps per_page to 100
|
|
(GitHub's max) so large result sets take fewer round-trips.
|
|
Raises RuntimeError if any page response is not a JSON array.
|
|
"""
|
|
url = self._resolve(path)
|
|
sep = '&' if '?' in url else '?'
|
|
url = '{}{}per_page={}'.format(url, sep, per_page)
|
|
while url is not None:
|
|
body, headers = self._do_request('GET', url, None)
|
|
if body is None:
|
|
return
|
|
if not isinstance(body, list):
|
|
raise RuntimeError(
|
|
'expected JSON array from {}, got {}'.format(
|
|
url, type(body).__name__))
|
|
for item in body:
|
|
yield item
|
|
url = _parse_next_link(headers.get('Link'))
|
|
|
|
def _resolve(self, path_or_url):
|
|
if path_or_url.startswith('http://') or path_or_url.startswith('https://'):
|
|
return path_or_url
|
|
return '{}/{}'.format(GITHUB_API.rstrip('/'), path_or_url.lstrip('/'))
|
|
|
|
def _do_request(self, method, url, json_body):
|
|
data = None
|
|
headers = {
|
|
'Authorization': 'Bearer {}'.format(self._token),
|
|
'Accept': 'application/vnd.github+json',
|
|
# Pin the API version so GitHub deprecations don't silently
|
|
# change the response shape under us.
|
|
'X-GitHub-Api-Version': API_VERSION,
|
|
'User-Agent': self._user_agent,
|
|
}
|
|
if json_body is not None:
|
|
data = json.dumps(json_body).encode('utf-8')
|
|
headers['Content-Type'] = 'application/json; charset=utf-8'
|
|
|
|
req = urllib.request.Request(
|
|
url, data=data, method=method, headers=headers)
|
|
try:
|
|
with urllib.request.urlopen(req) as resp:
|
|
raw = resp.read()
|
|
# HTTPMessage is case-insensitive on lookup but its items()
|
|
# preserves the original case. GitHub sends "Link" with a
|
|
# capital L, which is what _parse_next_link expects.
|
|
resp_headers = dict(resp.headers.items())
|
|
if not raw:
|
|
return None, resp_headers
|
|
return json.loads(raw.decode('utf-8')), resp_headers
|
|
except urllib.error.HTTPError as e:
|
|
# GitHub error bodies are JSON with a "message" field and often
|
|
# a "documentation_url". Dump the raw body into the exception so
|
|
# the CI log shows exactly what the API objected to. A bare
|
|
# "HTTP 422" tells us nothing useful.
|
|
try:
|
|
err_body = e.read().decode('utf-8', errors='replace')
|
|
except Exception:
|
|
err_body = '(no body)'
|
|
raise RuntimeError(
|
|
'GitHub API {} {} failed: HTTP {} {}\n{}'.format(
|
|
method, url, e.code, e.reason, err_body))
|
|
except urllib.error.URLError as e:
|
|
# Network layer failure (DNS, TLS, connection reset). No HTTP
|
|
# response to parse; just surface the transport reason.
|
|
raise RuntimeError(
|
|
'GitHub API {} {} failed: {}'.format(method, url, e.reason))
|