Skip to content

Commit d3c89d9

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 Closes commitizen-tools#640
1 parent 17b2f02 commit d3c89d9

15 files changed

+606
-11
lines changed

commitizen/changelog.py

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,13 @@
3535
from datetime import date
3636
from typing import Callable, Iterable
3737

38-
from jinja2 import Environment, PackageLoader
38+
from jinja2 import (
39+
BaseLoader,
40+
ChoiceLoader,
41+
Environment,
42+
FileSystemLoader,
43+
PackageLoader,
44+
)
3945
from packaging.version import InvalidVersion, Version
4046

4147
from commitizen import defaults
@@ -49,6 +55,8 @@
4955
# workaround mypy issue for 3.7 python
5056
VersionProtocol = typing.Any
5157

58+
DEFAULT_TEMPLATE = "keep_a_changelog_template.j2"
59+
5260

5361
def get_commit_tag(commit: GitCommit, tags: list[GitTag]) -> GitTag | None:
5462
return next((tag for tag in tags if tag.rev == commit.rev), None)
@@ -178,11 +186,18 @@ def order_changelog_tree(tree: Iterable, change_type_order: list[str]) -> Iterab
178186
return sorted_tree
179187

180188

181-
def render_changelog(tree: Iterable) -> str:
182-
loader = PackageLoader("commitizen", "templates")
189+
def render_changelog(
190+
tree: Iterable,
191+
loader: BaseLoader | None = None,
192+
template: str | None = None,
193+
**kwargs,
194+
) -> str:
195+
loader = ChoiceLoader(
196+
[FileSystemLoader("."), loader or PackageLoader("commitizen", "templates")]
197+
)
183198
env = Environment(loader=loader, trim_blocks=True)
184-
jinja_template = env.get_template("keep_a_changelog_template.j2")
185-
changelog: str = jinja_template.render(tree=tree)
199+
jinja_template = env.get_template(template or DEFAULT_TEMPLATE)
200+
changelog: str = jinja_template.render(tree=tree, **kwargs)
186201
return changelog
187202

188203

commitizen/cli.py

Lines changed: 49 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,9 @@
33
import argparse
44
import logging
55
import sys
6-
from pathlib import Path
6+
from copy import deepcopy
77
from functools import partial
8+
from pathlib import Path
89
from types import TracebackType
910

1011
import argcomplete
@@ -19,6 +20,51 @@
1920
)
2021

2122
logger = logging.getLogger(__name__)
23+
24+
25+
class ParseKwargs(argparse.Action):
26+
"""
27+
Parse arguments in the for `key=value`.
28+
29+
Quoted strings are automatically unquoted.
30+
Can be submitted multiple times:
31+
32+
ex:
33+
-k key=value -k double-quotes="value" -k single-quotes='value'
34+
35+
will result in
36+
37+
namespace["opt"] == {
38+
"key": "value",
39+
"double-quotes": "value",
40+
"single-quotes": "value",
41+
}
42+
"""
43+
44+
def __call__(self, parser, namespace, kwarg, option_string=None):
45+
kwargs = getattr(namespace, self.dest, None) or {}
46+
key, value = kwarg.split("=", 1)
47+
kwargs[key] = value.strip("'\"")
48+
setattr(namespace, self.dest, kwargs)
49+
50+
51+
tpl_arguments = (
52+
{
53+
"name": ["--template", "-t"],
54+
"help": (
55+
"changelog template file name "
56+
"(relative to the current working directory)"
57+
),
58+
},
59+
{
60+
"name": ["--extra", "-e"],
61+
"action": ParseKwargs,
62+
"dest": "extras",
63+
"metavar": "EXTRA",
64+
"help": "a changelog extra variable (in the form 'key=value')",
65+
},
66+
)
67+
2268
data = {
2369
"prog": "cz",
2470
"description": (
@@ -198,6 +244,7 @@
198244
"default": None,
199245
"help": "keep major version at zero, even for breaking changes",
200246
},
247+
*deepcopy(tpl_arguments),
201248
{
202249
"name": ["--prerelease-offset"],
203250
"type": int,
@@ -275,6 +322,7 @@
275322
"If not set, it will include prereleases in the changelog"
276323
),
277324
},
325+
*deepcopy(tpl_arguments),
278326
],
279327
},
280328
{

commitizen/commands/bump.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ def __init__(self, config: BaseConfig, arguments: dict):
4848
"annotated_tag",
4949
"major_version_zero",
5050
"prerelease_offset",
51+
"template",
5152
]
5253
if arguments[key] is not None
5354
},
@@ -66,6 +67,8 @@ def __init__(self, config: BaseConfig, arguments: dict):
6667
"version_type"
6768
)
6869
self.version_type = version_type and version_types.VERSION_TYPES[version_type]
70+
self.template = arguments["template"] or self.config.settings.get("template")
71+
self.extras = arguments["extras"]
6972

