Skip to content

Commit b9d1b59

Browse files
Add towncrier configuration and scripts
The changelog for 4.4.0 and later is assembled by towncrier from news fragments in doc/whatsnew/fragments/, like in pylint. bump_changelog.py is replaced by pylint's version: it updates towncrier.toml, creates the newsfile for a new minor version and runs 'towncrier build' (still invoked by tbump, same command). check_newsfragments.py validates the fragment format as a pre-commit hook.
1 parent 8d33a23 commit b9d1b59

7 files changed

Lines changed: 301 additions & 380 deletions

File tree

‎.pre-commit-config.yaml‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,13 @@ repos:
4040
exclude: tests/testdata
4141
- repo: local
4242
hooks:
43+
- id: check-newsfragments
44+
name: Check newsfragments
45+
entry: python3 script/check_newsfragments.py
46+
language: system
47+
types: [text]
48+
files: ^(doc/whatsnew/fragments)
49+
exclude: doc/whatsnew/fragments/_.*.rst
4350
- id: pylint
4451
name: pylint
4552
entry: pylint
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
{% set title = "What's new in astroid " + versiondata.version + "?" %}
2+
{{ title }}
3+
{{ underlines[0] * (title|length) }}
4+
Release date: {{ versiondata.date }}
5+
6+
{% for section, _ in sections.items() %}
7+
{% set underline = underlines[0] %}{% if section %}{{section}}
8+
{{ underline * section|length }}{% set underline = underlines[1] %}
9+
10+
{% endif %}
11+
12+
{% if sections[section] %}
13+
{% for category, val in definitions.items() if category in sections[section]%}
14+
{{ definitions[category]['name'] }}
15+
{{ underline * definitions[category]['name']|length }}
16+
17+
{% if definitions[category]['showcontent'] %}
18+
{% for text, values in sections[section][category].items() %}
19+
- {{ text }} ({{ values|join(', ') }})
20+
21+
{% endfor %}
22+
23+
{% else %}
24+
- {{ sections[section][category]['']|join(', ') }}
25+
26+
{% endif %}
27+
{% if sections[section][category]|length == 0 %}
28+
No significant changes.
29+
30+
{% else %}
31+
{% endif %}
32+
33+
{% endfor %}
34+
{% else %}
35+
No significant changes.
36+
37+
38+
{% endif %}
39+
{% endfor %}

‎requirements_minimal.txt‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# Tools used when releasing
22
contributors-txt>=1.1.0
33
tbump~=6.11
4+
towncrier>=24.8
45

56
# Tools used to run tests
67
coverage~=7.15

‎script/bump_changelog.py‎

Lines changed: 90 additions & 137 deletions
Original file line numberDiff line numberDiff line change
@@ -2,160 +2,113 @@
22
# For details: https://github.com/pylint-dev/astroid/blob/main/LICENSE
33
# Copyright (c) https://github.com/pylint-dev/astroid/blob/main/CONTRIBUTORS.txt
44

