Skip to content

Commit 60e903b

Browse files
feat: add pr-title input to validate pull request title (#217)
* feat: add pr-title input to validate pull request title Add a new pr-title input that validates the PR title against the Conventional Commits specification using commit-check's --message check. This is especially useful for teams using Squash and Merge, where the PR title becomes the final commit message. Key changes: - action.yml: add pr-title input (default: false) - main.py: add get_pr_title(), PR_TITLE_ENABLED flag, integrate PR title validation into run_commit_check() - main_test.py: add tests for get_pr_title(), PR title in run_commit_check(), and initial_emitted parameter Closes #93 * chore: auto fixes from pre-commit.com hooks * docs: add pr-title input documentation to README * docs: remove 'experimental' label from pr-comments The pr-comments feature has been stable for 8+ months with proper fork PR handling, pull_request_target support, and comprehensive error handling. The 'experimental' label is no longer accurate. * chore: enable pr-title check in self-test pipeline * fix: listen pull_request edited event so pr-title validates on title change The pull_request event does not include the 'edited' type by default, so changing the PR title never re-triggers the workflow. Adding 'edited' ensures the pr-title check runs immediately when the title is updated, giving the contributor instant feedback. * docs: add event type guidance for pr-title validation Explain that pull_request does not trigger on title edits by default, and show how to add the 'edited' type to enable immediate validation. * fix: add clear label to PR title check output - Print '--- PR title check ---' in the log so users can distinguish PR title validation from individual commit message checks - Always set output_prefix for result.txt so the failure output clearly identifies which check failed * fix: use consistent separator style for PR title output Remove the markdown-style '# PR Title Validation' heading from result.txt. When the PR title check fails after other failures, use '--- PR Title ---' to match the existing commit check separator style (e.g. '--- Commit 2/6:'). * refactor: remove noisy command logging from action output Remove the 'commit-check --message' command lines that were being printed to the action log for every check invocation. The results are already visible in the job summary and PR comments — the command echo was debug cruft that created noise, especially when checking many individual commits in a PR. * refactor: use ::debug:: workflow command for env var logging Convert log_env_vars() to use ::debug:: workflow commands so the environment variable values only appear in the action log when ACTIONS_STEP_DEBUG is enabled. This follows GitHub Actions best practices for diagnostic output. * chore: auto fixes from pre-commit.com hooks * refactor: clean up run_commit_check by removing dead code path The PR title check always runs first, so the 'if emitted_failure_output' branch inside it was unreachable. Remove it to reduce nesting and improve readability. * chore: auto fixes from pre-commit.com hooks --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent eec6c29 commit 60e903b

5 files changed

Lines changed: 297 additions & 25 deletions

File tree

‎.github/workflows/commit-check.yml‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ name: Commit Check
33
on:
44
pull_request:
55
branches: 'main'
6+
types: [opened, synchronize, reopened, edited]
67
workflow_dispatch:
78

89
jobs:
@@ -23,3 +24,4 @@ jobs:
2324
author-email: true
2425
job-summary: true
2526
pr-comments: ${{ github.event_name == 'pull_request' }}
27+
pr-title: true

‎README.md‎

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -121,8 +121,8 @@ jobs:
121121
- **Description**: post results to the pull request comments.
122122
- Default: `false`
123123

124-
> [!IMPORTANT]
125-
> `pr-comments` is an experimental feature. By default, it's disabled.
124+
> [!NOTE]
125+
> `pr-comments` is disabled by default.
126126
>
127127
> PR comments are skipped for pull requests from forked repositories. See
128128
> [docs/fork-pr-comments.md](docs/fork-pr-comments.md) for details on how to enable
@@ -131,6 +131,34 @@ jobs:
131131
> Note: write-access to pull-requests requires the `pull-requests: write` permission.
132132
> See [usage example](#usage).
133133

134+
### `pr-title`
135+
136+
- **Description**: check pull request title following [Conventional Commits](https://www.conventionalcommits.org/).
137+
- Default: `false`
138+
139+
> [!TIP]
140+
> This is especially useful for teams using **Squash & Merge**, where the PR title
141+
> becomes the final commit message in the main branch. When enabled, the action
142+
> validates the PR title against your Conventional Commits configuration, giving
143+
> early feedback at PR time rather than after merge.
144+
>
145+
> `pr-title` works alongside `message` — you can enable both to validate the PR
146+
> title and individual commits, or just one depending on your workflow.
147+
>
148+
> This setting only applies to `pull_request` and `pull_request_target` events;
149+
> it is silently ignored on `push` events.
150+
151+
> [!IMPORTANT]
152+
> By default, `pull_request` does **not** trigger on title changes.
153+
> To validate the PR title immediately when updated, add `edited` to your
154+
> workflow's event types:
155+
> ```yaml
156+
> on:
157+
> pull_request:
158+
> types: [opened, synchronize, reopened, edited]
159+
> ```
160+
> Without `edited`, only the initial title (at PR creation) is validated.
161+
134162
Note: the default rule of above inputs is following [this configuration](https://github.com/commit-check/commit-check-action/blob/main/commit-check.toml). If you want to customize, just add your [`commit-check.toml`](https://commit-check.github.io/commit-check/configuration.html) config file under your repository root directory.
135163

136164
## GitHub Action Job Summary

‎action.yml‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,10 @@ inputs:
3333
description: post results to the pull request comments
3434
required: false
3535
default: false
36+
pr-title:
37+
description: check pull request title following conventional commits
38+
required: false
39+
default: false
3640
runs:
3741
using: "composite"
3842
steps:
@@ -69,4 +73,5 @@ runs:
6973
DRY_RUN: ${{ inputs.dry-run }}
7074
JOB_SUMMARY: ${{ inputs.job-summary }}
7175
PR_COMMENTS: ${{ inputs.pr-comments }}
76+
PR_TITLE: ${{ inputs.pr-title }}
7277
GITHUB_TOKEN: ${{ github.token }}

‎main.py‎

Lines changed: 88 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
DRY_RUN = os.getenv("DRY_RUN", "false")
2121
JOB_SUMMARY = os.getenv("JOB_SUMMARY", "false")
2222
PR_COMMENTS = os.getenv("PR_COMMENTS", "false")
23+
PR_TITLE = os.getenv("PR_TITLE", "false")
2324
GITHUB_STEP_SUMMARY = os.environ["GITHUB_STEP_SUMMARY"]
2425

2526

@@ -35,24 +36,50 @@ def env_flag(name: str, default: str = "false") -> bool:
3536
DRY_RUN_ENABLED = env_flag("DRY_RUN")
3637
JOB_SUMMARY_ENABLED = env_flag("JOB_SUMMARY")
3738
PR_COMMENTS_ENABLED = env_flag("PR_COMMENTS")
39+
PR_TITLE_ENABLED = env_flag("PR_TITLE")
3840

3941

4042
def log_env_vars():
41-
"""Logs the environment variables for debugging purposes."""
42-
print(f"MESSAGE = {MESSAGE}")
43-
print(f"BRANCH = {BRANCH}")
44-
print(f"AUTHOR_NAME = {AUTHOR_NAME}")
45-
print(f"AUTHOR_EMAIL = {AUTHOR_EMAIL}")
46-
print(f"DRY_RUN = {DRY_RUN}")
47-
print(f"JOB_SUMMARY = {JOB_SUMMARY}")
48-
print(f"PR_COMMENTS = {PR_COMMENTS}\n")
43+
"""Logs the environment variables for debugging purposes.
44+
45+
Uses the ``::debug::`` workflow command so these only appear in the
46+
action log when ``ACTIONS_STEP_DEBUG`` is set to ``true``.
47+
"""
48+
for name in (
49+
"MESSAGE",
50+
"BRANCH",
51+
"AUTHOR_NAME",
52+
"AUTHOR_EMAIL",
53+
"DRY_RUN",
54+
"JOB_SUMMARY",
55+
"PR_COMMENTS",
56+
"PR_TITLE",
57+
):
58+
value = os.getenv(name, "false")
59+
print(f"::debug::{name}={value}")
4960

5061

5162
def is_pr_event() -> bool:
5263
"""Return whether the workflow was triggered by a PR-style event."""
5364
return os.getenv("GITHUB_EVENT_NAME", "") in {"pull_request", "pull_request_target"}
5465

5566

67+
def get_pr_title() -> str | None:
68+
"""Read PR title from GitHub event payload."""
69+
if not is_pr_event():
70+
return None
71+
event_path = os.getenv("GITHUB_EVENT_PATH")
72+
if not event_path:
73+
return None
74+
try:
75+
with open(event_path, "r") as f:
76+
event = json.load(f)
77+
return event.get("pull_request", {}).get("title")
78+
except Exception as e:
79+
print(f"::warning::Failed to read PR title from event: {e}", file=sys.stderr)
80+
return None
81+
82+
5683
def parse_commit_messages(output: str) -> list[str]:
5784
"""Split git log output into individual commit messages."""
5885
return [
@@ -132,7 +159,6 @@ def run_check_command(
132159
) -> int:
133160
"""Run commit-check and write both stdout and stderr to the result file."""
134161
command = ["commit-check"] + args
135-
print(" ".join(command))
136162
result = subprocess.run(
137163
command,
138164
input=input_text,
@@ -149,13 +175,23 @@ def run_check_command(
149175
return result.returncode
150176

151177

152-
def run_pr_message_checks(pr_messages: list[str], result_file: TextIO) -> int:
178+
def run_pr_message_checks(
179+
pr_messages: list[str],
180+
result_file: TextIO,
181+
initial_emitted: bool = False,
182+
) -> int:
153183
"""Checks each PR commit message individually via commit-check --message.
154184
185+
Parameters
186+
----------
187+
initial_emitted : bool
188+
Whether another check (e.g. PR title) has already produced banner output,
189+
so the first failing commit should use --no-banner.
190+
155191
Returns 1 if any message fails, 0 if all pass.
156192
"""
157193
has_failure = False
158-
emitted_failure_output = False
194+
emitted_failure_output = initial_emitted
159195
total = len(pr_messages)
160196
for index, msg in enumerate(pr_messages, start=1):
161197
command_args = ["--message"]
@@ -198,20 +234,53 @@ def build_check_args() -> list[str]:
198234

199235

200236
def run_commit_check() -> int:
201-
"""Runs the commit-check command and logs the result."""
237+
"""Runs all enabled checks and returns the overall exit code.
238+
239+
Checks are evaluated in order:
240+
1. PR title (when ``pr-title: true`` and in a PR event)
241+
2. Individual PR commit messages (when ``message: true`` and in a PR event)
242+
3. All remaining checks (branch, author name/email, etc.)
243+
244+
Outside of a PR event all enabled checks are handed to the CLI at once.
245+
"""
202246
args = build_check_args()
247+
exit_code = 0
248+
emitted_failure_output = False
249+
203250
with open("result.txt", "w") as result_file:
251+
# ---- 1. PR title check ------------------------------------------------
252+
if PR_TITLE_ENABLED and is_pr_event():
253+
pr_title = get_pr_title()
254+
if pr_title:
255+
rc = run_check_command(
256+
["--message"],
257+
result_file,
258+
input_text=pr_title,
259+
)
260+
if rc != 0:
261+
exit_code = max(exit_code, rc)
262+
emitted_failure_output = True
263+
264+
# ---- 2. Commit message checks -----------------------------------------
204265
if MESSAGE_ENABLED:
205266
pr_messages = get_pr_commit_messages()
206267
if pr_messages:
207-
# In PR context: check each commit message individually to avoid
268+
# In PR context: check each commit individually to avoid
208269
# only validating the synthetic merge commit at HEAD.
209-
message_rc = run_pr_message_checks(pr_messages, result_file)
210-
other_args = [a for a in args if a != "--message"]
211-
other_rc = run_other_checks(other_args, result_file)
212-
return 1 if message_rc or other_rc else 0
213-
# Non-PR context or message disabled: run all checks at once
214-
return 1 if run_check_command(args, result_file) else 0
270+
rc = run_pr_message_checks(
271+
pr_messages, result_file, initial_emitted=emitted_failure_output
272+
)
273+
if rc != 0:
274+
exit_code = max(exit_code, rc)
275+
args = [a for a in args if a != "--message"]
276+
277+
# ---- 3. Remaining checks (branch, author, etc.) -----------------------
278+
if args:
279+
rc = run_other_checks(args, result_file)
280+
if rc != 0:
281+
exit_code = max(exit_code, rc)
282+
283+
return 1 if exit_code else 0
215284

216285

217286
def read_result_file() -> str | None:

0 commit comments

Comments
 (0)