Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
117 changes: 113 additions & 4 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,118 @@ Our development branch is `main`. When submitting pull requests, please adhere t

By contributing any code or documentation to this repository (by raising pull requests or otherwise), you explicitly agree to the [License Agreement](https://github.com/commit-check/commit-check/blob/main/LICENSE).

We appreciate your contributions to make Commit Check even better!
## Architecture

### Overview

Commit-check validates Git commit metadata using a pipeline of configurable validators. The key flow is:

```
CLI args / Env vars / TOML file
ConfigMerger ← Merges all config sources (priority: CLI > Env > TOML > Defaults)
RuleBuilder ← Builds ValidationRule objects from merged config + rules catalog
ValidationEngine ← Iterates over rules, picks the right validator for each
BaseValidator subclasses ← Each validator performs one focused check
Exit code 0/1
```
Comment thread
shenxianpeng marked this conversation as resolved.

### Module responsibilities

```
commit_check/
├── __init__.py # Package constants: DEFAULT_COMMIT_TYPES, DEFAULT_BRANCH_TYPES, DEFAULT_BOOLEAN_RULES
├── main.py # CLI entry point, argument parsing, StdinReader
├── config.py # TOML file loading (uses tomllib on Python 3.11+, tomli on older)
├── config_merger.py # ConfigMerger: merges CLI → Env → TOML → Defaults
├── rule_builder.py # RuleBuilder: creates ValidationRule objects from config + catalog
Comment on lines +49 to +50

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Correct config merge-order wording and make TOML discovery order explicit.

Line 49 currently implies merge is performed from CLI down to defaults, but implementation merges in the opposite direction and only priority is CLI highest. Also, Line 80 should explicitly enumerate the TOML discovery order to avoid ambiguity.

Proposed wording update
-├── config_merger.py     # ConfigMerger: merges CLI → Env → TOML → Defaults
+├── config_merger.py     # ConfigMerger: merges Defaults → TOML → Env → CLI (effective priority: CLI > Env > TOML > Defaults)
@@
-| 3 | TOML config files | `cchk.toml`, `.github/cchk.toml`, etc. |
+| 3 | TOML config files | `--config` path, then `cchk.toml`, `commit-check.toml`, `.github/cchk.toml`, `.github/commit-check.toml` |

Based on learnings: "Define TOML configuration discovery order: --config argument, cchk.toml, commit-check.toml, .github/cchk.toml, .github/commit-check.toml".

Also applies to: 80-81

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@CONTRIBUTING.md` around lines 49 - 50, Update the merge-order wording in
CONTRIBUTING.md where the ConfigMerger description reads "merges CLI → Env →
TOML → Defaults" to correctly state that merging happens from Defaults up to
TOML → Env → CLI with CLI being highest priority (i.e., priority is CLI
highest), and explicitly enumerate the TOML discovery order in the doc (add the
sequence: --config argument, cchk.toml, commit-check.toml, .github/cchk.toml,
.github/commit-check.toml) to replace the ambiguous text found near the
RuleBuilder/ConfigMerger description and the later TOML notes so both
occurrences are consistent.

├── rules_catalog.py # Catalog of all rules (COMMIT_RULES, BRANCH_RULES)
├── engine.py # ValidationEngine, BaseValidator ABC, ValidationContext, ValidationResult
├── imperatives.py # ~258 English imperative verbs for subject validation
└── util.py # Git operations, output formatting (_print_failure)
```

## Development
### Validator class hierarchy

### Debug commit-check pre-commit hook
```
BaseValidator (ABC)
├── CommitMessageValidator # Full message: conventional commits format
├── SubjectValidator (ABC)
│ ├── SubjectCapitalizationValidator # First letter must be uppercase
│ ├── SubjectImperativeValidator # Subject must start with imperative verb
│ └── SubjectLengthValidator # Subject length min/max
├── AuthorValidator # Author name and email format
├── BranchValidator # Branch naming conventions
├── MergeBaseValidator # Merge base / rebase target
├── SignoffValidator # Signed-off-by trailer presence
├── BodyValidator # Commit body presence
└── CommitTypeValidator # Handles merge/revert/fixup/wip/empty commits
```

### Configuration priority cascade

| Priority | Source | Example |
|----------|--------|---------|
| 1 (highest) | CLI arguments | `--subject-max-length=72` |
| 2 | Environment variables | `CCHK_SUBJECT_MAX_LENGTH=72` |
| 3 | TOML config files | `cchk.toml`, `.github/cchk.toml`, etc. |
| 4 (lowest) | Built-in defaults | defined in `commit_check/__init__.py` |

## Development setup

### Prerequisites

- Python 3.9 or newer
- `nox` for running build sessions: `pip install nox`

### Install in development mode

```bash
git clone https://github.com/commit-check/commit-check.git
cd commit-check
pip install -e ".[test]"
```

### Run tests

```bash
# Fastest: run pytest directly
pytest tests/ -v

# With coverage report
nox -s coverage
```

### Lint and format

```bash
# Run all pre-commit hooks (ruff, mypy, codespell, etc.)
nox -s lint

# Or install hooks for automatic checks on every commit
pre-commit install
```

### Build documentation

```bash
# One-time build
nox -s docs

# Live preview with auto-reload
nox -s docs-live
```

### Test the pre-commit hook locally

```bash
pre-commit try-repo ./../commit-check/ check-message --verbose --hook-stage commit-msg --commit-msg-filename .git/COMMIT_EDITMSG
Comment thread
shenxianpeng marked this conversation as resolved.
Expand All @@ -32,7 +139,7 @@ pip install -e ./../commit-check/
commit-check -m
```

### Test commit-check pre-commit hook on GitHub
## Test commit-check pre-commit hook on GitHub

```yaml
- repo: https://github.com/commit-check/commit-check
Expand All @@ -42,3 +149,5 @@ commit-check -m
- id: check-branch
- id: check-author-email
```

We appreciate your contributions to make Commit Check even better!
7 changes: 6 additions & 1 deletion commit_check/rule_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,11 +110,16 @@ def _build_conventional_commit_rule(
allowed_types = self._get_allowed_commit_types()
regex = self._build_conventional_commit_regex(allowed_types)

types_str = ", ".join(allowed_types)
suggest = (
f"Use <type>(<scope>): <description>, where <type> is one of: {types_str}"
)
Comment on lines +113 to +116

@coderabbitai coderabbitai Bot Mar 17, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Guard against empty allow_commit_types before building suggestion text.

If config provides an empty list, Line 115 renders one of: with no values, and commit guidance becomes unusable.

Proposed fix
         allowed_types = self._get_allowed_commit_types()
+        if not allowed_types:
+            allowed_types = DEFAULT_COMMIT_TYPES
         regex = self._build_conventional_commit_regex(allowed_types)

         types_str = ", ".join(allowed_types)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@commit_check/rule_builder.py` around lines 113 - 116, The suggestion text
currently joins allowed_types into types_str and yields "one of:" even when
allowed_types is empty; update the logic around types_str/suggest (the variables
used at Lines where allowed_types and suggest are set) to guard against an empty
allow_commit_types list by detecting if allowed_types is truthy and, if empty,
set types_str to a fallback like "none specified" or replace the whole suggest
text with a generic "Use <type>(<scope>): <description>" guidance (or explicitly
state allowed types are not configured) so the suggestion remains meaningful
when allow_commit_types is an empty list.

@shenxianpeng shenxianpeng Mar 18, 2026

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Make sense, apply the change @coderabbitai

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@shenxianpeng, sure! Here's the plan to apply the fix:

  • Add an empty-list guard in _build_conventional_commit_rule after calling _get_allowed_commit_types(), falling back to DEFAULT_COMMIT_TYPES (already imported).

🧠 Learnings used
Learnt from: CR
Repo: commit-check/commit-check PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2026-03-02T05:17:44.250Z
Learning: Applies to commit_check/rules_catalog.py : Validate conventional commits with format: type(scope): description, supporting types build, chore, ci, docs, feat, fix, perf, refactor, revert, style, test

Learnt from: CR
Repo: commit-check/commit-check PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2026-03-02T05:17:44.250Z
Learning: Applies to commit_check/__init__.py : Store default validation types in commit_check/__init__.py (DEFAULT_COMMIT_TYPES, DEFAULT_BRANCH_TYPES, DEFAULT_BOOLEAN_RULES)

Learnt from: CR
Repo: commit-check/commit-check PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2026-03-02T05:17:44.250Z
Learning: Applies to commit_check/rules_catalog.py : Validate branch names with conventional patterns: bugfix/, feature/, release/, hotfix/, task/, chore/ prefixes, and special branches master, main, HEAD, PR-*

Learnt from: CR
Repo: commit-check/commit-check PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2026-03-02T05:17:44.250Z
Learning: Applies to commit_check/util.py : Use colorized ASCII art rejection message in output when validation fails

Failed to handle agent chat message. Please try again.

Comment on lines 110 to +116

return ValidationRule(
check=catalog_entry.check,
regex=regex,
error=catalog_entry.error,
suggest=catalog_entry.suggest,
suggest=suggest,
allowed=allowed_types,
Comment thread
shenxianpeng marked this conversation as resolved.
)

Expand Down
4 changes: 2 additions & 2 deletions commit_check/rules_catalog.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@ class RuleCatalogEntry:
RuleCatalogEntry(
check="subject_imperative",
regex=None,
error="Commit message should use imperative mood (e.g., 'Add feature' not 'Added feature')",
suggest="Use imperative mood in the subject line",
error="Commit message should use imperative mood (e.g., 'fix bug' not 'fixed bug', 'add feature' not 'adding feature')",
suggest="Change the first verb to imperative form, e.g., 'fix' instead of 'fixed'/'fixes'/'fixing'",
Comment thread
shenxianpeng marked this conversation as resolved.
),
RuleCatalogEntry(
check="subject_max_length",
Expand Down
9 changes: 4 additions & 5 deletions commit_check/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,11 @@
return None


def _print_failure(check: dict, regex: str, actual: str) -> None:

Check warning on line 35 in commit_check/util.py

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Remove the unused function parameter "regex".

See more on https://sonarcloud.io/project/issues?id=commit-check_commit-check&issues=AZz98USLd-42GULEDHrd&open=AZz98USLd-42GULEDHrd&pullRequest=383
"""Print a standardized failure message."""
if not print_error_header.has_been_called:
print_error_header()
print_error_message(check["check"], regex, check.get("error", ""), actual)
print_error_message(check["check"], check.get("error", ""), actual)
if check.get("suggest"):
print_suggestion(check.get("suggest"))

Expand Down Expand Up @@ -241,10 +241,9 @@
print(" ")


def print_error_message(check_type: str, regex: str, error: str, reason: str):
def print_error_message(check_type: str, error: str, reason: str):
"""Print error message.
:param check_type:
:param regex:
:param error:
:param reason:

Expand All @@ -255,8 +254,8 @@
end="",
)
print("")
print(f"It doesn't match regex: {regex}")
print(error)
if error:
print(error)


def print_suggestion(suggest: Optional[str]) -> None:
Expand Down
4 changes: 1 addition & 3 deletions tests/util_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -322,14 +322,12 @@ def test_print_error_header(self, capfd):
@pytest.mark.benchmark
def test_print_error_message(self, capfd, check_type, type_failed_msg):
# Must print on stdout with given argument.
dummy_regex = "dummy regex"
dummy_reason = "failure reason"
dummy_error = "dummy error"
print_error_message(check_type, dummy_regex, dummy_error, dummy_reason)
print_error_message(check_type, dummy_error, dummy_reason)
stdout, _ = capfd.readouterr()
assert check_type in stdout
assert type_failed_msg in stdout
assert f"It doesn't match regex: {dummy_regex}" in stdout
assert dummy_error in stdout

class TestPrintSuggestion:
Expand Down
Loading