5+
"""This script updates towncrier.toml and creates a new newsfile and intermediate
6+
folders if necessary.
57
"""
6-
This script permits to upgrade the changelog in astroid or pylint when releasing a version.
7-
"""
8-
9-
# pylint: disable=logging-fstring-interpolation
108

119
from __future__ import annotations
1210

1311
import argparse
14-
import enum
15-
import logging
16-
from datetime import datetime
12+
import re
1713
from pathlib import Path
14+
from subprocess import check_call
1815

19-
DEFAULT_CHANGELOG_PATH = Path("ChangeLog")
16+
NEWSFILE_PATTERN = re.compile(r"doc/whatsnew/\d/\d.\d+/index\.rst")
17+
NEWSFILE_PATH = "doc/whatsnew/{major}/{major}.{minor}/index.rst"
18+
TOWNCRIER_CONFIG_FILE = Path("towncrier.toml")
19+
TOWNCRIER_VERSION_PATTERN = re.compile(r"version = \"(\d+\.\d+\.\d+)\"")
2020

21-
RELEASE_DATE_TEXT = "Release date: TBA"
22-
WHATS_NEW_TEXT = "What's New in astroid"
23-
TODAY = datetime.now()
24-
FULL_WHATS_NEW_TEXT = WHATS_NEW_TEXT + " {version}?"
25-
NEW_RELEASE_DATE_MESSAGE = f"Release date: {TODAY.strftime('%Y-%m-%d')}"
21+
NEWSFILE_CONTENT_TEMPLATE = """
22+
***************************
23+
What's New in astroid {major}.{minor}
24+
***************************
25+
26+
.. towncrier release notes start
27+
"""
2628

2729

2830
def main() -> None:
29-
parser = argparse.ArgumentParser(__doc__)
30-
parser.add_argument("version", help="The version we want to release")
31+
parser = argparse.ArgumentParser()
32+
parser.add_argument("version", help="The new version to set")
3133
parser.add_argument(
32-
"-v", "--verbose", action="store_true", default=False, help="Logging or not"
34+
"--dry-run",
35+
action="store_true",
36+
help="Just show what would be done, don't write anything",
3337
)
3438
args = parser.parse_args()
35-
if args.verbose:
36-
logging.basicConfig(level=logging.DEBUG)
37-
logging.debug(f"Launching bump_changelog with args: {args}")
38-
if any(s in args.version for s in ("dev", "a", "b", "rc")):
39-
return
40-
with open(DEFAULT_CHANGELOG_PATH, encoding="utf-8") as f:
41-
content = f.read()
42-
content = transform_content(content, args.version)
43-
with open(DEFAULT_CHANGELOG_PATH, "w", encoding="utf8") as f:
44-
f.write(content)
45-
46-
47-
class VersionType(enum.Enum):
48-
MAJOR = 0
49-
MINOR = 1
50-
PATCH = 2
51-
52-
53-
def get_next_version(version: str, version_type: VersionType) -> str:
54-
new_version = version.split(".")
55-
part_to_increase = new_version[version_type.value]
56-
if "-" in part_to_increase:
57-
part_to_increase = part_to_increase.split("-")[0]
58-
for i in range(version_type.value, 3):
59-
new_version[i] = "0"
60-
new_version[version_type.value] = str(int(part_to_increase) + 1)
61-
return ".".join(new_version)
62-
63-
64-
def get_next_versions(version: str, version_type: VersionType) -> list[str]:
65-
if version_type == VersionType.PATCH:
66-
# "2.6.1" => ["2.6.2"]
67-
return [get_next_version(version, VersionType.PATCH)]
68-
if version_type == VersionType.MINOR:
69-
# "2.6.0" => ["2.7.0", "2.6.1"]
70-
assert version.endswith(".0"), f"{version} does not look like a minor version"
71-
else:
72-
# "3.0.0" => ["3.1.0", "3.0.1"]
73-
assert version.endswith(".0.0"), f"{version} does not look like a major version"
74-
next_minor_version = get_next_version(version, VersionType.MINOR)
75-
next_patch_version = get_next_version(version, VersionType.PATCH)
76-
logging.debug(f"Getting the new version for {version} - {version_type.name}")
77-
return [next_minor_version, next_patch_version]
78-
79-
80-
def get_version_type(version: str) -> VersionType:
81-
if version.endswith(".0.0"):
82-
version_type = VersionType.MAJOR
83-
elif version.endswith(".0"):
84-
version_type = VersionType.MINOR
85-
else:
86-
version_type = VersionType.PATCH
87-
return version_type
88-
89-
90-
def get_whats_new(
91-
version: str, add_date: bool = False, change_date: bool = False
92-
) -> str:
93-
whats_new_text = FULL_WHATS_NEW_TEXT.format(version=version)
94-
result = [whats_new_text, "=" * len(whats_new_text)]
95-
if add_date and change_date:
96-
result += [NEW_RELEASE_DATE_MESSAGE]
97-
elif add_date:
98-
result += [RELEASE_DATE_TEXT]
99-
elif change_date:
100-
raise ValueError("Can't use change_date=True with add_date=False")
101-
logging.debug(
102-
f"version='{version}', add_date='{add_date}', change_date='{change_date}': {result}"
103-
)
104-
return "\n".join(result)
105-
106-
107-
def get_all_whats_new(version: str, version_type: VersionType) -> str:
108-
result = ""
109-
for version_ in get_next_versions(version, version_type=version_type):
110-
result += get_whats_new(version_, add_date=True) + "\n" * 4
111-
return result
112-
113-
114-
def transform_content(content: str, version: str) -> str:
115-
version_type = get_version_type(version)
116-
next_version = get_next_version(version, version_type)
117-
old_date = get_whats_new(version, add_date=True)
118-
new_date = get_whats_new(version, add_date=True, change_date=True)
119-
next_version_with_date = get_all_whats_new(version, version_type)
120-
do_checks(content, next_version, version, version_type)
121-
index = content.find(old_date)
122-
logging.debug(f"Replacing\n'{old_date}'\nby\n'{new_date}'\n")
123-
content = content.replace(old_date, new_date)
124-
end_content = content[index:]
125-
content = content[:index]
126-
logging.debug(f"Adding:\n'{next_version_with_date}'\n")
127-
content += next_version_with_date + end_content
128-
return content
129-
130-
131-
def do_checks(content, next_version, version, version_type):
132-
err = "in the changelog, fix that first!"
133-
NEW_VERSION_ERROR_MSG = (
134-
f"The text for this version '{{version}}' did not exists {err}"
135-
)
136-
NEXT_VERSION_ERROR_MSG = (
137-
f"The text for the next version '{{version}}' already exists {err}"
39+
40+
if "dev" in args.version:
41+
print("'-devXY' will be cut from version in towncrier.toml")
42+
match = re.match(
43+
r"^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(-?\w+\d*)*", args.version
13844
)
139-
wn_next_version = get_whats_new(next_version)
140-
wn_this_version = get_whats_new(version)
141-
# There is only one field where the release date is TBA
142-
if version_type in [VersionType.MAJOR, VersionType.MINOR]:
143-
assert (
144-
content.count(RELEASE_DATE_TEXT) <= 1
145-
), f"There should be only one release date 'TBA' ({version}) {err}"
146-
else:
147-
next_minor_version = get_next_version(version, VersionType.MINOR)
148-
assert (
149-
content.count(RELEASE_DATE_TEXT) <= 2
150-
), f"There should be only two release dates 'TBA' ({version} and {next_minor_version}) {err}"
151-
# There is already a release note for the version we want to release
152-
assert content.count(wn_this_version) == 1, NEW_VERSION_ERROR_MSG.format(
153-
version=version
45+
if not match:
46+
print(
47+
"Fatal error - new version did not match the "
48+
"expected format (major.minor.patch[.*]). Abort!"
49+
)
50+
return
51+
major, minor, patch, suffix = match.groups()
52+
new_version = f"{major}.{minor}.{patch}"
53+
54+
new_newsfile = NEWSFILE_PATH.format(major=major, minor=minor)
55+
create_new_newsfile_if_necessary(new_newsfile, major, minor, args.dry_run)
56+
patch_towncrier_toml(new_newsfile, new_version, args.dry_run)
57+
build_changelog(suffix, args.dry_run)
58+
59+
60+
def create_new_newsfile_if_necessary(
61+
new_newsfile: str, major: str, minor: str, dry_run: bool
62+
) -> None:
63+
new_newsfile_path = Path(new_newsfile)
64+
if new_newsfile_path.exists():
65+
return
66+
67+
# create new file and add boiler plate content
68+
if dry_run:
69+
print(
70+
f"Dry run enabled - would create file {new_newsfile} "
71+
"and intermediate folders"
72+
)
73+
return
74+
75+
print("Creating new newsfile:", new_newsfile)
76+
new_newsfile_path.parent.mkdir(parents=True, exist_ok=True)
77+
new_newsfile_path.touch()
78+
new_newsfile_path.write_text(
79+
NEWSFILE_CONTENT_TEMPLATE.format(major=major, minor=minor),
80+
encoding="utf8",
15481
)
155-
# There is no release notes for the next version
156-
assert content.count(wn_next_version) == 0, NEXT_VERSION_ERROR_MSG.format(
157-
version=next_version
82+
83+
# tbump does not add and commit new files, so we add it ourselves
84+
print("Adding new newsfile to git")
85+
check_call(["git", "add", new_newsfile])
86+
87+
88+
def patch_towncrier_toml(new_newsfile: str, version: str, dry_run: bool) -> None:
89+
file_content = TOWNCRIER_CONFIG_FILE.read_text(encoding="utf-8")
90+
patched_newsfile_path = NEWSFILE_PATTERN.sub(new_newsfile, file_content)
91+
new_file_content = TOWNCRIER_VERSION_PATTERN.sub(
92+
f'version = "{version}"', patched_newsfile_path
15893
)
94+
if dry_run:
95+
print("Dry run enabled - this is what I would write:\n")
96+
print(new_file_content)
97+
return
98+
TOWNCRIER_CONFIG_FILE.write_text(new_file_content, encoding="utf-8")
99+
100+
101+
def build_changelog(suffix: str | None, dry_run: bool) -> None:
102+
if suffix:
103+
print("Not a release version, skipping changelog generation")
104+
return
105+
106+
if dry_run:
107+
print("Dry run enabled - not building changelog")
108+
return
109+
110+
print("Building changelog")
111+
check_call(["towncrier", "build", "--yes"])
159112

160113

161114
if __name__ == "__main__":

0 commit comments

Comments
 (0)