Debian Codegraph @

scripts/release.py

raw
1 #!/usr/bin/env python3
2
3 """
4 Tool to help automate changes needed in commits during and after releases
5 """
6
7 from __future__ import annotations
8
9 import argparse
10 import logging
11 import re
12 import sys
13 from datetime import datetime
14 from pathlib import Path
15 from subprocess import run
16
17 LOG = logging.getLogger(__name__)
18 NEW_VERSION_CHANGELOG_TEMPLATE = """\
19 ## Unreleased
20
21 <!-- PR authors:
22 Please include the PR number in the changelog entry, not the issue number -->
23
24 ### Highlights
25
26 <!-- Include any especially major or disruptive changes here -->
27
28 ### Stable style
29
30 <!-- Changes that affect Black's stable style -->
31
32 ### Preview style
33
34 <!-- Changes that affect Black's preview style -->
35
36 ### Configuration
37
38 <!-- Changes to how Black can be configured -->
39
40 ### Packaging
41
42 <!-- Changes to how Black is packaged, such as dependency requirements -->
43
44 ### Parser
45
46 <!-- Changes to the parser or to version autodetection -->
47
48 ### Performance
49
50 <!-- Changes that improve Black's performance. -->
51
52 ### Output
53
54 <!-- Changes to Black's terminal output and error messages -->
55
56 ### _Blackd_
57
58 <!-- Changes to blackd -->
59
60 ### Integrations
61
62 <!-- For example, Docker, GitHub Actions, pre-commit, editors -->
63
64 ### Documentation
65
66 <!-- Major changes to documentation and policies. Small docs changes
67 don't need a changelog entry. -->
68 """
69
70
71 class NoGitTagsError(Exception): ...
72
73
74 # TODO: Do better with alpha + beta releases
75 # Maybe we vendor packaging library
76 def get_git_tags(versions_only: bool = True) -> list[str]:
77 """Pull out all tags or calvers only"""
78 cp = run(["git", "tag"], capture_output=True, check=True, encoding="utf8")
79 if not cp.stdout:
80 LOG.error(f"Returned no git tags stdout: {cp.stderr}")
81 raise NoGitTagsError
82 git_tags = cp.stdout.splitlines()
83 if versions_only:
84 return [t for t in git_tags if t[0].isdigit()]
85 return git_tags
86
87
88 # TODO: Support sorting alpha/beta releases correctly
89 def tuple_calver(calver: str) -> tuple[int, ...]: # mypy can't notice maxsplit below
90 """Convert a calver string into a tuple of ints for sorting"""
91 try:
92 return tuple(map(int, calver.split(".", maxsplit=2)))
93 except ValueError:
94 return (0, 0, 0)
95
96
97 class SourceFiles:
98 def __init__(self, black_repo_dir: Path):
99 # File path fun all pathlib to be platform agnostic
100 self.black_repo_path = black_repo_dir
101 self.changes_path = self.black_repo_path / "CHANGES.md"
102 self.docs_path = self.black_repo_path / "docs"
103 self.version_doc_paths = (
104 self.docs_path / "integrations" / "source_version_control.md",
105 self.docs_path / "usage_and_configuration" / "the_basics.md",
106 self.docs_path / "guides" / "using_black_with_jupyter_notebooks.md",
107 )
108 self.current_version = self.get_current_version()
109 self.next_version = self.get_next_version()
110
111 def __str__(self) -> str:
112 return f"""\
113 > SourceFiles ENV:
114 Repo path: {self.black_repo_path}
115 CHANGES.md path: {self.changes_path}
116 docs path: {self.docs_path}
117 Current version: {self.current_version}
118 Next version: {self.next_version}
119 """
120
121 def add_template_to_changes(self) -> int:
122 """Add the template to CHANGES.md if it does not exist"""
123 LOG.info(f"Adding template to {self.changes_path}")
124
125 with self.changes_path.open("r", encoding="utf-8") as cfp:
126 changes_string = cfp.read()
127
128 if "## Unreleased" in changes_string:
129 LOG.error(f"{self.changes_path} already has unreleased template")
130 return 1
131
132 templated_changes_string = changes_string.replace(
133 "# Change Log\n",
134 f"# Change Log\n\n{NEW_VERSION_CHANGELOG_TEMPLATE}",
135 )
136
137 with self.changes_path.open("w", encoding="utf-8") as cfp:
138 cfp.write(templated_changes_string)
139
140 LOG.info(f"Added template to {self.changes_path}")
141 return 0
142
143 def cleanup_changes_template_for_release(self) -> None:
144 LOG.info(f"Cleaning up {self.changes_path}")
145
146 with self.changes_path.open("r", encoding="utf-8") as cfp:
147 changes_string = cfp.read()
148
149 # Change Unreleased to next version
150 changes_string = changes_string.replace(
151 "## Unreleased", f"## Version {self.next_version}"
152 )
153
154 # Remove all comments
155 changes_string = re.sub(r"(?m)^<!--(?>(?:.|\n)*?-->)\n+", "", changes_string)
156
157 # Remove empty subheadings
158 changes_string = re.sub(r"(?m)^###.+\n+(?=#)", "", changes_string)
159
160 with self.changes_path.open("w", encoding="utf-8") as cfp:
161 cfp.write(changes_string)
162
163 LOG.debug(f"Finished Cleaning up {self.changes_path}")
164
165 def get_current_version(self) -> str:
166 """Get the latest git (version) tag as latest version"""
167 return sorted(get_git_tags(), key=lambda k: tuple_calver(k))[-1]
168
169 def get_next_version(self) -> str:
170 """Workout the year and month + version number we need to move to"""
171 base_calver = datetime.today().strftime("%y.%m")
172 calver_parts = base_calver.split(".")
173 base_calver = f"{calver_parts[0]}.{int(calver_parts[1])}" # Remove leading 0
174 git_tags = get_git_tags()
175 same_month_releases = [
176 t for t in git_tags if t.startswith(base_calver) and "a" not in t
177 ]
178 if len(same_month_releases) < 1:
179 return f"{base_calver}.0"
180 same_month_version = same_month_releases[-1].split(".", 2)[-1]
181 return f"{base_calver}.{int(same_month_version) + 1}"
182
183 def update_repo_for_release(self) -> int:
184 """Update CHANGES.md + doc files ready for release"""
185 self.cleanup_changes_template_for_release()
186 self.update_version_in_docs()
187 return 0 # return 0 if no exceptions hit
188
189 def update_version_in_docs(self) -> None:
190 for doc_path in self.version_doc_paths:
191 LOG.info(f"Updating black version to {self.next_version} in {doc_path}")
192
193 with doc_path.open("r", encoding="utf-8") as dfp:
194 doc_string = dfp.read()
195
196 next_version_doc = doc_string.replace(
197 self.current_version, self.next_version
198 )
199
200 with doc_path.open("w", encoding="utf-8") as dfp:
201 dfp.write(next_version_doc)
202
203 LOG.debug(
204 f"Finished updating black version to {self.next_version} in {doc_path}"
205 )
206
207
208 def _handle_debug(debug: bool) -> None:
209 """Turn on debugging if asked otherwise INFO default"""
210 log_level = logging.DEBUG if debug else logging.INFO
211 logging.basicConfig(
212 format="[%(asctime)s] %(levelname)s: %(message)s (%(filename)s:%(lineno)d)",
213 level=log_level,
214 )
215
216
217 def parse_args() -> argparse.Namespace:
218 parser = argparse.ArgumentParser()
219 parser.add_argument(
220 "-a",
221 "--add-changes-template",
222 action="store_true",
223 help="Add the Unreleased template to CHANGES.md",
224 )
225 parser.add_argument(
226 "-d", "--debug", action="store_true", help="Verbose debug output"
227 )
228 args = parser.parse_args()
229 _handle_debug(args.debug)
230 return args
231
232
233 def main() -> int:
234 args = parse_args()
235
236 # Need parent.parent cause script is in scripts/ directory
237 sf = SourceFiles(Path(__file__).parent.parent)
238
239 if args.add_changes_template:
240 return sf.add_template_to_changes()
241
242 LOG.info(f"Current version detected to be {sf.current_version}")
243 LOG.info(f"Next version will be {sf.next_version}")
244 return sf.update_repo_for_release()
245
246
247 if __name__ == "__main__": # pragma: no cover
248 sys.exit(main())