Skip to content

Commit 93ffdc6

Browse files
authored
fix(review): show the cause of Review Readiness failures in annotations (#5575)
* feat(review): annotate Review Readiness failures with their cause Signed-off-by: Jim Meyer <jimeyer@nvidia.com> * fix(review): explain how to resolve Review Readiness label failures Signed-off-by: Jim Meyer <jimeyer@nvidia.com> * fix(review): correct label failure guidance for missing areas and roster edits Signed-off-by: Jim Meyer <jimeyer@nvidia.com> * fix(ci): name the failing step in Review Readiness errors Label failures now say what is wrong with this PR's labels, and GitHub API failures name the step that failed, such as requesting reviewers. Signed-off-by: Jim Meyer <jimeyer@nvidia.com> * fix(review): report unknown area and topic labels as invalid A label missing from REVIEWERS.md is treated as a wrong label on the PR, so the message asks the author to replace it rather than edit the roster. Signed-off-by: Jim Meyer <jimeyer@nvidia.com> * fix(review): tell authors to remove invalid area and topic labels Signed-off-by: Jim Meyer <jimeyer@nvidia.com> --------- Signed-off-by: Jim Meyer <jimeyer@nvidia.com>
1 parent d85ff58 commit 93ffdc6

2 files changed

Lines changed: 240 additions & 4 deletions

File tree

‎tasks/scripts/check_review_readiness.py‎

Lines changed: 81 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020

2121
import argparse
2222
import json
23+
import os
2324
import re
2425
import subprocess
2526
import sys
@@ -37,6 +38,66 @@
3738
}"""
3839

3940

41+
class LabelRoutingError(ValueError):
42+
"""The PR's area or topic labels prevent requesting reviewers."""
43+
44+
45+
def _api_action(method: str, path: str) -> str:
46+
"""Name the step a failed `gh api` call was performing."""
47+
if path.endswith("/requested_reviewers"):
48+
return (
49+
"Removing reviewer requests"
50+
if method == "DELETE"
51+
else "Requesting reviewers"
52+
)
53+
if path.endswith("/labels") and method == "POST":
54+
return "Adding labels"
55+
if method == "GET":
56+
return "Reading the PR from GitHub"
57+
return "A GitHub API call"
58+
59+
60+
def _escape_annotation(text: str, *, prop: bool = False) -> str:
61+
"""Escape text for a GitHub Actions workflow command."""
62+
text = text.replace("%", "%25").replace("\r", "%0D").replace("\n", "%0A")
63+
if prop:
64+
text = text.replace(":", "%3A").replace(",", "%2C")
65+
return text
66+
67+
68+
def describe_failure(exc: Exception) -> tuple[str, str]:
69+
"""Return a short category and an actionable message for a failure."""
70+
if isinstance(exc, LabelRoutingError):
71+
return "PR labels", str(exc)
72+
if isinstance(exc, subprocess.CalledProcessError):
73+
command = [str(part) for part in exc.cmd]
74+
method = "GET"
75+
if "--method" in command[:-1]:
76+
method = command[command.index("--method") + 1]
77+
path = command[2] if len(command) > 2 else ""
78+
message = (
79+
f"{_api_action(method, path)} failed with a GitHub API error: "
80+
f"gh api {method} {path}"
81+
)
82+
detail = (exc.stderr or "").strip()
83+
if detail:
84+
message += f": {detail}"
85+
message += f" (exit status {exc.returncode})"
86+
return "GitHub API error", message
87+
return "error", str(exc)
88+
89+
90+
def report_failure(exc: Exception, *, stream=None, env=None) -> None:
91+
"""Print the failure, plus an Actions error annotation when in Actions."""
92+
stream = sys.stderr if stream is None else stream
93+
env = os.environ if env is None else env
94+
category, message = describe_failure(exc)
95+
print(f"Review readiness: {message}", file=stream)
96+
if env.get("GITHUB_ACTIONS") == "true":
97+
title = _escape_annotation(f"Review Readiness: {category}", prop=True)
98+
print(f"::error title={title}::{_escape_annotation(message)}", file=stream)
99+
100+
40101
@dataclass(frozen=True)
41102
class ReviewPlan:
42103
add: tuple[str, ...]
@@ -94,11 +155,27 @@ def parse_reviewers(markdown: str) -> dict[str, set[str]]:
94155
def select_reviewers(categories: dict[str, set[str]], labels: set[str]) -> set[str]:
95156
"""Return matching handles for one primary area and any number of topics."""
96157
relevant = {label for label in labels if label.startswith(("area:", "topic:"))}
97-
if sum(label.startswith("area:") for label in relevant) != 1:
98-
raise ValueError("a ready PR must have exactly one area label")
158+
areas = sorted(label for label in relevant if label.startswith("area:"))
159+
if not areas:
160+
raise LabelRoutingError(
161+
"This PR has no area label. A ready PR needs exactly one; add one."
162+
)
163+
if len(areas) > 1:
164+
raise LabelRoutingError(
165+
f"This PR has more than one area label: {', '.join(areas)}. "
166+
"A ready PR needs exactly one; remove the others."
167+
)
99168
unknown = relevant - categories.keys()
100169
if unknown:
101-
raise ValueError("unknown area/topic labels: " + ", ".join(sorted(unknown)))
170+
names = ", ".join(sorted(unknown))
171+
if len(unknown) == 1:
172+
raise LabelRoutingError(
173+
f"There is an invalid area or topic label on this PR: {names}. "
174+
"Remove it."
175+
)
176+
raise LabelRoutingError(
177+
f"There are invalid area and topic labels on this PR: {names}. Remove them."
178+
)
102179
return set().union(*(categories[label] for label in relevant))
103180

