-
-
Notifications
You must be signed in to change notification settings - Fork 279
/
Copy pathchangelog.py
205 lines (175 loc) · 7.51 KB
/
changelog.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
import os.path
import re
from difflib import SequenceMatcher
from operator import itemgetter
from typing import Callable, Dict, List, Optional
from packaging.version import parse
from commitizen import changelog, defaults, factory, git, out, version_types
from commitizen.config import BaseConfig
from commitizen.defaults import DEFAULT_SETTINGS
from commitizen.exceptions import (
DryRunExit,
NoCommitsFoundError,
NoPatternMapError,
NoRevisionError,
NotAGitProjectError,
NotAllowed,
)
from commitizen.git import GitTag, smart_open
from commitizen.tags import make_tag_pattern, tag_from_version
class Changelog:
"""Generate a changelog based on the commit history."""
def __init__(self, config: BaseConfig, args):
if not git.is_git_project():
raise NotAGitProjectError()
self.config: BaseConfig = config
self.cz = factory.commiter_factory(self.config)
self.start_rev = args.get("start_rev") or self.config.settings.get(
"changelog_start_rev"
)
self.file_name = args.get("file_name") or self.config.settings.get(
"changelog_file"
)
self.incremental = args["incremental"] or self.config.settings.get(
"changelog_incremental"
)
self.dry_run = args["dry_run"]
self.current_version = (
args.get("current_version") or self.config.settings.get("version") or ""
)
self.current_version_instance = (
parse(self.current_version) if self.current_version else None
)
self.unreleased_version = args["unreleased_version"]
self.change_type_map = (
self.config.settings.get("change_type_map") or self.cz.change_type_map
)
self.change_type_order = (
self.config.settings.get("change_type_order")
or self.cz.change_type_order
or defaults.change_type_order
)
self.rev_range = args.get("rev_range")
self.tag_format: str = args.get("tag_format") or self.config.settings.get(
"tag_format", DEFAULT_SETTINGS["tag_format"]
)
self.merge_prerelease = args.get(
"merge_prerelease"
) or self.config.settings.get("changelog_merge_prerelease")
version_type = self.config.settings.get("version_type")
self.version_type = version_type and version_types.VERSION_TYPES[version_type]
tag_regex = args.get("tag_regex") or self.config.settings.get("tag_regex")
if not tag_regex:
tag_regex = make_tag_pattern(self.tag_format)
self.tag_pattern = re.compile(str(tag_regex), re.VERBOSE | re.IGNORECASE)
def _find_incremental_rev(self, latest_version: str, tags: List[GitTag]) -> str:
"""Try to find the 'start_rev'.
We use a similarity approach. We know how to parse the version from the markdown
changelog, but not the whole tag, we don't even know how's the tag made.
This 'smart' function tries to find a similarity between the found version number
and the available tag.
The SIMILARITY_THRESHOLD is an empirical value, it may have to be adjusted based
on our experience.
"""
SIMILARITY_THRESHOLD = 0.89
tag_ratio = map(
lambda tag: (SequenceMatcher(None, latest_version, tag.name).ratio(), tag),
tags,
)
try:
score, tag = max(tag_ratio, key=itemgetter(0))
except ValueError:
raise NoRevisionError()
if score < SIMILARITY_THRESHOLD:
raise NoRevisionError()
start_rev = tag.name
return start_rev
def write_changelog(
self, changelog_out: str, lines: List[str], changelog_meta: Dict
):
if not isinstance(self.file_name, str):
raise NotAllowed(
"Changelog file name is broken.\n"
"Check the flag `--file-name` in the terminal "
f"or the setting `changelog_file` in {self.config.path}"
)
changelog_hook: Optional[Callable] = self.cz.changelog_hook
with smart_open(self.file_name, "w") as changelog_file:
partial_changelog: Optional[str] = None
if self.incremental:
new_lines = changelog.incremental_build(
changelog_out, lines, changelog_meta
)
changelog_out = "".join(new_lines)
partial_changelog = changelog_out
if changelog_hook:
changelog_out = changelog_hook(changelog_out, partial_changelog)
changelog_file.write(changelog_out)
def __call__(self):
commit_parser = self.cz.commit_parser
changelog_pattern = self.cz.changelog_pattern
start_rev = self.start_rev
unreleased_version = self.unreleased_version
changelog_meta: Dict = {}
change_type_map: Optional[Dict] = self.change_type_map
changelog_message_builder_hook: Optional[
Callable
] = self.cz.changelog_message_builder_hook
merge_prerelease = self.merge_prerelease
if not changelog_pattern or not commit_parser:
raise NoPatternMapError(
f"'{self.config.settings['name']}' rule does not support changelog"
)
if self.incremental and self.rev_range:
raise NotAllowed("--incremental cannot be combined with a rev_range")
# Don't continue if no `file_name` specified.
assert self.file_name
tags = git.get_tags(pattern=self.tag_pattern)
if not tags:
tags = []
end_rev = ""
if self.incremental:
changelog_meta = changelog.get_metadata(self.file_name)
latest_version = changelog_meta.get("latest_version")
if latest_version:
latest_tag_version: str = tag_from_version(
latest_version,
tag_format=self.tag_format,
version_type_cls=self.version_type,
)
start_rev = self._find_incremental_rev(latest_tag_version, tags)
if self.rev_range:
start_rev, end_rev = changelog.get_oldest_and_newest_rev(
tags,
version=self.rev_range,
tag_format=self.tag_format,
version_type_cls=self.version_type,
)
commits = git.get_commits(start=start_rev, end=end_rev, args="--topo-order")
if not commits and (
self.current_version_instance is None
or not self.current_version_instance.is_prerelease
):
raise NoCommitsFoundError("No commits found")
tree = changelog.generate_tree_from_commits(
commits,
tags,
commit_parser,
changelog_pattern,
unreleased_version,
change_type_map=change_type_map,
changelog_message_builder_hook=changelog_message_builder_hook,
merge_prerelease=merge_prerelease,
)
if self.change_type_order:
tree = changelog.order_changelog_tree(tree, self.change_type_order)
changelog_out = changelog.render_changelog(tree)
changelog_out = changelog_out.lstrip("\n")
if self.dry_run:
out.write(changelog_out)
raise DryRunExit()
lines = []
if self.incremental and os.path.isfile(self.file_name):
with open(self.file_name, "r") as changelog_file:
lines = changelog_file.readlines()
self.write_changelog(changelog_out, lines, changelog_meta)