| 1 |
#!/usr/bin/env python3 |
| 2 |
|
| 3 |
"""A utility script for automating the beets release process.""" |
| 4 |
|
| 5 |
from __future__ import annotations |
| 6 |
|
| 7 |
import re |
| 8 |
import subprocess |
| 9 |
from collections.abc import Callable |
| 10 |
from contextlib import redirect_stdout |
| 11 |
from datetime import datetime, timezone |
| 12 |
from functools import partial |
| 13 |
from io import StringIO |
| 14 |
from pathlib import Path |
| 15 |
from typing import NamedTuple, TypeAlias |
| 16 |
|
| 17 |
import click |
| 18 |
import tomli |
| 19 |
from packaging.version import Version, parse |
| 20 |
from sphinx.ext import intersphinx |
| 21 |
|
| 22 |
from docs.conf import rst_epilog |
| 23 |
|
| 24 |
BASE = Path(__file__).parent.parent.absolute() |
| 25 |
PYPROJECT = BASE / "pyproject.toml" |
| 26 |
CHANGELOG = BASE / "docs" / "changelog.rst" |
| 27 |
DOCS = "https://beets.readthedocs.io/en/stable" |
| 28 |
|
| 29 |
VERSION_HEADER = r"\d+\.\d+\.\d+ \([^)]+\)" |
| 30 |
RST_LATEST_CHANGES = re.compile( |
| 31 |
rf"{VERSION_HEADER}\n--+\s+(.+?)\n\n+{VERSION_HEADER}", re.DOTALL |
| 32 |
) |
| 33 |
|
| 34 |
Replacement: TypeAlias = "tuple[str, str | Callable[[re.Match[str]], str]]" |
| 35 |
|
| 36 |
|
| 37 |
class Ref(NamedTuple): |
| 38 |
"""A reference to documentation with ID, path, and optional title.""" |
| 39 |
|
| 40 |
id: str |
| 41 |
path: str | None |
| 42 |
title: str | None |
| 43 |
|
| 44 |
@classmethod |
| 45 |
def from_line(cls, line: str) -> Ref: |
| 46 |
"""Create Ref from a Sphinx objects.inv line. |
| 47 |
|
| 48 |
Each line has the following structure: |
| 49 |
<id> [optional title : ] <relative-url-path> |
| 50 |
|
| 51 |
See the output of |
| 52 |
python -m sphinx.ext.intersphinx docs/_build/html/objects.inv |
| 53 |
""" |
| 54 |
if len(line_parts := line.split(" ", 1)) == 1: |
| 55 |
return cls(line, None, None) |
| 56 |
|
| 57 |
id_, path_with_name = line_parts |
| 58 |
parts = [p.strip() for p in path_with_name.split(":", 1)] |
| 59 |
|
| 60 |
if len(parts) == 1: |
| 61 |
path, name = parts[0], None |
| 62 |
else: |
| 63 |
name, path = parts |
| 64 |
|
| 65 |
return cls(id_, path, name) |
| 66 |
|
| 67 |
@property |
| 68 |
def url(self) -> str: |
| 69 |
"""Full documentation URL.""" |
| 70 |
return f"{DOCS}/{self.path}" |
| 71 |
|
| 72 |
@property |
| 73 |
def name(self) -> str: |
| 74 |
"""Display name (title if available, otherwise ID).""" |
| 75 |
return self.title or self.id |
| 76 |
|
| 77 |
|
| 78 |
def get_refs() -> dict[str, Ref]: |
| 79 |
"""Parse Sphinx objects.inv and return dict of documentation references.""" |
| 80 |
objects_filepath = Path("docs/_build/html/objects.inv") |
| 81 |
if not objects_filepath.exists(): |
| 82 |
raise ValueError("Documentation does not exist. Run 'poe docs' first.") |
| 83 |
|
| 84 |
captured_output = StringIO() |
| 85 |
|
| 86 |
with redirect_stdout(captured_output): |
| 87 |
intersphinx.inspect_main([str(objects_filepath)]) |
| 88 |
|
| 89 |
lines = captured_output.getvalue().replace("\t", " ").splitlines() |
| 90 |
return { |
| 91 |
r.id: r |
| 92 |
for ln in lines |
| 93 |
if ln.startswith(" ") and (r := Ref.from_line(ln.strip())) |
| 94 |
} |
| 95 |
|
| 96 |
|
| 97 |
def create_rst_replacements() -> list[Replacement]: |
| 98 |
"""Generate list of pattern replacements for RST changelog.""" |
| 99 |
refs = get_refs() |
| 100 |
|
| 101 |
def make_ref_link(ref_id: str, name: str | None = None) -> str: |
| 102 |
if ref_id.endswith("-cmd"): |
| 103 |
name = f"{ref_id.removesuffix('-cmd')} command" |
| 104 |
try: |
| 105 |
ref = refs[ref_id] |
| 106 |
except KeyError: |
| 107 |
return f"``{name or ref_id}``" |
| 108 |
else: |
| 109 |
return rf"`{name or ref.name} <{ref.url}>`_" |
| 110 |
|
| 111 |
commands = "|".join(r.split("-")[0] for r in refs if r.endswith("-cmd")) |
| 112 |
plugins = "|".join( |
| 113 |
r.split("/")[-1] for r in refs if r.startswith("plugins/") |
| 114 |
) |
| 115 |
explicit_replacements = dict( |
| 116 |
line.removeprefix(".. ").split(" replace:: ") |
| 117 |
for line in filter(None, rst_epilog.splitlines()) |
| 118 |
) |
| 119 |
return [ |
| 120 |
# Replace explicitly defined substitutions from rst_epilog |
| 121 |
# |BeetsPlugin| -> :class:`beets.plugins.BeetsPlugin` |
| 122 |
(r"\|\w[^ ]*\|", lambda m: explicit_replacements.get(m[0], m[0])), |
| 123 |
# Replace Sphinx directives by documentation URLs, e.g., |
| 124 |
# :ref:`/plugins/autobpm` -> [AutoBPM Plugin](DOCS/plugins/autobpm.html) # noqa: E501 |
| 125 |
# :ref:`list-cmd` -> [list command](DOCS/reference/cli.html#list-cmd) |
| 126 |
( |
| 127 |
r":(?:ref|doc|class|conf):`+~?(?:([^`<]+)<)?/?([\w.:/_-]+)>?`+", |
| 128 |
lambda m: make_ref_link(m[2], m[1]), |
| 129 |
), |
| 130 |
# Convert command references to documentation URLs |
| 131 |
# `beet move` or `move` command -> [move command](DOCS/reference/cli.html#move-cmd) # noqa: E501 |
| 132 |
( |
| 133 |
rf"`+beet ({commands})`+|`+({commands})`+(?= command)", |
| 134 |
lambda m: make_ref_link(f"{m[1] or m[2]}-cmd"), |
| 135 |
), |
| 136 |
# Convert plugin references to documentation URLs |
| 137 |
# `fetchart` plugin -> [fetchart](DOCS/plugins/fetchart.html) |
| 138 |
(rf"`+({plugins})`+", lambda m: make_ref_link(f"plugins/{m[1]}")), |
| 139 |
# Convert bug references to GitHub issue links |
| 140 |
(r":bug:`(\d+)`", r":bug: (#\1)"), |
| 141 |
# Convert user references to GitHub @mentions |
| 142 |
(r":user:`(\w+)`", r"\@\1"), |
| 143 |
] |
| 144 |
|
| 145 |
|
| 146 |
order_bullet_points = partial( |
| 147 |
re.compile(r"(\n- .*?(?=\n(?! *(-|\d\.) )|$))", flags=re.DOTALL).sub, |
| 148 |
lambda m: "\n- ".join(sorted(m.group().split("\n- "), key=str.lower)), |
| 149 |
) |
| 150 |
|
| 151 |
|
| 152 |
def update_docs_config(text: str, new: Version) -> str: |
| 153 |
new_major_minor = f"{new.major}.{new.minor}" |
| 154 |
text = re.sub(r"(?<=version = )[^\n]+", f'"{new_major_minor}"', text) |
| 155 |
return re.sub(r"(?<=release = )[^\n]+", f'"{new}"', text) |
| 156 |
|
| 157 |
|
| 158 |
def update_changelog(text: str, new: Version) -> str: |
| 159 |
new_header = f"{new} ({datetime.now(timezone.utc).date():%B %d, %Y})" |
| 160 |
return re.sub( |
| 161 |
# do not match if the new version is already present |
| 162 |
r"\nUnreleased\n--+\n", |
| 163 |
rf""" |
| 164 |
Unreleased |
| 165 |
---------- |
| 166 |
|
| 167 |
.. |
| 168 |
New features |
| 169 |
~~~~~~~~~~~~ |
| 170 |
|
| 171 |
.. |
| 172 |
Bug fixes |
| 173 |
~~~~~~~~~ |
| 174 |
|
| 175 |
.. |
| 176 |
For plugin developers |
| 177 |
~~~~~~~~~~~~~~~~~~~~~ |
| 178 |
|
| 179 |
.. |
| 180 |
Other changes |
| 181 |
~~~~~~~~~~~~~ |
| 182 |
|
| 183 |
{new_header} |
| 184 |
{"-" * len(new_header)} |
| 185 |
""", |
| 186 |
text, |
| 187 |
) |
| 188 |
|
| 189 |
|
| 190 |
UpdateVersionCallable = Callable[[str, Version], str] |
| 191 |
FILENAME_AND_UPDATE_TEXT: list[tuple[Path, UpdateVersionCallable]] = [ |
| 192 |
( |
| 193 |
PYPROJECT, |
| 194 |
lambda text, new: re.sub(r"(?<=\nversion = )[^\n]+", f'"{new}"', text), |
| 195 |
), |
| 196 |
( |
| 197 |
BASE / "beets" / "__init__.py", |
| 198 |
lambda text, new: re.sub( |
| 199 |
r"(?<=__version__ = )[^\n]+", f'"{new}"', text |
| 200 |
), |
| 201 |
), |
| 202 |
(CHANGELOG, update_changelog), |
| 203 |
(BASE / "docs" / "conf.py", update_docs_config), |
| 204 |
] |
| 205 |
|
| 206 |
|
| 207 |
def validate_new_version( |
| 208 |
ctx: click.Context, param: click.Argument, value: Version |
| 209 |
) -> Version: |
| 210 |
"""Validate the version is newer than the current one.""" |
| 211 |
with PYPROJECT.open("rb") as f: |
| 212 |
current = parse(tomli.load(f)["project"]["version"]) |
| 213 |
|
| 214 |
if not value > current: |
| 215 |
msg = f"version must be newer than {current}" |
| 216 |
raise click.BadParameter(msg) |
| 217 |
|
| 218 |
return value |
| 219 |
|
| 220 |
|
| 221 |
def bump_version(new: Version) -> None: |
| 222 |
"""Update the version number in specified files.""" |
| 223 |
for path, perform_update in FILENAME_AND_UPDATE_TEXT: |
| 224 |
with path.open("r+") as f: |
| 225 |
contents = f.read() |
| 226 |
f.seek(0) |
| 227 |
f.write(perform_update(contents, new)) |
| 228 |
f.truncate() |
| 229 |
|
| 230 |
|
| 231 |
def rst2md(text: str) -> str: |
| 232 |
"""Use Pandoc to convert text from ReST to Markdown.""" |
| 233 |
return ( |
| 234 |
subprocess.check_output( |
| 235 |
["pandoc", "--from=rst", "--to=gfm+hard_line_breaks"], |
| 236 |
input=text.encode(), |
| 237 |
) |
| 238 |
.decode() |
| 239 |
.strip() |
| 240 |
) |
| 241 |
|
| 242 |
|
| 243 |
def get_changelog_contents() -> str | None: |
| 244 |
if m := RST_LATEST_CHANGES.search(CHANGELOG.read_text()): |
| 245 |
return m.group(1) |
| 246 |
|
| 247 |
return None |
| 248 |
|
| 249 |
|
| 250 |
def changelog_as_markdown(rst: str) -> str: |
| 251 |
"""Get the latest changelog entry as hacked up Markdown.""" |
| 252 |
for pattern, repl in create_rst_replacements(): |
| 253 |
rst = re.sub(pattern, repl, rst, flags=re.M | re.DOTALL) |
| 254 |
|
| 255 |
md = rst2md(rst) |
| 256 |
|
| 257 |
# order bullet points in each of the lists alphabetically to |
| 258 |
# improve readability |
| 259 |
return order_bullet_points(md) |
| 260 |
|
| 261 |
|
| 262 |
@click.group() |
| 263 |
def cli() -> None: |
| 264 |
pass |
| 265 |
|
| 266 |
|
| 267 |
@cli.command() |
| 268 |
@click.argument("version", type=Version, callback=validate_new_version) |
| 269 |
def bump(version: Version) -> None: |
| 270 |
"""Bump the version in project files.""" |
| 271 |
bump_version(version) |
| 272 |
|
| 273 |
|
| 274 |
@cli.command() |
| 275 |
def changelog() -> None: |
| 276 |
"""Get the most recent version's changelog as Markdown.""" |
| 277 |
if changelog := get_changelog_contents(): |
| 278 |
try: |
| 279 |
print(changelog_as_markdown(changelog)) |
| 280 |
except ValueError as e: |
| 281 |
raise click.exceptions.UsageError(str(e)) |
| 282 |
|
| 283 |
|
| 284 |
if __name__ == "__main__": |
| 285 |
cli() |