104181

@@ -337,7 +414,7 @@ def main(argv: list[str] | None = None) -> int:
337414
TypeError,
338415
subprocess.CalledProcessError,
339416
) as exc:
340-
print(f"Review readiness: {exc}", file=sys.stderr)
417+
report_failure(exc)
341418
return 1
342419
print(
343420
json.dumps(

‎tasks/scripts/check_review_readiness_test.py‎

Lines changed: 159 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import contextlib
99
import io
1010
import json
11+
import os
1112
import subprocess
1213
import tempfile
1314
import unittest
@@ -138,6 +139,48 @@ def test_selects_all_matching_members_deduplicated(self):
138139
{"alice", "bob", "carol"},
139140
)
140141

142+
def test_multiple_area_labels_message(self):
143+
with self.assertRaises(routing.LabelRoutingError) as caught:
144+
routing.select_reviewers(CATEGORIES, {"area:runtime", "area:build"})
145+
self.assertEqual(
146+
str(caught.exception),
147+
"This PR has more than one area label: area:build, area:runtime. "
148+
"A ready PR needs exactly one; remove the others.",
149+
)
150+
151+
def test_missing_area_label_message(self):
152+
with self.assertRaises(routing.LabelRoutingError) as caught:
153+
routing.select_reviewers(CATEGORIES, {"topic:policy"})
154+
self.assertEqual(
155+
str(caught.exception),
156+
"This PR has no area label. A ready PR needs exactly one; add one.",
157+
)
158+
159+
def test_unknown_label_message(self):
160+
with self.assertRaises(routing.LabelRoutingError) as caught:
161+
routing.select_reviewers(
162+
CATEGORIES, {"area:runtime", "topic:nope", "topic:zzz"}
163+
)
164+
self.assertEqual(
165+
str(caught.exception),
166+
"There are invalid area and topic labels on this PR: topic:nope, "
167+
"topic:zzz. Remove them.",
168+
)
169+
170+
def test_single_unknown_label_message(self):
171+
with self.assertRaises(routing.LabelRoutingError) as caught:
172+
routing.select_reviewers(CATEGORIES, {"area:runtime", "topic:nope"})
173+
self.assertEqual(
174+
str(caught.exception),
175+
"There is an invalid area or topic label on this PR: topic:nope. "
176+
"Remove it.",
177+
)
178+
179+
def test_area_count_is_checked_before_unknown_labels(self):
180+
with self.assertRaises(routing.LabelRoutingError) as caught:
181+
routing.select_reviewers(CATEGORIES, {"area:nope", "area:other"})
182+
self.assertIn("more than one area label", str(caught.exception))
183+
141184
def test_requires_one_known_area_and_known_topics(self):
142185
for labels in (
143186
set(),
@@ -683,7 +726,123 @@ def test_label_write_failure_does_not_request_reviewers(self):
683726
load.assert_not_called()
684727

685728

729+
class FailureReportTests(unittest.TestCase):
730+
GH_COMMAND = (
731+
"gh",
732+
"api",
733+
"repos/o/r/pulls/42/requested_reviewers",
734+
"--method",
735+
"POST",
736+
"--input",
737+
"-",
738+
)
739+
740+
def test_escape_data_and_property(self):
741+
self.assertEqual(routing._escape_annotation("a%b\r\nc"), "a%25b%0D%0Ac")
742+
self.assertEqual(routing._escape_annotation("x:y,z", prop=True), "x%3Ay%2Cz")
743+
744+
def test_api_failure_includes_method_path_status_and_stderr(self):
745+
error = subprocess.CalledProcessError(
746+
1,
747+
self.GH_COMMAND,
748+
stderr="gh: Reviews may only be requested from collaborators. (HTTP 422)\n",
749+
)
750+
category, message = routing.describe_failure(error)
751+
self.assertEqual(category, "GitHub API error")
752+
self.assertTrue(
753+
message.startswith("Requesting reviewers failed with a GitHub API error"),
754+
message,
755+
)
756+
self.assertIn("POST repos/o/r/pulls/42/requested_reviewers", message)
757+
self.assertIn("exit status 1", message)
758+
self.assertIn("HTTP 422", message)
759+
self.assertNotIn("--input", message)
760+
761+
def test_api_failure_with_empty_stderr(self):
762+
for stderr in (None, "", " \n"):
763+
error = subprocess.CalledProcessError(1, self.GH_COMMAND, stderr=stderr)
764+
_, message = routing.describe_failure(error)
765+
self.assertNotIn("None", message)
766+
self.assertTrue(message.endswith("(exit status 1)"), message)
767+
768+
def test_get_is_the_default_method(self):
769+
error = subprocess.CalledProcessError(
770+
1, ["gh", "api", "repos/o/r/pulls/42", "--method", "GET"], stderr="x"
771+
)
772+
_, message = routing.describe_failure(error)
773+
self.assertIn("GET repos/o/r/pulls/42", message)
774+
775+
def test_api_failure_names_the_action(self):
776+
pull = "repos/o/r/pulls/42"
777+
cases = (
778+
("POST", f"{pull}/requested_reviewers", "Requesting reviewers"),
779+
("DELETE", f"{pull}/requested_reviewers", "Removing reviewer requests"),
780+
("POST", "repos/o/r/issues/42/labels", "Adding labels"),
781+
("GET", pull, "Reading the PR from GitHub"),
782+
)
783+
for method, path, action in cases:
784+
error = subprocess.CalledProcessError(
785+
1, ["gh", "api", path, "--method", method], stderr="x"
786+
)
787+
with self.subTest(method=method, path=path):
788+
_, message = routing.describe_failure(error)
789+
self.assertTrue(
790+
message.startswith(f"{action} failed with a GitHub API error"),
791+
message,
792+
)
793+
794+
def test_label_error_category(self):
795+
self.assertEqual(
796+
routing.describe_failure(routing.LabelRoutingError("x")),
797+
("PR labels", "x"),
798+
)
799+
800+
def test_other_value_error_is_generic(self):
801+
text = "PR routing changed; rerun reconciliation"
802+
self.assertEqual(routing.describe_failure(ValueError(text)), ("error", text))
803+
804+
def test_annotation_only_in_actions(self):
805+
error = routing.LabelRoutingError("bad 100%\nlabel")
806+
actions, local = io.StringIO(), io.StringIO()
807+
routing.report_failure(error, stream=actions, env={"GITHUB_ACTIONS": "true"})
808+
routing.report_failure(error, stream=local, env={})
809+
self.assertEqual(
810+
actions.getvalue(),
811+
"Review readiness: bad 100%\nlabel\n"
812+
"::error title=Review Readiness%3A PR labels::bad 100%25%0Alabel\n",
813+
)
814+
self.assertEqual(local.getvalue(), "Review readiness: bad 100%\nlabel\n")
815+
816+
def test_cli_failure_in_actions_prints_annotation(self):
817+
errors = io.StringIO()
818+
with (
819+
mock.patch.dict(os.environ, {"GITHUB_ACTIONS": "true"}),
820+
mock.patch.object(
821+
routing,
822+
"check_review_readiness",
823+
side_effect=routing.LabelRoutingError("boom"),
824+
),
825+
tempfile.TemporaryDirectory() as directory,
826+
contextlib.redirect_stderr(errors),
827+
):
828+
path = Path(directory) / "REVIEWERS.md"
829+
path.write_text(DOCUMENT, encoding="utf-8")
830+
result = routing.main(
831+
["--reviewers", str(path), "--repo", REPO, "--pr", "42"]
832+
)
833+
self.assertEqual(result, 1)
834+
self.assertIn(
835+
"::error title=Review Readiness%3A PR labels::boom", errors.getvalue()
836+
)
837+
838+
686839
class CliTests(unittest.TestCase):
840+
def setUp(self):
841+
patcher = mock.patch.dict(os.environ)
842+
patcher.start()
843+
self.addCleanup(patcher.stop)
844+
os.environ.pop("GITHUB_ACTIONS", None)
845+
687846
def test_emits_plan_and_passes_apply_option(self):
688847
with tempfile.TemporaryDirectory() as directory:
689848
path = Path(directory) / "REVIEWERS.md"

0 commit comments

Comments
 (0)