7073
def is_initial_tag(self, current_tag_version: str, is_yes: bool = False) -> bool:
7174
"""Check if reading the whole git tree up to HEAD is needed."""
@@ -271,6 +274,8 @@ def __call__(self): # noqa: C901
271274
"unreleased_version": new_tag_version,
272275
"incremental": True,
273276
"dry_run": dry_run,
277+
"template": self.template,
278+
"extras": self.extras,
274279
},
275280
)
276281
changelog_cmd()

commitizen/commands/changelog.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,8 @@ def __init__(self, config: BaseConfig, args):
6565

6666
version_type = self.config.settings.get("version_type")
6767
self.version_type = version_type and version_types.VERSION_TYPES[version_type]
68+
self.template = args.get("template") or self.config.settings.get("template")
69+
self.extras = args.get("extras") or {}
6870

6971
def _find_incremental_rev(self, latest_version: str, tags: list[GitTag]) -> str:
7072
"""Try to find the 'start_rev'.
@@ -183,7 +185,13 @@ def __call__(self):
183185
)
184186
if self.change_type_order:
185187
tree = changelog.order_changelog_tree(tree, self.change_type_order)
186-
changelog_out = changelog.render_changelog(tree)
188+
189+
extras = self.cz.template_extras.copy()
190+
extras.update(self.config.settings["extras"])
191+
extras.update(self.extras)
192+
changelog_out = changelog.render_changelog(
193+
tree, loader=self.cz.template_loader, template=self.template, **extras
194+
)
187195
changelog_out = changelog_out.lstrip("\n")
188196

189197
if self.dry_run:

commitizen/cz/base.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
11
from __future__ import annotations
22

33
from abc import ABCMeta, abstractmethod
4-
from typing import Callable
4+
from typing import Any, Callable
55

6+
from jinja2 import BaseLoader
67
from prompt_toolkit.styles import Style, merge_styles
78

89
from commitizen import git
10+
from commitizen.changelog import DEFAULT_TEMPLATE
911
from commitizen.config.base_config import BaseConfig
1012
from commitizen.defaults import Questions
1113

@@ -43,6 +45,10 @@ class BaseCommitizen(metaclass=ABCMeta):
4345
# Executed only at the end of the changelog generation
4446
changelog_hook: Callable[[str, str | None], str] | None = None
4547

48+
template: str = DEFAULT_TEMPLATE
49+
template_loader: BaseLoader | None = None
50+
template_extras: dict[str, Any] = {}
51+
4652
def __init__(self, config: BaseConfig):
4753
self.config = config
4854
if not self.config.settings.get("style"):

commitizen/defaults.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,8 @@ class Settings(TypedDict, total=False):
5353
post_bump_hooks: list[str] | None
5454
prerelease_offset: int
5555
version_type: str | None
56+
template: str | None
57+
extras: dict[str, Any]
5658

5759

5860
name: str = "cz_conventional_commits"
@@ -84,6 +86,8 @@ class Settings(TypedDict, total=False):
8486
"post_bump_hooks": [],
8587
"prerelease_offset": 0,
8688
"version_type": None,
89+
"template": None,
90+
"extras": {},
8791
}
8892

8993
MAJOR = "MAJOR"

docs/bump.md

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@ usage: cz bump [-h] [--dry-run] [--files-only] [--local-version] [--changelog]
5858
[--devrelease DEVRELEASE] [--increment {MAJOR,MINOR,PATCH}]
5959
[--check-consistency] [--annotated-tag] [--gpg-sign]
6060
[--changelog-to-stdout] [--retry] [--major-version-zero]
61+
[--template TEMPLATE] [--extra EXTRA]
6162
[MANUAL_VERSION]
6263

6364
positional arguments:
@@ -97,6 +98,10 @@ options:
9798
--version-type {pep440,semver}
9899
choose version type
99100

101+
--template TEMPLATE, -t TEMPLATE
102+
changelog template file name (relative to the current working directory)
103+
--extra EXTRA, -e EXTRA
104+
a changelog extra variable (in the form 'key=value')
100105
```
101106
102107
### `--files-only`
@@ -241,6 +246,21 @@ Can I transition from one to the other?
241246
242247
Yes, you shouldn't have any issues.
243248
249+
### `--template`
250+
251+
Provides your own changelog jinja template.
252+
See [the template customization section](customization.md#customizing-the-changelog-template)
253+
254+
### `--extra`
255+
256+
Provides your own changelog extra variables by using the `extras` settings or the `--extra/-e` parameter.
257+
258+
```bash
259+
cz bump --changelog --extra key=value -e short="quoted value"
260+
```
261+
262+
See [the template customization section](customization.md#customizing-the-changelog-template).
263+
244264
## Avoid raising errors
245265
246266
Some situations from commitizen raise an exit code different than 0.

docs/changelog.md

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ update_changelog_on_bump = true
1414
```bash
1515
$ cz changelog --help
1616
usage: cz changelog [-h] [--dry-run] [--file-name FILE_NAME] [--unreleased-version UNRELEASED_VERSION] [--incremental] [--start-rev START_REV]
17+
[--template TEMPLATE] [--extra EXTRA]
1718
[rev_range]
1819

1920
positional arguments:
@@ -31,6 +32,11 @@ optional arguments:
3132
start rev of the changelog. If not set, it will generate changelog from the start
3233
--merge-prerelease
3334
collect all changes from prereleases into next non-prerelease. If not set, it will include prereleases in the changelog
35+
start rev of the changelog.If not set, it will generate changelog from the start
36+
--template TEMPLATE, -t TEMPLATE
37+
changelog template file name (relative to the current working directory)
38+
--extra EXTRA, -e EXTRA
39+
a changelog extra variable (in the form 'key=value')
3440
```
3541
3642
### Examples
@@ -186,6 +192,21 @@ cz changelog --merge-prerelease
186192
changelog_merge_prerelease = true
187193
```
188194
195+
### `template`
196+
197+
Provides your own changelog jinja template by using the `template` settings or the `--template` parameter.
198+
See [the template customization section](customization.md#customizing-the-changelog-template)
199+
200+
### `extras`
201+
202+
Provides your own changelog extra variables by using the `extras` settings or the `--extra/-e` parameter.
203+
204+
```bash
205+
cz changelog --extra key=value -e short="quoted value"
206+
```
207+
208+
See [the template customization section](customization.md#customizing-the-changelog-template)
209+
189210
## Hooks
190211
191212
Supported hook methods:

docs/config.md

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,22 @@ Default: `[]`
178178

179179
Calls the hook scripts **after** bumping the version. [Read more][post_bump_hooks]
180180

181+
### `template`
182+
183+
Type: `str`
184+
185+
Default: `None` (provided by plugin)
186+
187+
Provide custom changelog jinja template path relative to the current working directory. [Read more][template-customization]
188+
189+
### `extras`
190+
191+
Type: `dict[str, Any]`
192+
193+
Default: `{}`
194+
195+
Provide extra variables to the changelog template. [Read more][template-customization] |
196+
181197
## Configuration file
182198

183199
### pyproject.toml or .cz.toml
@@ -349,4 +365,5 @@ setup(
349365
[additional-features]: https://github.com/tmbo/questionary#additional-features
350366
[customization]: customization.md
351367
[shortcuts]: customization.md#shortcut-keys
368+
[template-customization]: customization.md#customizing-the-changelog-template
352369
[annotated-tags-vs-lightweight]: https://stackoverflow.com/a/11514139/2047185

0 commit comments

Comments
 (0)