Skip to content

Commit 461d20a

Browse files
committed
feat(template): allow to override the template from cli, configuration and plugins
Fixes commitizen-tools#132 Fixes commitizen-tools#384 Fixes commitizen-tools#433 Closes commitizen-tools#376
1 parent a2cad36 commit 461d20a

15 files changed

+594
-9
lines changed

commitizen/changelog.py

+20-5
Original file line numberDiff line numberDiff line change
@@ -31,13 +31,21 @@
3131
from datetime import date
3232
from typing import Callable, Dict, Iterable, List, Optional, Tuple
3333

34-
from jinja2 import Environment, PackageLoader
34+
from jinja2 import (
35+
BaseLoader,
36+
ChoiceLoader,
37+
Environment,
38+
FileSystemLoader,
39+
PackageLoader,
40+
)
3541

3642
from commitizen import defaults
3743
from commitizen.bump import normalize_tag
3844
from commitizen.exceptions import InvalidConfigurationError, NoCommitsFoundError
3945
from commitizen.git import GitCommit, GitTag
4046

47+
DEFAULT_TEMPLATE = "keep_a_changelog_template.j2"
48+
4149

4250
def get_commit_tag(commit: GitCommit, tags: List[GitTag]) -> Optional[GitTag]:
4351
return next((tag for tag in tags if tag.rev == commit.rev), None)
@@ -139,11 +147,18 @@ def order_changelog_tree(tree: Iterable, change_type_order: List[str]) -> Iterab
139147
return sorted_tree
140148

141149

142-
def render_changelog(tree: Iterable) -> str:
143-
loader = PackageLoader("commitizen", "templates")
150+
def render_changelog(
151+
tree: Iterable,
152+
loader: Optional[BaseLoader] = None,
153+
template: Optional[str] = None,
154+
**kwargs,
155+
) -> str:
156+
loader = ChoiceLoader(
157+
[FileSystemLoader("."), loader or PackageLoader("commitizen", "templates")]
158+
)
144159
env = Environment(loader=loader, trim_blocks=True)
145-
jinja_template = env.get_template("keep_a_changelog_template.j2")
146-
changelog: str = jinja_template.render(tree=tree)
160+
jinja_template = env.get_template(template or DEFAULT_TEMPLATE)
161+
changelog: str = jinja_template.render(tree=tree, **kwargs)
147162
return changelog
148163

149164

commitizen/cli.py

+48
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import argparse
22
import logging
33
import sys
4+
from copy import deepcopy
45
from functools import partial
56
from types import TracebackType
67
from typing import List
@@ -17,6 +18,51 @@
1718
)
1819

1920
logger = logging.getLogger(__name__)
21+
22+
23+
class ParseKwargs(argparse.Action):
24+
"""
25+
Parse arguments in the for `key=value`.
26+
27+
Quoted strings are automatically unquoted.
28+
Can be submitted multiple times:
29+
30+
ex:
31+
-k key=value -k double-quotes="value" -k single-quotes='value'
32+
33+
will result in
34+
35+
namespace["opt"] == {
36+
"key": "value",
37+
"double-quotes": "value",
38+
"single-quotes": "value",
39+
}
40+
"""
41+
42+
def __call__(self, parser, namespace, kwarg, option_string=None):
43+
kwargs = getattr(namespace, self.dest, None) or {}
44+
key, value = kwarg.split("=", 1)
45+
kwargs[key] = value.strip("'\"")
46+
setattr(namespace, self.dest, kwargs)
47+
48+
49+
tpl_arguments = (
50+
{
51+
"name": ["--template", "-t"],
52+
"help": (
53+
"changelog template file name "
54+
"(relative to the current working directory)"
55+
),
56+
},
57+
{
58+
"name": ["--extra", "-e"],
59+
"action": ParseKwargs,
60+
"dest": "extras",
61+
"metavar": "EXTRA",
62+
"help": "a changelog extra variable (in the form 'key=value')",
63+
},
64+
)
65+
2066
data = {
2167
"prog": "cz",
2268
"description": (
@@ -190,6 +236,7 @@
190236
"default": None,
191237
"help": "keep major version at zero, even for breaking changes",
192238
},
239+
*deepcopy(tpl_arguments),
193240
{
194241
"name": ["--prerelease-offset"],
195242
"type": int,
@@ -252,6 +299,7 @@
252299
"If not set, it will generate changelog from the start"
253300
),
254301
},
302+
*deepcopy(tpl_arguments),
255303
],
256304
},
257305
{

commitizen/commands/bump.py

+5
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ def __init__(self, config: BaseConfig, arguments: dict):
4747
"annotated_tag",
4848
"major_version_zero",
4949
"prerelease_offset",
50+
"template",
5051
]
5152
if arguments[key] is not None
5253
},
@@ -61,6 +62,8 @@ def __init__(self, config: BaseConfig, arguments: dict):
6162
self.retry = arguments["retry"]
6263
self.pre_bump_hooks = self.config.settings["pre_bump_hooks"]
6364
self.post_bump_hooks = self.config.settings["post_bump_hooks"]
65+
self.template = arguments["template"] or self.config.settings.get("template")
66+
self.extras = arguments["extras"]
6467

