feat: add custom regex back via message_pattern config option - #427
Conversation
✅ Deploy Preview for commit-check ready!
To edit notification comments on pull requests, go to your Netlify project configuration. |
📝 WalkthroughWalkthroughThis PR adds a ChangesCustom Regex Message Pattern Feature
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
Suggested labels
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #427 +/- ##
==========================================
+ Coverage 95.92% 95.93% +0.01%
==========================================
Files 10 10
Lines 1152 1155 +3
==========================================
+ Hits 1105 1108 +3
Misses 47 47 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
🧹 Nitpick comments (3)
docs/configuration.rst (1)
388-392: 💤 Low valueDocumentation is clear but could refine the "mutually exclusive" phrasing.
The description states:
This is mutually exclusive with
conventional_commits— ifmessage_patternis non-empty it takes precedence."Mutually exclusive" typically means both cannot be set simultaneously, but here they can both be set—
message_patternsimply takes precedence. Consider rewording for precision:When set to a non-empty value,
message_patterntakes precedence over theconventional_commitsauto-generated regex.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@docs/configuration.rst` around lines 388 - 392, Update the phrasing explaining the relationship between message_pattern and conventional_commits: replace "This is mutually exclusive with ``conventional_commits`` — if ``message_pattern`` is non-empty it takes precedence." with a clearer statement such as "When set to a non-empty value, ``message_pattern`` takes precedence over the ``conventional_commits`` auto-generated regex." Ensure this change references the same option names (``message_pattern`` and ``conventional_commits``) so readers understand precedence rather than mutual exclusivity.commit_check/rule_builder.py (2)
161-161: 💤 Low valueConsider including the pattern in the suggestion message.
The hardcoded suggestion "Commit message does not match the required pattern" doesn't tell users what pattern is expected. Including the actual regex would make debugging easier.
💡 Proposed enhancement
- suggest="Commit message does not match the required pattern", + suggest=f"Commit message does not match the required pattern: {custom_pattern}",🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@commit_check/rule_builder.py` at line 161, Update the suggestion text so it includes the actual regex pattern used for validation instead of the generic message; locate the assignment to suggest (the `suggest="Commit message does not match the required pattern"` entry) in rule_builder.py and interpolate/format the rule's regex (the variable used for the commit message check, e.g., the pattern/regex variable that the rule uses) into that string so users see the exact pattern expected.
155-162: ⚡ Quick winConsider validating the custom regex pattern at configuration time.
Currently, an invalid regex in
message_patternwill fail at runtime whenCommitMessageValidatorcallsre.match(). Validating the pattern here would provide earlier, clearer feedback.🛡️ Proposed validation logic
custom_pattern = self.commit_config.get("message_pattern", "") if custom_pattern: + # Validate regex syntax early + try: + import re + re.compile(custom_pattern) + except re.error as e: + raise ValueError(f"Invalid message_pattern regex: {e}") return ValidationRule( check=catalog_entry.check, regex=custom_pattern, error=catalog_entry.error, suggest="Commit message does not match the required pattern", )🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@commit_check/rule_builder.py` around lines 155 - 162, The custom regex in commit_config["message_pattern"] should be validated when building the ValidationRule to fail fast: in the block that creates ValidationRule (referencing commit_config, ValidationRule and catalog_entry) try to compile the pattern with re.compile() and catch re.error; if compilation fails raise or propagate a clear configuration error (or log and skip rule) so CommitMessageValidator's later re.match() cannot encounter an invalid pattern at runtime; optionally store the compiled pattern in the ValidationRule so validators reuse the precompiled regex.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@commit_check/rule_builder.py`:
- Line 161: Update the suggestion text so it includes the actual regex pattern
used for validation instead of the generic message; locate the assignment to
suggest (the `suggest="Commit message does not match the required pattern"`
entry) in rule_builder.py and interpolate/format the rule's regex (the variable
used for the commit message check, e.g., the pattern/regex variable that the
rule uses) into that string so users see the exact pattern expected.
- Around line 155-162: The custom regex in commit_config["message_pattern"]
should be validated when building the ValidationRule to fail fast: in the block
that creates ValidationRule (referencing commit_config, ValidationRule and
catalog_entry) try to compile the pattern with re.compile() and catch re.error;
if compilation fails raise or propagate a clear configuration error (or log and
skip rule) so CommitMessageValidator's later re.match() cannot encounter an
invalid pattern at runtime; optionally store the compiled pattern in the
ValidationRule so validators reuse the precompiled regex.
In `@docs/configuration.rst`:
- Around line 388-392: Update the phrasing explaining the relationship between
message_pattern and conventional_commits: replace "This is mutually exclusive
with ``conventional_commits`` — if ``message_pattern`` is non-empty it takes
precedence." with a clearer statement such as "When set to a non-empty value,
``message_pattern`` takes precedence over the ``conventional_commits``
auto-generated regex." Ensure this change references the same option names
(``message_pattern`` and ``conventional_commits``) so readers understand
precedence rather than mutual exclusivity.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 61e206ae-b488-408d-8872-a84c37c28a93
📒 Files selected for processing (7)
commit_check/config_merger.pycommit_check/main.pycommit_check/rule_builder.pydocs/configuration.rstdocs/migration.rsttests/engine_test.pytests/rule_builder_test.py
3098376 to
72d4bd9
Compare
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
docs/configuration.rst (1)
217-282:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winAdd
message_patternto the configuration mapping table.The mapping table documents how each option corresponds across TOML config, environment variables, and CLI arguments. The
message_patternoption is missing from this table, even though it supports all three configuration methods (verified incommit_check/config_merger.py). Users need to know aboutCCHK_MESSAGE_PATTERNand--message-pattern.📝 Suggested addition
Insert after the
conventional_commitsrow (around line 225):* - ``conventional_commits = true`` - ``CCHK_CONVENTIONAL_COMMITS=true`` - ``--conventional-commits=true`` + * - ``message_pattern = "^PROJ-\\d+: .+"`` + - ``CCHK_MESSAGE_PATTERN=^PROJ-\\d+: .+`` + - ``--message-pattern=^PROJ-\\d+: .+`` * - ``subject_capitalized = false`` - ``CCHK_SUBJECT_CAPITALIZED=false`` - ``--subject-capitalized=false``🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@docs/configuration.rst` around lines 217 - 282, The docs table is missing the message_pattern option mapping; add a new row for the TOML key message_pattern and its env/CLI forms by inserting a table row after the conventional_commits entry that shows ``message_pattern = "<pattern>"`` under TOML, ``CCHK_MESSAGE_PATTERN=<pattern>`` under Environment Variable, and ``--message-pattern=<pattern>`` under CLI Argument so users see the mapping for message_pattern, CCHK_MESSAGE_PATTERN, and --message-pattern.
🧹 Nitpick comments (1)
tests/rule_builder_test.py (1)
242-242: 💤 Low valueConsider extracting the duplicated "Bad format" literal.
The literal
"Bad format"appears 4 times across the three new tests (lines 242, 248, 263, 284). Extracting it to a module-level constant would reduce duplication.♻️ Suggested refactor
+# Test constants +_TEST_ERROR_MSG = "Bad format" + class TestValidationRule: `@pytest.mark.benchmark` def test_validation_rule_to_dict_with_ignored(self):Then replace each usage:
catalog_entry = RuleCatalogEntry( - check="message", regex="", error="Bad format", suggest="Use JIRA format" + check="message", regex="", error=_TEST_ERROR_MSG, suggest="Use JIRA format" )🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@tests/rule_builder_test.py` at line 242, Extract the duplicated literal "Bad format" into a module-level constant (e.g., BAD_FORMAT_ERROR) at the top of tests/rule_builder_test.py and replace all occurrences of the string in the new tests with that constant; update the three tests that currently use "Bad format" (the four usages noted in the diff) to reference BAD_FORMAT_ERROR so the message is defined once and reused.Source: Linters/SAST tools
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Outside diff comments:
In `@docs/configuration.rst`:
- Around line 217-282: The docs table is missing the message_pattern option
mapping; add a new row for the TOML key message_pattern and its env/CLI forms by
inserting a table row after the conventional_commits entry that shows
``message_pattern = "<pattern>"`` under TOML, ``CCHK_MESSAGE_PATTERN=<pattern>``
under Environment Variable, and ``--message-pattern=<pattern>`` under CLI
Argument so users see the mapping for message_pattern, CCHK_MESSAGE_PATTERN, and
--message-pattern.
---
Nitpick comments:
In `@tests/rule_builder_test.py`:
- Line 242: Extract the duplicated literal "Bad format" into a module-level
constant (e.g., BAD_FORMAT_ERROR) at the top of tests/rule_builder_test.py and
replace all occurrences of the string in the new tests with that constant;
update the three tests that currently use "Bad format" (the four usages noted in
the diff) to reference BAD_FORMAT_ERROR so the message is defined once and
reused.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 44122a8b-c4f3-49c6-a263-75b26d31bbd9
📒 Files selected for processing (7)
commit_check/config_merger.pycommit_check/main.pycommit_check/rule_builder.pydocs/configuration.rstdocs/migration.rsttests/engine_test.pytests/rule_builder_test.py
✅ Files skipped from review due to trivial changes (1)
- docs/migration.rst
🚧 Files skipped from review as they are similar to previous changes (4)
- commit_check/config_merger.py
- commit_check/rule_builder.py
- commit_check/main.py
- tests/engine_test.py
Add `message_pattern` to the `[commit]` config section — a custom regex that replaces the auto-generated Conventional Commits regex when set. Only available via TOML and env var (CCHK_MESSAGE_PATTERN), not as a CLI flag, since regex belongs in config files not command lines. Closes #426
72d4bd9 to
5b41b42
Compare
Merging this PR will not alter performance
Performance Changes
Comparing Footnotes
|
|
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@commit_check/rule_builder.py`:
- Around line 155-156: The code currently calls
self.commit_config.get("message_pattern", "").strip() which crashes if
message_pattern is not a string; change it to first retrieve the raw value
(e.g., raw = self.commit_config.get("message_pattern", None)), check
isinstance(raw, str) and only then call strip() (assign custom_pattern =
raw.strip()), otherwise set custom_pattern = "" (or otherwise fallback safely)
so non-string TOML values don't raise in rule_builder.py; update any downstream
uses that assume custom_pattern is a string accordingly.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 7fd1833c-eb55-401b-ab0b-fc7f0a34c096
📒 Files selected for processing (7)
commit_check/config_merger.pycommit_check/rule_builder.pydocs/configuration.rstdocs/migration.rsttests/config_merger_test.pytests/engine_test.pytests/rule_builder_test.py
✅ Files skipped from review due to trivial changes (1)
- docs/migration.rst
🚧 Files skipped from review as they are similar to previous changes (1)
- docs/configuration.rst
| custom_pattern = self.commit_config.get("message_pattern", "").strip() | ||
| if custom_pattern: |
There was a problem hiding this comment.
Guard message_pattern type before calling .strip() to avoid runtime crash.
On Line 155, self.commit_config.get("message_pattern", "").strip() will raise if TOML provides a non-string value (e.g., number/list), causing rule building to fail instead of falling back safely.
Suggested fix
- custom_pattern = self.commit_config.get("message_pattern", "").strip()
+ raw_pattern = self.commit_config.get("message_pattern", "")
+ custom_pattern = raw_pattern.strip() if isinstance(raw_pattern, str) else ""
if custom_pattern:
return ValidationRule(
check=catalog_entry.check,
regex=custom_pattern,🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@commit_check/rule_builder.py` around lines 155 - 156, The code currently
calls self.commit_config.get("message_pattern", "").strip() which crashes if
message_pattern is not a string; change it to first retrieve the raw value
(e.g., raw = self.commit_config.get("message_pattern", None)), check
isinstance(raw, str) and only then call strip() (assign custom_pattern =
raw.strip()), otherwise set custom_pattern = "" (or otherwise fallback safely)
so non-string TOML values don't raise in rule_builder.py; update any downstream
uses that assume custom_pattern is a string accordingly.
message_pattern config option



Summary
Add
message_patternto the[commit]config section — a custom regex that replaces the auto-generated Conventional Commits regex when set. Only available via TOML config and env var (CCHK_MESSAGE_PATTERN). No CLI flag — regex belongs in config files, not command lines.Closes #426.
Motivation
Many organizations have custom commit message policies beyond Conventional Commits:
PROJ-123: Fix login bugFix login #123Usage
TOML config
Environment variable
When
message_patternis set (non-empty), it takes precedence overconventional_commits. If empty/unset, behavior is unchanged.Summary by CodeRabbit
New Features
Documentation