Debian Codegraph @

docs/customization/python_class.md

raw
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 ### Filter commits before bump and changelog generation
122
123 Custom rules can select which commits are relevant before Commitizen calculates a
124 version increment or generates a changelog.
125
126 | Method | Used by | Default behavior |
127 | ----------------------------------- | ----------------------------------------------------- | ---------------------------- |
128 | `filter_commits` | Shared by the operation-specific methods | Return all commits unchanged |
129 | `filter_commits_before_bump` | `cz bump` and `cz version --next USE_GIT_COMMITS` | Call `filter_commits` |
130 | `filter_commits_before_changelog` | `cz changelog`, including changelogs created by bump | Call `filter_commits` |
131
132 Override `filter_commits` when bump and changelog generation should use the same
133 selection. Override an operation-specific method when their selections should
134 differ. These methods do not affect `cz check`.
135
136 For example, a monorepo can use a full commit-message metadata line to associate
137 commits with applications:
138
139 ```text
140 feat: add shared library
141
142 Applications: ['AppA', 'AppB']
143 ```
144
145 A plugin can retain the built-in Conventional Commits behavior while filtering
146 on that metadata:
147
148 ```python title="cz_applications.py"
149 import re
150
151 from commitizen import git
152 from commitizen.cz.conventional_commits import ConventionalCommitsCz
153 from commitizen.exceptions import InvalidConfigurationError
154
155
156 class ApplicationsCommitizen(ConventionalCommitsCz):
157 """Apply Conventional Commits rules to one configured application.
158
159 Example:
160 Configure `app = "AppA"` to keep commits whose `Applications:` metadata
161 includes `AppA`.
162 """
163
164 def filter_commits(self, commits: list[git.GitCommit]) -> list[git.GitCommit]:
165 """Keep commits associated with the configured application.
166
167 Args:
168 commits: The commits available to the current operation.
169
170 Returns:
171 Commits whose full message lists the configured application.
172
173 Raises:
174 InvalidConfigurationError: If the plugin's `app` setting is missing.
175 """
176 application = dict(self.config.settings).get("app")
177 if not isinstance(application, str) or not application:
178 raise InvalidConfigurationError(
179 "cz_applications requires a non-empty 'app' setting"
180 )
181
182 application_line = re.compile(
183 rf"""^Applications:\s*\[[^\]]*['"]{re.escape(application)}['"][^\]]*\]\s*$""",
184 re.MULTILINE,
185 )
186 return [commit for commit in commits if application_line.search(commit.message)]
187 ```
188
189 Expose the class through the plugin package:
190
191 ```toml title="pyproject.toml"
192 [project.entry-points."commitizen.plugin"]
193 cz_applications = "cz_applications:ApplicationsCommitizen"
194 ```
195
196 Then select the plugin and application in each component's configuration:
197
198 ```toml title="app-a/.cz.toml"
199 [tool.commitizen]
200 name = "cz_applications"
201 app = "AppA"
202 version = "1.0.0"
203 tag_format = "$version-app-a"
204 ```
205
206 `app` is owned and interpreted by this plugin; it is not a built-in Commitizen
207 setting. TOML keys under `[tool.commitizen]` are available through
208 `self.config.settings`. The declarative `[tool.commitizen.customize]` section
209 cannot override Python methods, so this use case requires a Python plugin.
210
211 Filtering happens before the existing rule processing. The retained commits are
212 still interpreted by `bump_pattern` and `bump_map` for version increments and by
213 `changelog_pattern` and `commit_parser` for changelog entries.
214
215 [convcomms]: https://github.com/commitizen-tools/commitizen/blob/master/commitizen/cz/conventional_commits/conventional_commits.py
216
217 ### Custom commit validation and error message
218
219 The commit message validation can be customized by overriding the `validate_commit_message` and `format_error_message`
220 methods from `BaseCommitizen`. This allows for a more detailed feedback to the user where the error originates from.
221
222 ```python
223 import re
224 from commitizen.cz.base import BaseCommitizen, ValidationResult
225 from commitizen import git
226
227
228 class CustomValidationCz(BaseCommitizen):
229 def validate_commit_message(
230 self,
231 *,
232 commit_msg: str,
233 pattern: str | None,
234 allow_abort: bool,
235 allowed_prefixes: list[str],
236 max_msg_length: int,
237 ) -> ValidationResult:
238 """Validate commit message against the pattern."""
239 if not commit_msg:
240 return allow_abort, [] if allow_abort else [f"commit message is empty"]
241 if pattern is None:
242 return True, []
243 if any(map(commit_msg.startswith, allowed_prefixes)):
244 return True, []
245 if max_msg_length:
246 msg_len = len(commit_msg.partition("\n")[0].strip())
247 if msg_len > max_msg_length:
248 return False, [
249 f"commit message is too long. Max length is {max_msg_length}"
250 ]
251 pattern_match = re.match(pattern, commit_msg)
252 if pattern_match:
253 return True, []
254 else:
255 # Perform additional validation of the commit message format
256 # and add custom error messages as needed
257 return False, ["commit message does not match the pattern"]
258
259 def format_exception_message(
260 self, ill_formatted_commits: list[tuple[git.GitCommit, list]]
261 ) -> str:
262 """Format commit errors."""
263 displayed_msgs_content = "\n".join(
264 (
265 f'commit "{commit.rev}": "{commit.message}"'
266 f"errors:\n"
267 "\n".join((f"- {error}" for error in errors))
268 )
269 for commit, errors in ill_formatted_commits
270 )
271 return (
272 "commit validation: failed!\n"
273 "please enter a commit message in the commitizen format.\n"
274 f"{displayed_msgs_content}\n"
275 f"pattern: {self.schema_pattern()}"
276 )
277 ```
278
279 ## Custom changelog generator
280
281 The changelog generator should just work in a very basic manner without touching anything.
282 You can customize it of course, and the following variables are the ones you need to add to your custom `BaseCommitizen`.
283
284 | Parameter | Type | Required | Description |
285 | -------------------------------- | ------------------------------------------------------------------------ | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
286 | `commit_parser` | `str` | NO | Regex which should provide the variables explained in the [changelog description][changelog-des] |
287 | `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 |
288 | `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 |
289 | `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. |
290 | `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 |
291 | `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
292
293 ```python title="cz_strange.py"
294 from commitizen.cz.base import BaseCommitizen
295 import chat
296 import compliance
297
298
299 class StrangeCommitizen(BaseCommitizen):
300 changelog_pattern = r"^(break|new|fix|hotfix)"
301 commit_parser = r"^(?P<change_type>feat|fix|refactor|perf|BREAKING CHANGE)(?:\((?P<scope>[^()\r\n]*)\)|\()?(?P<breaking>!)?:\s(?P<message>.*)?"
302 change_type_map = {
303 "feat": "Features",
304 "fix": "Bug Fixes",
305 "refactor": "Code Refactor",
306 "perf": "Performance improvements",
307 }
308
309 def changelog_message_builder_hook(
310 self, parsed_message: dict, commit: git.GitCommit
311 ) -> dict | list | None:
312 rev = commit.rev
313 m = parsed_message["message"]
314 parsed_message[
315 "message"
316 ] = f"{m} {rev} [{commit.author}]({commit.author_email})"
317 return parsed_message
318
319 def changelog_release_hook(self, release: dict, tag: git.GitTag) -> dict:
320 release["author"] = tag.author
321 return release
322
323 def changelog_hook(
324 self, full_changelog: str, partial_changelog: Optional[str]
325 ) -> str:
326 """Executed at the end of the changelog generation
327
328 full_changelog: it's the output about to being written into the file
329 partial_changelog: it's the new stuff, this is useful to send slack messages or
330 similar
331
332 Return:
333 the new updated full_changelog
334 """
335 if partial_changelog:
336 chat.room("#committers").notify(partial_changelog)
337 if full_changelog:
338 compliance.send(full_changelog)
339 full_changelog.replace(" fix ", " **fix** ")
340 return full_changelog
341 ```
342
343 ## Raise Customize Exception
344
345 If you want `commitizen` to catch your exception and print the message, you'll have to inherit `CzException`.
346
347 ```python
348 from commitizen.cz.exception import CzException
349
350
351 class NoSubjectProvidedException(CzException):
352 ...
353 ```
354
355 ## Migrating from legacy plugin format
356
357 Commitizen migrated to a new plugin format relying on `importlib.metadata.EntryPoint`.
358 Migration should be straight-forward for legacy plugins:
359
360 - Remove the `discover_this` line from your plugin module
361 - Expose the plugin class under as a `commitizen.plugin` entrypoint.
362
363 The name of the plugin is now determined by the name of the entrypoint.
364
365 ### Example
366
367 If you were having a `CzPlugin` class in a `cz_plugin.py` module like this:
368
369 ```python
370 from commitizen.cz.base import BaseCommitizen
371
372
373 class PluginCz(BaseCommitizen):
374 ...
375
376
377 discover_this = PluginCz
378 ```
379
380 Then remove the `discover_this` line:
381
382 ```python
383 from commitizen.cz.base import BaseCommitizen
384
385
386 class PluginCz(BaseCommitizen):
387 ...
388 ```
389
390 and expose the class as entrypoint in your `setuptools`:
391
392 ```python
393 from setuptools import setup
394
395 setup(
396 name="MyPlugin",
397 version="0.1.0",
398 py_modules=["cz_plugin"],
399 entry_points={"commitizen.plugin": ["plugin = cz_plugin:PluginCz"]},
400 ...,
401 )
402 ```
403
404 Then your plugin will be available under the name `plugin`.