6568
def is_initial_tag(self, current_tag_version: str, is_yes: bool = False) -> bool:
6669
"""Check if reading the whole git tree up to HEAD is needed."""
@@ -254,6 +257,8 @@ def __call__(self): # noqa: C901
254257
"unreleased_version": new_tag_version,
255258
"incremental": True,
256259
"dry_run": dry_run,
260+
"template": self.template,
261+
"extras": self.extras,
257262
},
258263
)
259264
changelog_cmd()

commitizen/commands/changelog.py

+9-1
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,8 @@ def __init__(self, config: BaseConfig, args):
4949
self.tag_format = args.get("tag_format") or self.config.settings.get(
5050
"tag_format"
5151
)
52+
self.template = args.get("template") or self.config.settings.get("template")
53+
self.extras = args.get("extras") or {}
5254

5355
def _find_incremental_rev(self, latest_version: str, tags: List[GitTag]) -> str:
5456
"""Try to find the 'start_rev'.
@@ -161,7 +163,13 @@ def __call__(self):
161163
)
162164
if self.change_type_order:
163165
tree = changelog.order_changelog_tree(tree, self.change_type_order)
164-
changelog_out = changelog.render_changelog(tree)
166+
167+
extras = self.cz.template_extras.copy()
168+
extras.update(self.config.settings["extras"])
169+
extras.update(self.extras)
170+
changelog_out = changelog.render_changelog(
171+
tree, loader=self.cz.template_loader, template=self.template, **extras
172+
)
165173
changelog_out = changelog_out.lstrip("\n")
166174

167175
if self.dry_run:

commitizen/cz/base.py

+9-1
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,13 @@
1+
from __future__ import annotations
2+
13
from abc import ABCMeta, abstractmethod
2-
from typing import Callable, Dict, List, Optional, Tuple
4+
from typing import Any, Callable, Dict, List, Optional, Tuple
35

6+
from jinja2 import BaseLoader
47
from prompt_toolkit.styles import Style, merge_styles
58

69
from commitizen import git
10+
from commitizen.changelog import DEFAULT_TEMPLATE
711
from commitizen.config.base_config import BaseConfig
812
from commitizen.defaults import Questions
913

@@ -40,6 +44,10 @@ class BaseCommitizen(metaclass=ABCMeta):
4044
# Executed only at the end of the changelog generation
4145
changelog_hook: Optional[Callable[[str, Optional[str]], str]] = None
4246

47+
template: str = DEFAULT_TEMPLATE
48+
template_loader: Optional[BaseLoader] = None
49+
template_extras: dict[str, Any] = {}
50+
4351
def __init__(self, config: BaseConfig):
4452
self.config = config
4553
if not self.config.settings.get("style"):

commitizen/defaults.py

+6
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from __future__ import annotations
2+
13
import pathlib
24
from collections import OrderedDict
35
from typing import Any, Dict, Iterable, List, MutableMapping, Optional, Tuple, Union
@@ -43,6 +45,8 @@ class Settings(TypedDict, total=False):
4345
pre_bump_hooks: Optional[List[str]]
4446
post_bump_hooks: Optional[List[str]]
4547
prerelease_offset: int
48+
template: Optional[str]
49+
extras: dict[str, Any]
4650

4751

4852
name: str = "cz_conventional_commits"
@@ -71,6 +75,8 @@ class Settings(TypedDict, total=False):
7175
"pre_bump_hooks": [],
7276
"post_bump_hooks": [],
7377
"prerelease_offset": 0,
78+
"template": None,
79+
"extras": {},
7480
}
7581

7682
MAJOR = "MAJOR"

docs/bump.md

+20
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@ usage: cz bump [-h] [--dry-run] [--files-only] [--local-version] [--changelog]
6060
[--devrelease DEVRELEASE] [--increment {MAJOR,MINOR,PATCH}]
6161
[--check-consistency] [--annotated-tag] [--gpg-sign]
6262
[--changelog-to-stdout] [--retry] [--major-version-zero]
63+
[--template TEMPLATE] [--extra EXTRA]
6364
[MANUAL_VERSION]
6465

6566
positional arguments:
@@ -96,6 +97,10 @@ options:
9697
--retry retry commit if it fails the 1st time
9798
--major-version-zero keep major version at zero, even for breaking changes
9899
--prerelease-offset start pre-releases with this offset
100+
--template TEMPLATE, -t TEMPLATE
101+
changelog template file name (relative to the current working directory)
102+
--extra EXTRA, -e EXTRA
103+
a changelog extra variable (in the form 'key=value')
99104
```
100105
101106
### `--files-only`
@@ -214,6 +219,21 @@ We recommend setting `major_version_zero = true` in your configuration file whil
214219
is in its initial development. Remove that configuration using a breaking-change commit to bump
215220
your project’s major version to `v1.0.0` once your project has reached maturity.
216221
222+
### `--template`
223+
224+
Provides your own changelog jinja template.
225+
See [the template customization section](customization.md#customizing-the-changelog-template)
226+
227+
### `--extra`
228+
229+
Provides your own changelog extra variables by using the `extras` settings or the `--extra/-e` parameter.
230+
231+
```bash
232+
cz bump --changelog --extra key=value -e short="quoted value"
233+
```
234+
235+
See [the template customization section](customization.md#customizing-the-changelog-template).
236+
217237
## Avoid raising errors
218238
219239
Some situations from commitizen rise an exit code different than 0.

docs/changelog.md

+20
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ This command will generate a changelog following the committing rules establishe
77
```bash
88
$ cz changelog --help
99
usage: cz changelog [-h] [--dry-run] [--file-name FILE_NAME] [--unreleased-version UNRELEASED_VERSION] [--incremental] [--start-rev START_REV]
10+
[--template TEMPLATE] [--extra EXTRA]
1011
[rev_range]
1112

1213
positional arguments:
@@ -22,6 +23,10 @@ optional arguments:
2223
--incremental generates changelog from last created version, useful if the changelog has been manually modified
2324
--start-rev START_REV
2425
start rev of the changelog.If not set, it will generate changelog from the start
26+
--template TEMPLATE, -t TEMPLATE
27+
changelog template file name (relative to the current working directory)
28+
--extra EXTRA, -e EXTRA
29+
a changelog extra variable (in the form 'key=value')
2530
```
2631
2732
### Examples
@@ -161,6 +166,21 @@ cz changelog --start-rev="v0.2.0"
161166
changelog_start_rev = "v0.2.0"
162167
```
163168
169+
### `template`
170+
171+
Provides your own changelog jinja template by using the `template` settings or the `--template` parameter.
172+
See [the template customization section](customization.md#customizing-the-changelog-template)
173+
174+
### `extras`
175+
176+
Provides your own changelog extra variables by using the `extras` settings or the `--extra/-e` parameter.
177+
178+
```bash
179+
cz changelog --extra key=value -e short="quoted value"
180+
```
181+
182+
See [the template customization section](customization.md#customizing-the-changelog-template)
183+
164184
## Hooks
165185
166186
Supported hook methods:

docs/config.md

+3
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@
2121
| `use_shortcuts` | `bool` | `false` | If enabled, commitizen will show keyboard shortcuts when selecting from a list. Define a `key` for each of your choices to set the key. [See more][shortcuts] |
2222
| `major_version_zero` | `bool` | `false` | When true, breaking changes on a `0.x` will remain as a `0.x` version. On `false`, a breaking change will bump a `0.x` version to `1.0`. [major-version-zero] |
2323
| `prerelease_offset` | `int` | `0` | In special cases it may be necessary that a prerelease cannot start with a 0, e.g. in an embedded project the individual characters are encoded in bytes. This can be done by specifying an offset from which to start counting. [prerelease-offset] |
24+
| <a name="cfg-template"></a>`template` | `str` | `None` | Provide custom changelog jinja template path relative to the current working directory. [See more (template customization)][template-customization] |
25+
| <a name="cfg-extras"></a>`extras` | `dict` | `{}` | Provide extra variables to the changelog template. [See more (template customization)][template-customization] |
2426

2527
## pyproject.toml or .cz.toml
2628

@@ -121,4 +123,5 @@ commitizen:
121123
[additional-features]: https://github.com/tmbo/questionary#additional-features
122124
[customization]: customization.md
123125
[shortcuts]: customization.md#shortcut-keys
126+
[template-customization]: customization.md#customizing-the-changelog-template
124127
[annotated-tags-vs-lightweight]: https://stackoverflow.com/a/11514139/2047185

0 commit comments

Comments
 (0)