Skip to content

Commit 9703fab

Browse files
shenxianpengclaude
andcommitted
fix: check the PR author on HEAD^2, not GitHub's merge commit
On refs/pull/N/merge HEAD is a merge commit that GitHub authored, so author-name and author-email validated "GitHub <noreply@github.com>" whatever the contributor had configured. In a PR event, pass --rev HEAD^2 (commit-check >= 2.16.0 reads that commit's recorded author) to the author checks. When HEAD^2 does not resolve, which is what a fetch-depth: 1 clone looks like, fall back to the previous behaviour and emit the same shallow-checkout warning as the commit-message path. The branch check is unaffected. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018xYa7m3qup5wyN5MaXFgf6
1 parent 4c84bff commit 9703fab

2 files changed

Lines changed: 152 additions & 5 deletions

File tree

‎main.py‎

Lines changed: 50 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,15 @@ def is_pr_event() -> bool:
193193
#: The one fix for every "history is too shallow" finding below.
194194
SHALLOW_CHECKOUT_HINT = "is actions/checkout using fetch-depth: 0?"
195195

196+
#: The pull request branch tip. On ``refs/pull/N/merge`` HEAD is a merge
197+
#: commit that GitHub authored, so its recorded author is
198+
#: ``GitHub <noreply@github.com>`` whatever the contributor configured;
199+
#: HEAD^2 is the commit the contributor actually made.
200+
PR_HEAD_REV = "HEAD^2"
201+
202+
#: The checks whose subject is a commit's recorded author.
203+
AUTHOR_FLAGS = ("--author-name", "--author-email")
204+
196205

197206
def warn_shallow_checkout(problem: str, consequence: str) -> None:
198207
"""Annotate a PR run whose clone is too shallow to do what was asked.
@@ -206,6 +215,25 @@ def warn_shallow_checkout(problem: str, consequence: str) -> None:
206215
print(f"::warning title=commit-check::{_annotation_escape(text)}")
207216

208217

218+
def pr_head_rev() -> str | None:
219+
"""Return ``HEAD^2`` when it resolves, ``None`` on a shallow clone.
220+
221+
With ``fetch-depth: 1`` the merge commit's parents are not fetched and
222+
``git rev-parse HEAD^2`` fails, so the caller has to settle for HEAD.
223+
"""
224+
try:
225+
result = subprocess.run(
226+
["git", "rev-parse", "--verify", "--quiet", PR_HEAD_REV],
227+
stdout=subprocess.PIPE,
228+
stderr=subprocess.PIPE,
229+
encoding="utf-8",
230+
check=False,
231+
)
232+
except OSError:
233+
return None
234+
return PR_HEAD_REV if result.returncode == 0 else None
235+
236+
209237
def get_pr_title() -> str | None:
210238
"""Read PR title from GitHub event payload."""
211239
if not is_pr_event():
@@ -339,13 +367,22 @@ def run_pr_message_checks(pr_messages: list[str]) -> list[ScopeResult]:
339367
return results
340368

341369

342-
def run_other_checks(args: list[str]) -> list[ScopeResult]:
343-
"""Run each non-message check (branch, author) once, as its own scope."""
370+
def run_other_checks(args: list[str], rev: str | None = None) -> list[ScopeResult]:
371+
"""Run each non-message check (branch, author) once, as its own scope.
372+
373+
``rev`` goes to the author checks only: it names the commit whose
374+
recorded author is validated (commit-check >= 2.16.0), which in a PR is
375+
the branch tip rather than GitHub's merge commit. The branch check has
376+
no commit to point at, so it never takes it.
377+
"""
344378
results: list[ScopeResult] = []
345379
for flag in args:
346380
label = CHECK_LABELS.get(flag)
347381
if label:
348-
results.append(check_scope(label, [flag]))
382+
cli_args = [flag]
383+
if rev and flag in AUTHOR_FLAGS:
384+
cli_args += ["--rev", rev]
385+
results.append(check_scope(label, cli_args))
349386
return results
350387

351388

@@ -400,7 +437,16 @@ def run_commit_check() -> tuple[int, list[ScopeResult]]:
400437
if "--message" in args:
401438
results.append(check_scope("Commit message", ["--message"]))
402439
args = [a for a in args if a != "--message"]
403-
results.extend(run_other_checks(args))
440+
rev = None
441+
if is_pr_event() and any(flag in AUTHOR_FLAGS for flag in args):
442+
rev = pr_head_rev()
443+
if rev is None:
444+
warn_shallow_checkout(
445+
f"Could not resolve {PR_HEAD_REV} for the author checks",
446+
"HEAD's author was checked instead, which on a pull request "
447+
"is GitHub's merge commit",
448+
)
449+
results.extend(run_other_checks(args, rev=rev))
404450

405451
exit_code = exit_code_for(results)
406452
return exit_code, results

‎main_test.py‎

Lines changed: 102 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -576,7 +576,7 @@ def test_non_pr_message_check_uses_commit_message_scope(self):
576576
def test_message_flag_removed_before_other_checks_in_pr(self):
577577
captured_args = []
578578

579-
def fake_other_checks(args):
579+
def fake_other_checks(args, rev=None):
580580
captured_args.extend(args)
581581
return []
582582

@@ -642,6 +642,107 @@ def test_push_without_pr_commits_does_not_warn(self):
642642
_rc, _results, output = self._run_capturing_stdout()
643643
self.assertNotIn("::warning", output)
644644

645+
@staticmethod
646+
def _fake_git_and_cli(head2_resolves: bool):
647+
"""subprocess.run stand-in: answers rev-parse and the CLI alike."""
648+
commands: list[list[str]] = []
649+
650+
def run(command, **_kwargs):
651+
commands.append(command)
652+
if command[:2] == ["git", "rev-parse"]:
653+
return MagicMock(
654+
returncode=0 if head2_resolves else 1,
655+
stdout="abc123\n" if head2_resolves else "",
656+
)
657+
check = command[3].lstrip("-").replace("-", "_")
658+
return MagicMock(returncode=0, stdout=json_output(make_check(check)))
659+
660+
return run, commands
661+
662+
def test_pr_author_checks_read_the_branch_tip(self):
663+
"""On refs/pull/N/merge HEAD's author is GitHub, not the contributor."""
664+
run, commands = self._fake_git_and_cli(head2_resolves=True)
665+
with (
666+
patch("main.MESSAGE_ENABLED", False),
667+
patch("main.BRANCH_ENABLED", True),
668+
patch("main.AUTHOR_NAME_ENABLED", True),
669+
patch("main.AUTHOR_EMAIL_ENABLED", True),
670+
patch("main.is_pr_event", return_value=True),
671+
patch("main.subprocess.run", side_effect=run),
672+
):
673+
rc, results, output = self._run_capturing_stdout()
674+
self.assertEqual(rc, 0)
675+
self.assertEqual(
676+
[s.label for s in results], ["Branch", "Author name", "Author email"]
677+
)
678+
self.assertIn(["git", "rev-parse", "--verify", "--quiet", "HEAD^2"], commands)
679+
self.assertIn(
680+
["commit-check", "--format", "json", "--author-name", "--rev", "HEAD^2"],
681+
commands,
682+
)
683+
self.assertIn(
684+
["commit-check", "--format", "json", "--author-email", "--rev", "HEAD^2"],
685+
commands,
686+
)
687+
# The branch check has no commit to point at.
688+
self.assertIn(["commit-check", "--format", "json", "--branch"], commands)
689+
self.assertNotIn("::warning", output)
690+
691+
def test_pr_author_checks_fall_back_to_head_on_shallow_clone(self):
692+
run, commands = self._fake_git_and_cli(head2_resolves=False)
693+
with (
694+
patch("main.MESSAGE_ENABLED", False),
695+
patch("main.BRANCH_ENABLED", False),
696+
patch("main.AUTHOR_NAME_ENABLED", True),
697+
patch("main.AUTHOR_EMAIL_ENABLED", False),
698+
patch("main.is_pr_event", return_value=True),
699+
patch("main.subprocess.run", side_effect=run),
700+
):
701+
rc, results, output = self._run_capturing_stdout()
702+
self.assertEqual(rc, 0)
703+
self.assertIn(["commit-check", "--format", "json", "--author-name"], commands)
704+
self.assertFalse([c for c in commands if "--rev" in c], commands)
705+
warning = [ln for ln in output.splitlines() if ln.startswith("::warning")]
706+
self.assertEqual(len(warning), 1, output)
707+
self.assertTrue(warning[0].startswith("::warning title=commit-check::"))
708+
self.assertIn("Could not resolve HEAD^2", warning[0])
709+
self.assertIn("is actions/checkout using fetch-depth: 0?", warning[0])
710+
711+
def test_push_author_checks_never_pass_rev(self):
712+
run, commands = self._fake_git_and_cli(head2_resolves=True)
713+
with (
714+
patch("main.MESSAGE_ENABLED", False),
715+
patch("main.BRANCH_ENABLED", False),
716+
patch("main.AUTHOR_NAME_ENABLED", True),
717+
patch("main.AUTHOR_EMAIL_ENABLED", True),
718+
patch("main.is_pr_event", return_value=False),
719+
patch("main.subprocess.run", side_effect=run),
720+
):
721+
_rc, _results, output = self._run_capturing_stdout()
722+
self.assertFalse([c for c in commands if c[0] == "git"], commands)
723+
self.assertFalse([c for c in commands if "--rev" in c], commands)
724+
self.assertNotIn("::warning", output)
725+
726+
727+
class TestPrHeadRev(unittest.TestCase):
728+
def test_resolving_head2_returns_the_revision(self):
729+
with patch(
730+
"main.subprocess.run", return_value=MagicMock(returncode=0)
731+
) as mock_run:
732+
self.assertEqual(main.pr_head_rev(), "HEAD^2")
733+
self.assertEqual(
734+
mock_run.call_args[0][0],
735+
["git", "rev-parse", "--verify", "--quiet", "HEAD^2"],
736+
)
737+
738+
def test_shallow_clone_returns_none(self):
739+
with patch("main.subprocess.run", return_value=MagicMock(returncode=1)):
740+
self.assertIsNone(main.pr_head_rev())
741+
742+
def test_missing_git_returns_none(self):
743+
with patch("main.subprocess.run", side_effect=OSError("no git")):
744+
self.assertIsNone(main.pr_head_rev())
745+
645746

646747
class TestCommitCheckVersionPin(unittest.TestCase):
647748
"""The warn rendering is inert against an engine that never emits it.

0 commit comments

Comments
 (0)