Skip to content

Commit 0910b3d

Browse files
committed
feat: implement PR commit message retrieval and validation in commit-check
1 parent 40fb31e commit 0910b3d

File tree

1 file changed

+56
-2
lines changed

1 file changed

+56
-2
lines changed

main.py

Lines changed: 56 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,30 @@ def log_env_vars():
3636
print(f"PR_COMMENTS = {PR_COMMENTS}\n")
3737

3838

39+
def get_pr_commit_messages() -> list[str]:
40+
"""Get all commit messages for the current PR (pull_request event only).
41+
42+
In a pull_request event, actions/checkout checks out a synthetic merge
43+
commit (HEAD = merge of PR branch into base). HEAD^1 is the base branch
44+
tip, HEAD^2 is the PR branch tip. So HEAD^1..HEAD^2 gives all PR commits.
45+
"""
46+
if os.getenv("GITHUB_EVENT_NAME", "") != "pull_request":
47+
return []
48+
try:
49+
result = subprocess.run(
50+
["git", "log", "--pretty=format:%B%x00", "HEAD^1..HEAD^2"],
51+
stdout=subprocess.PIPE,
52+
stderr=subprocess.PIPE,
53+
encoding="utf-8",
54+
check=False,
55+
)
56+
if result.returncode == 0 and result.stdout:
57+
return [m.strip() for m in result.stdout.split("\x00") if m.strip()]
58+
except Exception:
59+
pass
60+
return []
61+
62+
3963
def run_commit_check() -> int:
4064
"""Runs the commit-check command and logs the result."""
4165
args = [
@@ -58,9 +82,39 @@ def run_commit_check() -> int:
5882
if value == "true"
5983
]
6084

61-
command = ["commit-check"] + args
62-
print(" ".join(command))
85+
total_rc = 0
6386
with open("result.txt", "w") as result_file:
87+
if MESSAGE == "true":
88+
pr_messages = get_pr_commit_messages()
89+
if pr_messages:
90+
# In PR context: check each commit message individually to avoid
91+
# only validating the synthetic merge commit at HEAD.
92+
for msg in pr_messages:
93+
result = subprocess.run(
94+
["commit-check", "--message"],
95+
input=msg,
96+
stdout=result_file,
97+
stderr=subprocess.PIPE,
98+
text=True,
99+
check=False,
100+
)
101+
total_rc += result.returncode
102+
103+
# Run non-message checks (branch, author) once
104+
other_args = [a for a in args if a != "--message"]
105+
if other_args:
106+
command = ["commit-check"] + other_args
107+
print(" ".join(command))
108+
result = subprocess.run(
109+
command, stdout=result_file, stderr=subprocess.PIPE, check=False
110+
)
111+
total_rc += result.returncode
112+
113+
return total_rc
114+
115+
# Non-PR context or message disabled: run all checks at once
116+
command = ["commit-check"] + args
117+
print(" ".join(command))
64118
result = subprocess.run(
65119
command, stdout=result_file, stderr=subprocess.PIPE, check=False
66120
)

0 commit comments

Comments
 (0)