Skip to content

Commit 840a41a

Browse files
committed
fix: pipe each pull request commit with its own author
1 parent 48ea848 commit 840a41a

2 files changed

Lines changed: 126 additions & 22 deletions

File tree

‎main.py‎

Lines changed: 26 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -311,6 +311,23 @@ def _rev_resolves(rev: str) -> bool:
311311
return result.returncode == 0
312312

313313

314+
def _local_author(sha: str) -> tuple[str, str] | None:
315+
"""Author (name, email) of a commit the clone holds, or ``None``."""
316+
try:
317+
result = subprocess.run(
318+
["git", "show", "-s", "--format=%an%x1f%ae", sha],
319+
capture_output=True,
320+
encoding="utf-8",
321+
check=False,
322+
)
323+
except OSError:
324+
return None
325+
name, sep, email = result.stdout.strip("\n").partition("\x1f")
326+
if result.returncode != 0 or not sep:
327+
return None
328+
return name, email
329+
330+
314331
def _fetch_commit(sha: str) -> bool:
315332
"""Fetch one commit, without its history, into a clone that lacks it."""
316333
try:
@@ -653,23 +670,22 @@ def check_scope(
653670
def run_pr_message_checks(pr_commits: list[Commit]) -> list[ScopeResult]:
654671
"""Check each PR commit individually via commit-check --message.
655672
656-
A commit the clone holds is checked by its hash (``--rev``), so the CLI
657-
reads its message and its own author: the AI author rule (CC017) and
673+
The raw message is piped in, so every commit is read the same way
674+
whether the clone holds it or only the API listed it. Its own author
675+
goes with it as git's author variables, which is where the CLI reads the
676+
author of a piped message: the AI author rule (CC017) and
658677
``ignore_authors`` then judge that commit's author, not whoever HEAD or
659-
the runner's git config names. A commit listed only by the API is piped
660-
in, with the author the API recorded passed as git's author variables.
678+
the runner's git config names.
661679
"""
662680
results: list[ScopeResult] = []
663681
total = len(pr_commits)
664682
for index, (sha, msg) in enumerate(pr_commits, start=1):
665683
label = f"Commit {index}/{total}"
666-
if sha and _rev_resolves(sha):
667-
results.append(check_scope(label, ["--message", "--rev", sha], sha=sha))
668-
continue
684+
author = API_AUTHORS.get(sha) or (_local_author(sha) if sha else None)
669685
env = None
670-
if sha in API_AUTHORS:
671-
name, email = API_AUTHORS[sha]
672-
env = {"GIT_AUTHOR_NAME": name, "GIT_AUTHOR_EMAIL": email}
686+
if author:
687+
names = ("GIT_AUTHOR_NAME", "GIT_AUTHOR_EMAIL")
688+
env = {key: value for key, value in zip(names, author) if value} or None
673689
results.append(
674690
check_scope(label, ["--message"], input_text=msg, sha=sha, env=env)
675691
)

‎main_test.py‎

Lines changed: 100 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
11
"""Unit tests for main.py."""
22

3+
import functools
34
import importlib.metadata
45
import io
56
import json
67
import os
78
import re
89
import runpy
910
import shutil
11+
import subprocess
1012
import sys
1113
import tempfile
1214
import unittest
@@ -390,32 +392,55 @@ def test_invalid_json_falls_back_to_raw_text(self):
390392

391393

392394
class TestRunPrMessageChecks(unittest.TestCase):
393-
"""Commits the clone lacks are piped in; the rest are checked by hash."""
395+
"""Each commit's raw message is piped in, with that commit's own author."""
394396

395397
def setUp(self):
396-
resolves = patch("main._rev_resolves", return_value=False)
397-
resolves.start()
398-
self.addCleanup(resolves.stop)
398+
local = patch("main._local_author", return_value=None)
399+
self.local_author = local.start()
400+
self.addCleanup(local.stop)
399401
main.API_AUTHORS.clear()
400402
self.addCleanup(main.API_AUTHORS.clear)
401403

402-
def test_a_commit_in_the_clone_is_checked_by_its_hash(self):
403-
"""The CLI then reads that commit's own author (CC017, ignore_authors)."""
404+
def test_a_commit_in_the_clone_carries_its_own_author(self):
405+
"""The raw message is still piped, so it reads as before (no --rev)."""
406+
self.local_author.return_value = ("Renovate Bot", "bot@renovateapp.com")
404407
mock_result = MagicMock(returncode=0, stdout=json_output(make_check("message")))
405-
with (
406-
patch("main._rev_resolves", return_value=True),
407-
patch("main.subprocess.run", return_value=mock_result) as mock_run,
408-
):
408+
with patch("main.subprocess.run", return_value=mock_result) as mock_run:
409409
scopes = main.run_pr_message_checks([(SHA_A, "fix: something")])
410410
self.assertEqual(scopes[0].status, "pass")
411411
self.assertEqual(scopes[0].sha, SHA_A)
412+
self.local_author.assert_called_once_with(SHA_A)
412413
self.assertEqual(
413414
mock_run.call_args[0][0],
414-
["commit-check", "--format", "json", "--message", "--rev", SHA_A],
415+
["commit-check", "--format", "json", "--message"],
415416
)
416-
self.assertIsNone(mock_run.call_args[1]["input"])
417+
self.assertEqual(mock_run.call_args[1]["input"], "fix: something")
418+
env = mock_run.call_args[1]["env"]
419+
self.assertEqual(env["GIT_AUTHOR_NAME"], "Renovate Bot")
420+
self.assertEqual(env["GIT_AUTHOR_EMAIL"], "bot@renovateapp.com")
421+
422+
def test_a_blank_author_field_is_left_to_git(self):
423+
self.local_author.return_value = ("Renovate Bot", "")
424+
mock_result = MagicMock(returncode=0, stdout=json_output(make_check("message")))
425+
with patch("main.subprocess.run", return_value=mock_result) as mock_run:
426+
main.run_pr_message_checks([(SHA_A, "fix: something")])
427+
env = mock_run.call_args[1]["env"]
428+
self.assertEqual(env["GIT_AUTHOR_NAME"], "Renovate Bot")
429+
self.assertNotEqual(env.get("GIT_AUTHOR_EMAIL"), "")
430+
431+
def test_no_author_at_all_passes_no_environment(self):
432+
self.local_author.return_value = ("", "")
433+
mock_result = MagicMock(returncode=0, stdout=json_output(make_check("message")))
434+
with patch("main.subprocess.run", return_value=mock_result) as mock_run:
435+
main.run_pr_message_checks([(SHA_A, "fix: something")])
417436
self.assertIsNone(mock_run.call_args[1]["env"])
418437

438+
def test_a_commit_without_a_hash_is_not_looked_up(self):
439+
mock_result = MagicMock(returncode=0, stdout=json_output(make_check("message")))
440+
with patch("main.subprocess.run", return_value=mock_result):
441+
main.run_pr_message_checks([("", "fix: something")])
442+
self.local_author.assert_not_called()
443+
419444
def test_an_api_listed_commit_carries_its_author(self):
420445
"""No commit to read, so the API's author goes in git's variables."""
421446
main.API_AUTHORS[SHA_A] = ("google-labs-jules[bot]", "jules@example.com")
@@ -490,6 +515,69 @@ def test_empty_list(self):
490515
mock_run.assert_not_called()
491516

492517

518+
class TestLocalAuthor(unittest.TestCase):
519+
"""The author of a commit the clone holds, read from git."""
520+
521+
def test_reads_name_and_email(self):
522+
result = MagicMock(returncode=0, stdout="Jane Dev\x1fjane@example.com\n")
523+
with patch("main.subprocess.run", return_value=result) as mock_run:
524+
self.assertEqual(
525+
main._local_author(SHA_A), ("Jane Dev", "jane@example.com")
526+
)
527+
self.assertEqual(
528+
mock_run.call_args[0][0],
529+
["git", "show", "-s", "--format=%an%x1f%ae", SHA_A],
530+
)
531+
532+
def test_a_commit_git_cannot_show_has_no_author(self):
533+
result = MagicMock(returncode=128, stdout="")
534+
with patch("main.subprocess.run", return_value=result):
535+
self.assertIsNone(main._local_author(SHA_A))
536+
537+
def test_output_without_the_separator_has_no_author(self):
538+
result = MagicMock(returncode=0, stdout="unexpected\n")
539+
with patch("main.subprocess.run", return_value=result):
540+
self.assertIsNone(main._local_author(SHA_A))
541+
542+
def test_missing_git_has_no_author(self):
543+
with patch("main.subprocess.run", side_effect=OSError("no git")):
544+
self.assertIsNone(main._local_author(SHA_A))
545+
546+
def test_reads_a_real_commit(self):
547+
with tempfile.TemporaryDirectory() as repo:
548+
env = {
549+
**os.environ,
550+
"GIT_AUTHOR_NAME": "Renovate Bot",
551+
"GIT_AUTHOR_EMAIL": "bot@renovateapp.com",
552+
"GIT_COMMITTER_NAME": "Renovate Bot",
553+
"GIT_COMMITTER_EMAIL": "bot@renovateapp.com",
554+
}
555+
run = functools.partial(
556+
subprocess.run, cwd=repo, env=env, check=True, capture_output=True
557+
)
558+
run(["git", "init", "-q"])
559+
run(
560+
[
561+
"git",
562+
"-c",
563+
"commit.gpgsign=false",
564+
"commit",
565+
"-q",
566+
"--allow-empty",
567+
"-m",
568+
"chore: bump",
569+
]
570+
)
571+
sha = run(["git", "rev-parse", "HEAD"], text=True).stdout.strip()
572+
cwd = os.getcwd()
573+
os.chdir(repo)
574+
try:
575+
author = main._local_author(sha)
576+
finally:
577+
os.chdir(cwd)
578+
self.assertEqual(author, ("Renovate Bot", "bot@renovateapp.com"))
579+
580+
493581
class TestRunOtherChecks(unittest.TestCase):
494582
def test_empty_args_returns_no_scopes(self):
495583
with patch("main.subprocess.run") as mock_run:

0 commit comments

Comments
 (0)