| 1 |
# Customizing through a python class |
| 2 |
|
| 3 |
The basic steps are: |
| 4 |
|
| 5 |
1. Inheriting from `BaseCommitizen`. |
| 6 |
2. Give a name to your rules. |
| 7 |
3. Create a Python package using proper [build backend](https://packaging.python.org/en/latest/glossary/#term-Build-Backend) |
| 8 |
4. Expose the class as a `commitizen.plugin` entrypoint. |
| 9 |
|
| 10 |
Check an [example][convcomms] on how to configure `BaseCommitizen`. |
| 11 |
|
| 12 |
You can also automate the steps above through [cookiecutter](https://cookiecutter.readthedocs.io/en/1.7.0/). |
| 13 |
|
| 14 |
```sh |
| 15 |
cookiecutter gh:commitizen-tools/commitizen_cz_template |
| 16 |
``` |
| 17 |
|
| 18 |
See [commitizen_cz_template](https://github.com/commitizen-tools/commitizen_cz_template) for details. |
| 19 |
|
| 20 |
See [Third-party plugins](../third-party-plugins/about.md) for more details on how to create a third-party Commitizen plugin. |
| 21 |
|
| 22 |
## Custom commit rules |
| 23 |
|
| 24 |
Create a Python module, for example `cz_jira.py`. |
| 25 |
|
| 26 |
Inherit from `BaseCommitizen`, and you must define `questions` and `message`. The others are optional. |
| 27 |
|
| 28 |
```python title="cz_jira.py" |
| 29 |
from commitizen.cz.base import BaseCommitizen |
| 30 |
from commitizen.defaults import Questions |
| 31 |
|
| 32 |
|
| 33 |
class JiraCz(BaseCommitizen): |
| 34 |
# Questions = Iterable[MutableMapping[str, Any]] |
| 35 |
# It expects a list with dictionaries. |
| 36 |
def questions(self) -> Questions: |
| 37 |
"""Questions regarding the commit message.""" |
| 38 |
questions = [ |
| 39 |
{"type": "input", "name": "title", "message": "Commit title"}, |
| 40 |
{"type": "input", "name": "issue", "message": "Jira Issue number:"}, |
| 41 |
] |
| 42 |
return questions |
| 43 |
|
| 44 |
def message(self, answers: dict) -> str: |
| 45 |
"""Generate the message with the given answers.""" |
| 46 |
return f"answers['title'] (#answers['issue'])" |
| 47 |
|
| 48 |
def example(self) -> str: |
| 49 |
"""Provide an example to help understand the style (OPTIONAL) |
| 50 |
|
| 51 |
Used by `cz example`. |
| 52 |
""" |
| 53 |
return "Problem with user (#321)" |
| 54 |
|
| 55 |
def schema(self) -> str: |
| 56 |
"""Show the schema used (OPTIONAL) |
| 57 |
|
| 58 |
Used by `cz schema`. |
| 59 |
""" |
| 60 |
return "<title> (<issue>)" |
| 61 |
|
| 62 |
def info(self) -> str: |
| 63 |
"""Explanation of the commit rules. (OPTIONAL) |
| 64 |
|
| 65 |
Used by `cz info`. |
| 66 |
""" |
| 67 |
return "We use this because is useful" |
| 68 |
``` |
| 69 |
|
| 70 |
The next file required is `setup.py` modified from flask version. |
| 71 |
|
| 72 |
```python title="setup.py" |
| 73 |
from setuptools import setup |
| 74 |
|
| 75 |
setup( |
| 76 |
name="JiraCommitizen", |
| 77 |
version="0.1.0", |
| 78 |
py_modules=["cz_jira"], |
| 79 |
license="MIT", |
| 80 |
long_description="this is a long description", |
| 81 |
install_requires=["commitizen"], |
| 82 |
entry_points={"commitizen.plugin": ["cz_jira = cz_jira:JiraCz"]}, |
| 83 |
) |
| 84 |
``` |
| 85 |
|
| 86 |
So in the end, we would have |
| 87 |
|
| 88 |
. |
| 89 |
├── cz_jira.py |
| 90 |
└── setup.py |
| 91 |
|
| 92 |
And that's it. You can install it without uploading to PyPI by simply |
| 93 |
doing `pip install .` |
| 94 |
|
| 95 |
## Custom bump rules |
| 96 |
|
| 97 |
You need to define 2 parameters inside your custom `BaseCommitizen`. |
| 98 |
|
| 99 |
| Parameter | Type | Default | Description | |
| 100 |
| -------------- | ------ | ------- | ----------------------------------------------------------------------------------------------------- | |
| 101 |
| `bump_pattern` | `str` | `None` | Regex to extract information from commit (subject and body) | |
| 102 |
| `bump_map` | `dict` | `None` | Dictionary mapping the extracted information to a `SemVer` increment type (`MAJOR`, `MINOR`, `PATCH`) | |
| 103 |
|
| 104 |
Let's see an example. |
| 105 |
|
| 106 |
```python title="cz_strange.py" |
| 107 |
from commitizen.cz.base import BaseCommitizen |
| 108 |
|
| 109 |
|
| 110 |
class StrangeCommitizen(BaseCommitizen): |
| 111 |
bump_pattern = r"^(break|new|fix|hotfix)" |
| 112 |
bump_map = {"break": "MAJOR", "new": "MINOR", "fix": "PATCH", "hotfix": "PATCH"} |
| 113 |
``` |
| 114 |
|
| 115 |
That's it, your Commitizen now supports custom rules, and you can run. |
| 116 |
|
| 117 |
```bash |
| 118 |
cz -n cz_strange bump |
| 119 |
``` |
| 120 |
|
| 121 |
[convcomms]: https://github.com/commitizen-tools/commitizen/blob/master/commitizen/cz/conventional_commits/conventional_commits.py |
| 122 |
|
| 123 |
### Custom commit validation and error message |
| 124 |
|
| 125 |
The commit message validation can be customized by overriding the `validate_commit_message` and `format_error_message` |
| 126 |
methods from `BaseCommitizen`. This allows for a more detailed feedback to the user where the error originates from. |
| 127 |
|
| 128 |
```python |
| 129 |
import re |
| 130 |
from commitizen.cz.base import BaseCommitizen, ValidationResult |
| 131 |
from commitizen import git |
| 132 |
|
| 133 |
|
| 134 |
class CustomValidationCz(BaseCommitizen): |
| 135 |
def validate_commit_message( |
| 136 |
self, |
| 137 |
*, |
| 138 |
commit_msg: str, |
| 139 |
pattern: str | None, |
| 140 |
allow_abort: bool, |
| 141 |
allowed_prefixes: list[str], |
| 142 |
max_msg_length: int, |
| 143 |
) -> ValidationResult: |
| 144 |
"""Validate commit message against the pattern.""" |
| 145 |
if not commit_msg: |
| 146 |
return allow_abort, [] if allow_abort else [f"commit message is empty"] |
| 147 |
if pattern is None: |
| 148 |
return True, [] |
| 149 |
if any(map(commit_msg.startswith, allowed_prefixes)): |
| 150 |
return True, [] |
| 151 |
if max_msg_length: |
| 152 |
msg_len = len(commit_msg.partition("\n")[0].strip()) |
| 153 |
if msg_len > max_msg_length: |
| 154 |
return False, [ |
| 155 |
f"commit message is too long. Max length is {max_msg_length}" |
| 156 |
] |
| 157 |
pattern_match = re.match(pattern, commit_msg) |
| 158 |
if pattern_match: |
| 159 |
return True, [] |
| 160 |
else: |
| 161 |
# Perform additional validation of the commit message format |
| 162 |
# and add custom error messages as needed |
| 163 |
return False, ["commit message does not match the pattern"] |
| 164 |
|
| 165 |
def format_exception_message( |
| 166 |
self, ill_formatted_commits: list[tuple[git.GitCommit, list]] |
| 167 |
) -> str: |
| 168 |
"""Format commit errors.""" |
| 169 |
displayed_msgs_content = "\n".join( |
| 170 |
( |
| 171 |
f'commit "{commit.rev}": "{commit.message}"' |
| 172 |
f"errors:\n" |
| 173 |
"\n".join((f"- {error}" for error in errors)) |
| 174 |
) |
| 175 |
for commit, errors in ill_formatted_commits |
| 176 |
) |
| 177 |
return ( |
| 178 |
"commit validation: failed!\n" |
| 179 |
"please enter a commit message in the commitizen format.\n" |
| 180 |
f"{displayed_msgs_content}\n" |
| 181 |
f"pattern: {self.schema_pattern()}" |
| 182 |
) |
| 183 |
``` |
| 184 |
|
| 185 |
## Custom changelog generator |
| 186 |
|
| 187 |
The changelog generator should just work in a very basic manner without touching anything. |
| 188 |
You can customize it of course, and the following variables are the ones you need to add to your custom `BaseCommitizen`. |
| 189 |
|
| 190 |
| Parameter | Type | Required | Description | |
| 191 |
| -------------------------------- | ------------------------------------------------------------------------ | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | |
| 192 |
| `commit_parser` | `str` | NO | Regex which should provide the variables explained in the [changelog description][changelog-des] | |
| 193 |
| `changelog_pattern` | `str` | NO | Regex to validate the commits, this is useful to skip commits that don't meet your ruling standards like a Merge. Usually the same as bump_pattern | |
| 194 |
| `change_type_map` | `dict` | NO | Convert the title of the change type that will appear in the changelog, if a value is not found, the original will be provided | |
| 195 |
| `changelog_message_builder_hook` | `method: (dict, git.GitCommit) -> dict | list | None` | NO | Customize with extra information your message output, like adding links, this function is executed per parsed commit. Each GitCommit contains the following attrs: `rev`, `title`, `body`, `author`, `author_email`. Returning a falsy value ignore the commit. | |
| 196 |
| `changelog_hook` | `method: (full_changelog: str, partial_changelog: Optional[str]) -> str` | NO | Receives the whole and partial (if used incremental) changelog. Useful to send slack messages or notify a compliance department. Must return the full_changelog | |
| 197 |
| `changelog_release_hook` | `method: (release: dict, tag: git.GitTag) -> dict` | NO | Receives each generated changelog release and its associated tag. Useful to enrich releases before they are rendered. Must return the update release |
| 198 |
|
| 199 |
```python title="cz_strange.py" |
| 200 |
from commitizen.cz.base import BaseCommitizen |
| 201 |
import chat |
| 202 |
import compliance |
| 203 |
|
| 204 |
|
| 205 |
class StrangeCommitizen(BaseCommitizen): |
| 206 |
changelog_pattern = r"^(break|new|fix|hotfix)" |
| 207 |
commit_parser = r"^(?P<change_type>feat|fix|refactor|perf|BREAKING CHANGE)(?:\((?P<scope>[^()\r\n]*)\)|\()?(?P<breaking>!)?:\s(?P<message>.*)?" |
| 208 |
change_type_map = { |
| 209 |
"feat": "Features", |
| 210 |
"fix": "Bug Fixes", |
| 211 |
"refactor": "Code Refactor", |
| 212 |
"perf": "Performance improvements", |
| 213 |
} |
| 214 |
|
| 215 |
def changelog_message_builder_hook( |
| 216 |
self, parsed_message: dict, commit: git.GitCommit |
| 217 |
) -> dict | list | None: |
| 218 |
rev = commit.rev |
| 219 |
m = parsed_message["message"] |
| 220 |
parsed_message[ |
| 221 |
"message" |
| 222 |
] = f"{m} {rev} [{commit.author}]({commit.author_email})" |
| 223 |
return parsed_message |
| 224 |
|
| 225 |
def changelog_release_hook(self, release: dict, tag: git.GitTag) -> dict: |
| 226 |
release["author"] = tag.author |
| 227 |
return release |
| 228 |
|
| 229 |
def changelog_hook( |
| 230 |
self, full_changelog: str, partial_changelog: Optional[str] |
| 231 |
) -> str: |
| 232 |
"""Executed at the end of the changelog generation |
| 233 |
|
| 234 |
full_changelog: it's the output about to being written into the file |
| 235 |
partial_changelog: it's the new stuff, this is useful to send slack messages or |
| 236 |
similar |
| 237 |
|
| 238 |
Return: |
| 239 |
the new updated full_changelog |
| 240 |
""" |
| 241 |
if partial_changelog: |
| 242 |
chat.room("#committers").notify(partial_changelog) |
| 243 |
if full_changelog: |
| 244 |
compliance.send(full_changelog) |
| 245 |
full_changelog.replace(" fix ", " **fix** ") |
| 246 |
return full_changelog |
| 247 |
``` |
| 248 |
|
| 249 |
## Raise Customize Exception |
| 250 |
|
| 251 |
If you want `commitizen` to catch your exception and print the message, you'll have to inherit `CzException`. |
| 252 |
|
| 253 |
```python |
| 254 |
from commitizen.cz.exception import CzException |
| 255 |
|
| 256 |
|
| 257 |
class NoSubjectProvidedException(CzException): |
| 258 |
... |
| 259 |
``` |
| 260 |
|
| 261 |
## Migrating from legacy plugin format |
| 262 |
|
| 263 |
Commitizen migrated to a new plugin format relying on `importlib.metadata.EntryPoint`. |
| 264 |
Migration should be straight-forward for legacy plugins: |
| 265 |
|
| 266 |
- Remove the `discover_this` line from your plugin module |
| 267 |
- Expose the plugin class under as a `commitizen.plugin` entrypoint. |
| 268 |
|
| 269 |
The name of the plugin is now determined by the name of the entrypoint. |
| 270 |
|
| 271 |
### Example |
| 272 |
|
| 273 |
If you were having a `CzPlugin` class in a `cz_plugin.py` module like this: |
| 274 |
|
| 275 |
```python |
| 276 |
from commitizen.cz.base import BaseCommitizen |
| 277 |
|
| 278 |
|
| 279 |
class PluginCz(BaseCommitizen): |
| 280 |
... |
| 281 |
|
| 282 |
|
| 283 |
discover_this = PluginCz |
| 284 |
``` |
| 285 |
|
| 286 |
Then remove the `discover_this` line: |
| 287 |
|
| 288 |
```python |
| 289 |
from commitizen.cz.base import BaseCommitizen |
| 290 |
|
| 291 |
|
| 292 |
class PluginCz(BaseCommitizen): |
| 293 |
... |
| 294 |
``` |
| 295 |
|
| 296 |
and expose the class as entrypoint in your `setuptools`: |
| 297 |
|
| 298 |
```python |
| 299 |
from setuptools import setup |
| 300 |
|
| 301 |
setup( |
| 302 |
name="MyPlugin", |
| 303 |
version="0.1.0", |
| 304 |
py_modules=["cz_plugin"], |
| 305 |
entry_points={"commitizen.plugin": ["plugin = cz_plugin:PluginCz"]}, |
| 306 |
..., |
| 307 |
) |
| 308 |
``` |
| 309 |
|
| 310 |
Then your plugin will be available under the name `plugin`. |