Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 51 additions & 13 deletions action/publish.py
Original file line number Diff line number Diff line change
Expand Up @@ -173,19 +173,16 @@ def add_pr_comments(results: list[model.ScopeResult]) -> int:
"See https://github.com/commit-check/commit-check-action/blob/main/docs/fork-pr-comments.md"
)
print(f"::warning::{msg}")
if inputs.JOB_SUMMARY_ENABLED and inputs.GITHUB_STEP_SUMMARY:
with open(inputs.GITHUB_STEP_SUMMARY, "a", encoding="utf-8") as f:
f.write(
"\n---\n"
"### \u2139\ufe0f PR Comment Skipped\n\n"
"Pull requests from forked repositories cannot write comments "
"using the `pull_request` event because `GITHUB_TOKEN` has "
"read-only permissions. The report above and the annotations "
"on the run page are unaffected.\n\n"
"> **\U0001f4a1 Tip:** see "
"[Fork pull requests]"
"(https://github.com/commit-check/commit-check-action/blob/main/docs/fork-pr-comments.md).\n"
)
_add_summary_note(
"PR Comment Skipped",
"Pull requests from forked repositories cannot write comments "
"using the `pull_request` event because `GITHUB_TOKEN` has "
"read-only permissions. The report above and the annotations "
"on the run page are unaffected.\n\n"
"> **\U0001f4a1 Tip:** see "
"[Fork pull requests]"
"(https://github.com/commit-check/commit-check-action/blob/main/docs/fork-pr-comments.md).\n",
)
return 0

try:
Expand All @@ -199,6 +196,9 @@ def add_pr_comments(results: list[model.ScopeResult]) -> int:
print(f"::warning::Unable to post PR comment: {e}", file=sys.stderr)
return 0

# Set once the report is on the pull request, so a refusal while deleting
# an old copy does not get the summary to say the comment never came.
posted = False
try:
token = os.getenv("GITHUB_TOKEN")
repo_name = os.getenv("GITHUB_REPOSITORY")
Expand All @@ -224,6 +224,7 @@ def add_pr_comments(results: list[model.ScopeResult]) -> int:
return model.exit_code_for(results)
print(f"Updating the last comment on PR #{pr_number}.")
target.edit(pr_comment_body)
posted = True
for comment in stale:
print(f"Deleting an old comment on PR #{pr_number}.")
comment.delete()
Expand All @@ -245,6 +246,25 @@ def add_pr_comments(results: list[model.ScopeResult]) -> int:
f"Error: {detail or e}",
file=sys.stderr,
)
# The annotation alone is easy to miss on a green run: the
# summary is where a reader looks for the comment that never came.
# A rate limit also answers 403, and more permissions do not fix
# it, so that case keeps just the warning.
rate_limited = "rate limit" in (detail or "").lower()
if not posted and not rate_limited:
_add_summary_note(
"PR Comment Not Posted",
"GitHub refused the comment (403 Forbidden): this job's "
"`GITHUB_TOKEN` cannot write to pull requests. Grant it in "
"the workflow:\n\n"
"```yaml\n"
"permissions:\n"
" contents: read\n"
" pull-requests: write\n"
"```\n\n"
"The report above and the annotations on the run page are "
"unaffected.\n",
)
return 0
# Annotated, not just printed: posting the comment is best-effort and
# never fails the step, so without an annotation the run is green, the
Expand All @@ -256,6 +276,24 @@ def add_pr_comments(results: list[model.ScopeResult]) -> int:
return 0


def _add_summary_note(title: str, body: str) -> None:
"""Append a note about the PR comment to the job summary, if one is written.

The report ends on its footer line with no newline. A ``---`` straight
under a text line is a setext underline, which turned that footer into a
heading, so the rule gets a blank line on each side.
"""
if not (inputs.JOB_SUMMARY_ENABLED and inputs.GITHUB_STEP_SUMMARY):
return
# Called from exception handlers: a failed write must stay best-effort
# rather than escape them and fail the step.
try:
with open(inputs.GITHUB_STEP_SUMMARY, "a", encoding="utf-8") as f:
f.write(f"\n\n---\n\n### \u2139\ufe0f {title}\n\n{body}")
except OSError as e:
print(f"::warning::Unable to write to the job summary: {e}", file=sys.stderr)


def ai_tools_found(results: list[model.ScopeResult]) -> list[str]:
"""Every AI tool found in the pull request, sorted.

Expand Down
11 changes: 9 additions & 2 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,17 @@

def _reconfigure_io() -> None:
"""Reconfigure stdout/stderr to UTF-8 so emoji and check marks never
crash on runners with legacy encodings (e.g. cp1252 on Windows)."""
crash on runners with legacy encodings (e.g. cp1252 on Windows).

Both streams are also line-buffered. On a runner stdout is a pipe, so it
was block-buffered while stderr was not: every stderr warning landed
above the whole report in the step log, and stdout lines such as
"Creating a new comment" came out last, after the warning saying the
comment had failed.
"""
for stream in (sys.stdout, sys.stderr):
if hasattr(stream, "reconfigure"):
stream.reconfigure(encoding="utf-8", errors="replace")
stream.reconfigure(encoding="utf-8", errors="replace", line_buffering=True)


