forked from commitizen-tools/commitizen
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbump.py
More file actions
228 lines (187 loc) · 7.45 KB
/
bump.py
File metadata and controls
228 lines (187 loc) · 7.45 KB
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
import os
import re
import sys
import typing
from collections import OrderedDict
from itertools import zip_longest
from string import Template
from typing import List, Optional, Tuple, Type, Union
from packaging.version import Version
from commitizen.defaults import MAJOR, MINOR, PATCH, bump_message
from commitizen.exceptions import CurrentVersionNotFoundError
from commitizen.git import GitCommit, smart_open
if sys.version_info >= (3, 8):
from commitizen.version_types import VersionProtocol
else:
# workaround mypy issue for 3.7 python
VersionProtocol = typing.Any
def find_increment(
commits: List[GitCommit], regex: str, increments_map: Union[dict, OrderedDict]
) -> Optional[str]:
if isinstance(increments_map, dict):
increments_map = OrderedDict(increments_map)
# Most important cases are major and minor.
# Everything else will be considered patch.
select_pattern = re.compile(regex)
increment: Optional[str] = None
for commit in commits:
for message in commit.message.split("\n"):
result = select_pattern.search(message)
if result:
found_keyword = result.group(1)
new_increment = None
for match_pattern in increments_map.keys():
if re.match(match_pattern, found_keyword):
new_increment = increments_map[match_pattern]
break
if increment == "MAJOR":
break
elif increment == "MINOR" and new_increment == "MAJOR":
increment = new_increment
elif increment == "PATCH" or increment is None:
increment = new_increment
return increment
def prerelease_generator(
current_version: str, prerelease: Optional[str] = None, offset: int = 0
) -> str:
"""Generate prerelease
X.YaN # Alpha release
X.YbN # Beta release
X.YrcN # Release Candidate
X.Y # Final
This function might return something like 'alpha1'
but it will be handled by Version.
"""
if not prerelease:
return ""
version = Version(current_version)
# version.pre is needed for mypy check
if version.is_prerelease and version.pre and prerelease.startswith(version.pre[0]):
prev_prerelease: int = version.pre[1]
new_prerelease_number = prev_prerelease + 1
else:
new_prerelease_number = offset
pre_version = f"{prerelease}{new_prerelease_number}"
return pre_version
def devrelease_generator(devrelease: int = None) -> str:
"""Generate devrelease
The devrelease version should be passed directly and is not
inferred based on the previous version.
"""
if devrelease is None:
return ""
return f"dev{devrelease}"
def semver_generator(current_version: str, increment: str = None) -> str:
version = Version(current_version)
prev_release = list(version.release)
increments = [MAJOR, MINOR, PATCH]
increments_version = dict(zip_longest(increments, prev_release, fillvalue=0))
# This flag means that current version
# must remove its prerelease tag,
# so it doesn't matter the increment.
# Example: 1.0.0a0 with PATCH/MINOR -> 1.0.0
if not version.is_prerelease:
if increment == MAJOR:
increments_version[MAJOR] += 1
increments_version[MINOR] = 0
increments_version[PATCH] = 0
elif increment == MINOR:
increments_version[MINOR] += 1
increments_version[PATCH] = 0
elif increment == PATCH:
increments_version[PATCH] += 1
return str(
f"{increments_version['MAJOR']}."
f"{increments_version['MINOR']}."
f"{increments_version['PATCH']}"
)
def generate_version(
current_version: str,
increment: str,
prerelease: Optional[str] = None,
prerelease_offset: int = 0,
devrelease: Optional[int] = None,
is_local_version: bool = False,
version_type_cls: Optional[Type[VersionProtocol]] = None,
) -> VersionProtocol:
"""Based on the given increment a proper semver will be generated.
For now the rules and versioning scheme is based on
python's PEP 0440.
More info: https://www.python.org/dev/peps/pep-0440/
Example:
PATCH 1.0.0 -> 1.0.1
MINOR 1.0.0 -> 1.1.0
MAJOR 1.0.0 -> 2.0.0
"""
if version_type_cls is None:
version_type_cls = Version
if is_local_version:
version = version_type_cls(current_version)
dev_version = devrelease_generator(devrelease=devrelease)
pre_version = prerelease_generator(
str(version.local), prerelease=prerelease, offset=prerelease_offset
)
semver = semver_generator(str(version.local), increment=increment)
return version_type_cls(f"{version.public}+{semver}{pre_version}{dev_version}")
else:
dev_version = devrelease_generator(devrelease=devrelease)
pre_version = prerelease_generator(
current_version, prerelease=prerelease, offset=prerelease_offset
)
semver = semver_generator(current_version, increment=increment)
# TODO: post version
return version_type_cls(f"{semver}{pre_version}{dev_version}")
def update_version_in_files(
current_version: str, new_version: str, files: List[str], *, check_consistency=False
) -> None:
"""Change old version to the new one in every file given.
Note that this version is not the tag formatted one.
So for example, your tag could look like `v1.0.0` while your version in
the package like `1.0.0`.
"""
# TODO: separate check step and write step
for location in files:
drive, tail = os.path.splitdrive(location)
path, _, regex = tail.partition(":")
filepath = drive + path
if not regex:
regex = _version_to_regex(current_version)
current_version_found, version_file = _bump_with_regex(
filepath, current_version, new_version, regex
)
if check_consistency and not current_version_found:
raise CurrentVersionNotFoundError(
f"Current version {current_version} is not found in {location}.\n"
"The version defined in commitizen configuration and the ones in "
"version_files are possibly inconsistent."
)
# Write the file out again
with smart_open(filepath, "w") as file:
file.write(version_file)
def _bump_with_regex(
version_filepath: str, current_version: str, new_version: str, regex: str
) -> Tuple[bool, str]:
current_version_found = False
lines = []
pattern = re.compile(regex)
with open(version_filepath, "r") as f:
for line in f:
if pattern.search(line):
bumped_line = line.replace(current_version, new_version)
if bumped_line != line:
current_version_found = True
lines.append(bumped_line)
else:
lines.append(line)
return current_version_found, "".join(lines)
def _version_to_regex(version: str) -> str:
return version.replace(".", r"\.").replace("+", r"\+")
def create_commit_message(
current_version: Union[Version, str],
new_version: Union[Version, str],
message_template: str = None,
) -> str:
if message_template is None:
message_template = bump_message
t = Template(message_template)
return t.safe_substitute(current_version=current_version, new_version=new_version)