-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent_version.py
More file actions
224 lines (183 loc) · 8.09 KB
/
Copy pathcontent_version.py
File metadata and controls
224 lines (183 loc) · 8.09 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
#!/usr/bin/env python3
"""Shared readers for the book's prose edition, framework pin, and changelog.
The book is a living document: its prose (the chapters under ``content/``) is versioned
independently of the site generator, PDF renderer, and other tooling. The current version is a
single line in ``content/VERSION``; the human-readable history lives in ``content/CHANGELOG.md``.
This module is imported by:
* ``site/generate.py`` — to surface the version across the web edition and build the
version-history page,
* ``scripts/build_pdf.py`` — to stamp the version into the PDF footer,
and is used as a CLI by ``.github/workflows/release-content.yml`` to cut GitHub Releases:
python scripts/content_version.py version # -> 1.1
python scripts/content_version.py tag # -> content-v1.1
python scripts/content_version.py notes # release notes for the current version
python scripts/content_version.py notes 1.0 # release notes for a specific version
Keeping the parser here (rather than in the site generator) means the release workflow never has
to import the site build, and every consumer reads the same format.
"""
from __future__ import annotations
import re
import sys
from dataclasses import dataclass, field
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
VERSION_PATH = ROOT / "content" / "VERSION"
FRAMEWORK_VERSION_PATH = ROOT / "content" / "FRAMEWORK_VERSION"
CHANGELOG_PATH = ROOT / "content" / "CHANGELOG.md"
# Git tag / GitHub Release naming for a content version, e.g. "content-v1.1".
TAG_PREFIX = "content-v"
_VERSION_RE = re.compile(r"(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)(?:\.(?:0|[1-9][0-9]*))?")
_FRAMEWORK_VERSION_RE = re.compile(
r"v(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)"
)
# "## [1.1] - 2026-07-08" -> version + date
_HEADER_RE = re.compile(r"^##\s+\[(?P<version>[^\]]+)\]\s*-\s*(?P<date>.+?)\s*$")
# "### Added"
_GROUP_RE = re.compile(r"^###\s+(?P<title>.+?)\s*$")
# "- item" / "* item"
_ITEM_RE = re.compile(r"^\s*[-*]\s+(?P<item>.+?)\s*$")
@dataclass
class ChangeGroup:
"""A labelled group of bullet items within one version (e.g. "Added")."""
title: str
items: list[str] = field(default_factory=list)
@dataclass
class Release:
"""One content version parsed from the changelog."""
version: str
date: str
summary: str
groups: list[ChangeGroup]
body: str # raw markdown between this header and the next — used as release notes
@property
def tag(self) -> str:
return f"{TAG_PREFIX}{self.version}"
def validate_version(version: str) -> str:
"""Require a two- or three-component prose edition, without a leading ``v``."""
if not _VERSION_RE.fullmatch(version):
raise ValueError(
f"Invalid content version {version!r}; expected MAJOR.MINOR or "
"MAJOR.MINOR.PATCH without a leading v or leading zeroes."
)
return version
def read_version(path: Path | None = None) -> str:
"""Return the current content version string (e.g. "1.1")."""
path = path if path is not None else VERSION_PATH
try:
text = path.read_text(encoding="utf-8").strip()
except FileNotFoundError as exc:
raise ValueError(f"Missing required content version file: {path}") from exc
return validate_version(text)
def validate_framework_version(version: str) -> str:
"""Require an exact stable upstream tag, independently of the prose edition."""
if not _FRAMEWORK_VERSION_RE.fullmatch(version):
raise ValueError(
f"Invalid framework version {version!r}; expected an exact stable tag such as v0.88.7."
)
return version
def read_framework_version(path: Path | None = None) -> str:
"""Return the validated coverage pin; never infer it from the prose edition."""
path = path if path is not None else FRAMEWORK_VERSION_PATH
try:
text = path.read_text(encoding="utf-8").strip()
except FileNotFoundError as exc:
raise ValueError(f"Missing required framework version file: {path}") from exc
return validate_framework_version(text)
def tag_for(version: str) -> str:
return f"{TAG_PREFIX}{validate_version(version)}"
def _read_changelog(path: Path | None = None) -> str:
try:
return (path if path is not None else CHANGELOG_PATH).read_text(encoding="utf-8")
except FileNotFoundError:
return ""
def parse_changelog(path: Path | None = None) -> list[Release]:
"""Parse ``content/CHANGELOG.md`` into an ordered list of releases (newest first)."""
lines = _read_changelog(path).splitlines()
# Find each "## [version] - date" header and the line range of its body.
headers: list[tuple[int, str, str]] = []
for idx, line in enumerate(lines):
match = _HEADER_RE.match(line)
if match:
headers.append((idx, match.group("version").strip(), match.group("date").strip()))
releases: list[Release] = []
for pos, (start, version, dt) in enumerate(headers):
end = headers[pos + 1][0] if pos + 1 < len(headers) else len(lines)
body_lines = lines[start + 1 : end]
body = "\n".join(body_lines).strip("\n")
summary_parts: list[str] = []
groups: list[ChangeGroup] = []
current: ChangeGroup | None = None
summary_done = False
for raw in body_lines:
line = raw.rstrip()
if not line.strip():
if summary_parts:
summary_done = True
continue
group_match = _GROUP_RE.match(line)
if group_match:
summary_done = True
current = ChangeGroup(title=group_match.group("title").strip())
groups.append(current)
continue
item_match = _ITEM_RE.match(line)
if item_match:
summary_done = True
item = item_match.group("item").strip()
if current is None:
current = ChangeGroup(title="")
groups.append(current)
current.items.append(item)
continue
# A non-blank line that is neither a group heading nor a new bullet: treat it as a
# wrapped continuation of the previous bullet (changelog items often soft-wrap), or
# as part of the intro summary if we haven't reached the bullets yet.
if current is not None and current.items:
current.items[-1] = f"{current.items[-1]} {line.strip()}"
elif not summary_done:
summary_parts.append(line.strip())
releases.append(
Release(
version=version,
date=dt,
summary=" ".join(summary_parts).strip(),
groups=groups,
body=body,
)
)
return releases
def release_for(version: str) -> Release | None:
for release in parse_changelog():
if release.version == version:
return release
return None
def notes_for(version: str) -> str:
"""Return the changelog body (markdown) for ``version``, suitable as release notes."""
validate_version(version)
release = release_for(version)
return release.body if release else ""
def _cli(argv: list[str]) -> int:
command = argv[0] if argv else "version"
if command == "version":
print(read_version())
return 0
if command == "tag":
version = argv[1] if len(argv) > 1 else read_version()
print(tag_for(version))
return 0
if command == "notes":
version = argv[1] if len(argv) > 1 else read_version()
notes = notes_for(version)
if not notes:
print(f"No changelog entry found for version {version!r}.", file=sys.stderr)
return 1
print(notes)
return 0
print(f"Unknown command: {command!r}. Use one of: version, tag, notes.", file=sys.stderr)
return 2
if __name__ == "__main__":
try:
raise SystemExit(_cli(sys.argv[1:]))
except (OSError, ValueError) as exc:
print(f"ERROR: {exc}", file=sys.stderr)
raise SystemExit(1) from exc