|
3 | 3 | except ImportError:
|
4 | 4 | from string import Template # type: ignore
|
5 | 5 |
|
| 6 | +import re |
6 | 7 | from typing import Optional
|
7 | 8 |
|
8 | 9 | from commitizen import defaults
|
9 | 10 | from commitizen.config import BaseConfig
|
10 | 11 | from commitizen.cz.base import BaseCommitizen
|
11 | 12 | from commitizen.defaults import Questions
|
12 |
| -from commitizen.exceptions import MissingCzCustomizeConfigError |
| 13 | +from commitizen.exceptions import ( |
| 14 | + InvalidCommitMessageError, |
| 15 | + MissingCzCustomizeConfigError, |
| 16 | +) |
13 | 17 |
|
14 |
| -__all__ = ["CustomizeCommitsCz"] |
| 18 | +__all__ = ["CustomizeCommitsCz", "CustomizeCommitValidationCz"] |
15 | 19 |
|
16 | 20 |
|
17 | 21 | class CustomizeCommitsCz(BaseCommitizen):
|
@@ -79,3 +83,53 @@ def info(self) -> Optional[str]:
|
79 | 83 | elif info:
|
80 | 84 | return info
|
81 | 85 | return None
|
| 86 | + |
| 87 | + |
| 88 | +class CustomizeCommitValidationCz(CustomizeCommitsCz): |
| 89 | + def validate_commit(self, pattern, commit, allow_abort): |
| 90 | + """ |
| 91 | + Validates that a commit message doesn't contain certain tokens. |
| 92 | + """ |
| 93 | + if not commit.message: |
| 94 | + return allow_abort |
| 95 | + |
| 96 | + invalid_tokens = ["Merge", "Revert", "Pull request", "fixup!", "squash!"] |
| 97 | + for token in invalid_tokens: |
| 98 | + if commit.message.startswith(token): |
| 99 | + raise InvalidCommitMessageError( |
| 100 | + f"Commits may not start with the token {token}." |
| 101 | + ) |
| 102 | + |
| 103 | + return re.match(pattern, commit.message) |
| 104 | + |
| 105 | + def validate_commits(self, commits, allow_abort): |
| 106 | + """ |
| 107 | + Validates a list of commits against the configured commit validation schema. |
| 108 | + See the schema() and example() functions for examples. |
| 109 | + """ |
| 110 | + |
| 111 | + pattern = self.schema_pattern() |
| 112 | + |
| 113 | + displayed_msgs_content = [] |
| 114 | + for commit in commits: |
| 115 | + message = "" |
| 116 | + valid = False |
| 117 | + try: |
| 118 | + valid = self.validate_commit(pattern, commit, allow_abort) |
| 119 | + except InvalidCommitMessageError as e: |
| 120 | + message = e.message |
| 121 | + |
| 122 | + if not valid: |
| 123 | + displayed_msgs_content.append( |
| 124 | + f"commit {commit.rev}\n" |
| 125 | + f"Author: {commit.author} <{commit.author_email}>\n\n" |
| 126 | + f"{commit.message}\n\n" |
| 127 | + f"commit validation: failed! {message}\n" |
| 128 | + ) |
| 129 | + |
| 130 | + if displayed_msgs_content: |
| 131 | + displayed_msgs = "\n".join(displayed_msgs_content) |
| 132 | + raise InvalidCommitMessageError( |
| 133 | + f"{displayed_msgs}\n" |
| 134 | + "Please enter a commit message in the commitizen format.\n" |
| 135 | + ) |
0 commit comments