-
Notifications
You must be signed in to change notification settings - Fork 0
/
prep_release.py
223 lines (178 loc) · 7.09 KB
/
prep_release.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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
"""Script for preparing the repo for a new release."""
import argparse
import re
import subprocess # noqa: S404
import sys
from datetime import date
if sys.version_info[0:2] <= (3, 6):
raise RuntimeError("Script runs only with python 3.7 or newer.")
PATCH = ("patch", "bugfix")
MINOR = ("minor", "feature")
MAJOR = ("major", "breaking")
REPO_URL = "https://github.com/rstcheck/rstcheck-core"
#: -- UTILS ----------------------------------------------------------------------------
class PyprojectError(Exception):
"""Exception for lookup errors in pyproject.toml file."""
def _get_config_value(section: str, key: str) -> str: # noqa: CCR001
"""Extract a config value from pyproject.toml file.
:return: config value
"""
with open("pyproject.toml", encoding="utf8") as pyproject_file:
pyproject = pyproject_file.read().split("\n")
start = False
for line in pyproject:
if not start and line.strip().startswith(section):
start = True
continue
if start and line.strip().startswith("["):
break
if start and line.strip().startswith(key):
match = re.match(r"\s*" + key + r"""\s?=\s?["']{1}([^"']*)["']{1}.*""", line)
if match:
return match.group(1)
raise PyprojectError(
f"No value for key '{key}' in {section} section could be extracted."
)
raise PyprojectError(f"No '{key}' found in {section} section.")
def _set_config_value(section: str, key: str, value: str) -> None:
"""Set a config value in pyproject.toml file."""
with open("pyproject.toml", encoding="utf8") as pyproject_file:
pyproject = pyproject_file.read().split("\n")
start = False
for idx, line in enumerate(pyproject):
if not start and line.strip().startswith(section):
start = True
continue
if start and line.strip().startswith("["):
raise PyprojectError(f"No '{key}' found in {section} section.")
if start and line.strip().startswith(key):
match = re.sub(
r"(\s*" + key + r"""\s?=\s?["']{1})[^"']*(["']{1}.*)""",
f"\\g<1>{value}\\g<2>",
line,
)
pyproject[idx] = match
break
with open("pyproject.toml", "w", encoding="utf8") as pyproject_file:
pyproject_file.write("\n".join(pyproject))
#: -- MAIN -----------------------------------------------------------------------------
def bump_version(release_type: str = "patch") -> str:
"""Bump the current version for the next release.
:param release_type: type of release;
allowed values are: patch | minor/feature | major/breaking;
defaults to "patch"
:raises ValueError: when an invalid release_type is given.
:raises ValueError: when the version string from pyproject.toml is not parsable.
:return: new version string
"""
if release_type not in PATCH + MINOR + MAJOR:
raise ValueError(f"Invalid version increase type: {release_type}")
current_version = _get_config_value("[tool.poetry]", "version")
version_parts = re.match(r"(?P<major>\d+)\.(?P<minor>\d+)\.(?P<patch>\d+)", current_version)
if not version_parts:
raise ValueError(f"Unparsable version: {current_version}")
if release_type in MAJOR:
version = f"{int(version_parts.group('major')) + 1}.0.0"
elif release_type in MINOR:
version = f"{version_parts.group('major')}" f".{int(version_parts.group('minor')) + 1}.0"
elif release_type in PATCH:
version = (
f"{version_parts.group('major')}"
f".{version_parts.group('minor')}"
f".{int(version_parts.group('patch')) + 1}"
)
else:
print("Given `RELEASE TYPE` is invalid.")
sys.exit(1)
_set_config_value("[tool.poetry]", "version", version)
return version
def update_changelog(new_version: str, last_version: str, first_release: bool) -> None:
"""Update CHANGELOG.md to be release ready.
:param new_version: new version string
:param last_version: current version string
:first_release: if this is the first release
"""
with open("CHANGELOG.md", encoding="utf8") as changelog_file:
changelog_lines = changelog_file.read().split("\n")
release_line = 0
for idx, line in enumerate(changelog_lines):
if line.startswith("## Unreleased"):
release_line = idx
if release_line:
today = date.today().isoformat()
compare = f"{'' if first_release else 'v'}{last_version}...v{new_version}"
changelog_lines[release_line] = (
"## Unreleased\n"
"\n"
f"[diff v{new_version}...main]"
f"({REPO_URL}/compare/v{new_version}...main)\n"
"\n"
f"## [{new_version} ({today})]({REPO_URL}/releases/v{new_version})\n"
"\n"
f"[diff {compare}]({REPO_URL}/compare/{compare})"
)
if len(changelog_lines) - 1 >= release_line + 2:
changelog_lines.pop(release_line + 1) # Remove blank line
changelog_lines.pop(release_line + 1) # Remove [diff ...] link line
with open("CHANGELOG.md", "w", encoding="utf8") as changelog_file:
changelog_file.write("\n".join(changelog_lines))
def commit_and_tag(version: str) -> None:
"""Git commit and tag the new release."""
subprocess.run( # noqa: S603,S607
[
"git",
"commit",
"--no-verify",
f"--message=release v{version} [skip ci]",
"--include",
"pyproject.toml",
"CHANGELOG.md",
],
check=True,
)
subprocess.run( # noqa: S603,S607
["git", "tag", "-am", f"'v{version}'", f"v{version}"], check=True
)
def _parser() -> argparse.Namespace:
"""Create parser and return parsed args."""
parser = argparse.ArgumentParser()
parser.add_argument(
"increase_type",
metavar="RELEASE TYPE",
default="patch",
nargs="?",
help=(
"Release type: patch/bugfix | minor/feature | major/breaking; "
"gets ignored on `--first-release`; "
"defaults to patch"
),
)
parser.add_argument(
"--first-release",
action="store_true",
help="Flag for first release to prevent version bumping.",
)
return parser.parse_args()
def _main() -> int:
"""Prepare release main routine."""
args = _parser()
if args.first_release:
release_version = _get_config_value("[tool.poetry]", "version")
#: Get first commit
current_version = subprocess.run( # noqa: S603,S607
["git", "rev-list", "--max-parents=0", "HEAD"],
check=True,
capture_output=True,
).stdout.decode()[0:7]
else:
current_version = _get_config_value("[tool.poetry]", "version")
release_version = bump_version(args.increase_type)
update_changelog(
release_version,
current_version,
args.first_release,
)
commit_and_tag(release_version)
return 0
if __name__ == "__main__":
sys.exit(_main())