def log_error_and_exit(ret_code: int) -> None:
Expand Down
9 changes: 3 additions & 6 deletions tests/main_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,12 +94,9 @@ def reconfigure(self, **kwargs):
patch.object(sys, "stderr", fake_err),
):
main._reconfigure_io()
self.assertEqual(
fake_out.reconfigured, {"encoding": "utf-8", "errors": "replace"}
)
self.assertEqual(
fake_err.reconfigured, {"encoding": "utf-8", "errors": "replace"}
)
expected = {"encoding": "utf-8", "errors": "replace", "line_buffering": True}
self.assertEqual(fake_out.reconfigured, expected)
self.assertEqual(fake_err.reconfigured, expected)

def test_streams_without_reconfigure_are_ignored(self):
class NoopStream:
Expand Down
83 changes: 81 additions & 2 deletions tests/publish_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -391,9 +391,9 @@ class TestAddPrCommentsFailures(unittest.TestCase):
on the page says why.
"""

def _run(self, side_effect):
def _run(self, side_effect, summary_path=None, comments=()):
mock_pull_request = MagicMock()
mock_pull_request.get_comments.return_value = []
mock_pull_request.get_comments.return_value = list(comments)
mock_pull_request.create_comment.side_effect = side_effect
mock_repo = MagicMock()
mock_repo.get_issue.return_value = mock_pull_request
Expand All @@ -415,6 +415,8 @@ def _run(self, side_effect):
},
),
patch.dict(sys.modules, {"github": github_module}),
patch("action.inputs.JOB_SUMMARY_ENABLED", summary_path is not None),
patch("action.inputs.GITHUB_STEP_SUMMARY", summary_path),
patch("builtins.print") as mock_print,
):
rc = publish.add_pr_comments([fail_scope()])
Expand Down Expand Up @@ -451,6 +453,83 @@ def test_forbidden_with_a_non_mapping_payload_still_warns(self):
self.assertIn("pull-requests: write", warning)
self.assertIn("status 403", warning)

def test_forbidden_explains_the_missing_comment_in_the_summary(self):
# A 403 leaves the run green with no comment; the annotation is easy
# to miss, so the summary says what happened and how to grant it.
summary_path = os.path.join(tempfile.mkdtemp(), "summary.txt")
rc, _ = self._run(
_StubGithubException(403, {"message": "Resource not accessible"}),
summary_path=summary_path,
)
self.assertEqual(rc, 0)
with open(summary_path, encoding="utf-8") as f:
content = f.read()
self.assertIn("PR Comment Not Posted", content)
self.assertIn("pull-requests: write", content)
self.assertNotIn("fork", content)

def test_summary_note_does_not_turn_the_footer_into_a_heading(self):
# The report ends on its footer line; "---" right under a text line
# is a setext underline, so the rule needs a blank line above it.
summary_path = os.path.join(tempfile.mkdtemp(), "summary.txt")
with open(summary_path, "w", encoding="utf-8") as f:
f.write("<sub>Checked by Commit Check</sub>")
self._run(_StubGithubException(403, None), summary_path=summary_path)
with open(summary_path, encoding="utf-8") as f:
content = f.read()
self.assertIn("</sub>\n\n---\n\n### ", content)

def test_forbidden_without_a_summary_writes_no_note(self):
rc, _ = self._run(_StubGithubException(403, None))
self.assertEqual(rc, 0)

def test_rate_limit_refusal_adds_no_permissions_note(self):
# A rate limit also answers 403; granting permissions cannot fix it.
summary_path = os.path.join(tempfile.mkdtemp(), "summary.txt")
rc, printed = self._run(
_StubGithubException(403, {"message": "API rate limit exceeded"}),
summary_path=summary_path,
)
self.assertEqual(rc, 0)
self.assertTrue(any("::warning::" in w for w in printed), printed)
self.assertFalse(os.path.exists(summary_path))

def test_refused_cleanup_after_an_update_adds_no_note(self):
# The report was edited in place; only deleting an old copy failed.
def own(body):
comment = MagicMock()
comment.body = f"{render.COMMENT_MARKER}\n{body}"
comment.user.type = "Bot"
return comment

old, target = own("old"), own("stale report")
old.delete.side_effect = _StubGithubException(403, None)
summary_path = os.path.join(tempfile.mkdtemp(), "summary.txt")
rc, _ = self._run(None, summary_path=summary_path, comments=[old, target])
self.assertEqual(rc, 0)
target.edit.assert_called_once()
self.assertFalse(os.path.exists(summary_path))

def test_a_failed_summary_write_stays_best_effort(self):
# The note is written from an exception handler; an OSError there
# must not escape and fail the step.
missing_dir = os.path.join(tempfile.mkdtemp(), "gone", "summary.txt")
rc, printed = self._run(
_StubGithubException(403, None), summary_path=missing_dir
)
self.assertEqual(rc, 0)
self.assertTrue(
any("Unable to write to the job summary" in w for w in printed), printed
)

def test_other_api_errors_add_no_summary_note(self):
summary_path = os.path.join(tempfile.mkdtemp(), "summary.txt")
rc, _ = self._run(
_StubGithubException(500, {"message": "boom"}), summary_path=summary_path
)
self.assertEqual(rc, 0)
self.assertFalse(os.path.exists(summary_path))

def test_other_api_errors_are_annotated(self):
rc, printed = self._run(_StubGithubException(500, {"message": "boom"}))
self.assertEqual(rc, 0)
Expand Down
Loading