forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdesktop-changelog.py
More file actions
executable file
·289 lines (226 loc) · 10.4 KB
/
Copy pathdesktop-changelog.py
File metadata and controls
executable file
·289 lines (226 loc) · 10.4 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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
#!/usr/bin/env python3
"""Manage desktop changelog fragments and legacy changelog output."""
from __future__ import annotations
import argparse
import json
import sys
from datetime import date
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
DESKTOP_DIR = ROOT / "desktop" / "macos"
CHANGELOG_DIR = DESKTOP_DIR / "changelog"
UNRELEASED_DIR = CHANGELOG_DIR / "unreleased"
RELEASES_DIR = CHANGELOG_DIR / "releases"
LEGACY_CHANGELOG_PATH = DESKTOP_DIR / "CHANGELOG.json"
NONE_KIND = "none"
class ChangelogError(Exception):
pass
def read_json(path: Path) -> object:
try:
return json.loads(path.read_text(encoding="utf-8"))
except json.JSONDecodeError as exc:
raise ChangelogError(f"{path} is not valid JSON: {exc}") from exc
def write_json(path: Path, data: object) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(data, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
def normalize_changes(raw: object, path: Path) -> list[str]:
if isinstance(raw, str):
changes = [raw]
elif isinstance(raw, list):
changes = raw
else:
raise ChangelogError(f"{path} must contain a string change or a list of changes")
normalized = []
for change in changes:
if not isinstance(change, str) or not change.strip():
raise ChangelogError(f"{path} contains an empty or non-string changelog entry")
normalized.append(change.strip())
return normalized
def is_none_kind_fragment(data: object) -> bool:
return isinstance(data, dict) and data.get("kind") == NONE_KIND
def read_unreleased_fragment(path: Path) -> list[str]:
data = read_json(path)
if is_none_kind_fragment(data):
return []
if isinstance(data, dict):
if "change" in data:
return normalize_changes(data["change"], path)
if "changes" in data:
return normalize_changes(data["changes"], path)
raise ChangelogError(f"{path} must contain a 'change' string, 'changes' list, or 'kind': '{NONE_KIND}'")
def read_release_file(path: Path) -> dict[str, object]:
data = read_json(path)
if not isinstance(data, dict):
raise ChangelogError(f"{path} must contain a JSON object")
version = data.get("version")
release_date = data.get("date")
changes = data.get("changes")
if not isinstance(version, str) or not version.strip():
raise ChangelogError(f"{path} must contain a non-empty 'version'")
if not isinstance(release_date, str) or not release_date.strip():
raise ChangelogError(f"{path} must contain a non-empty 'date'")
return {
"version": version.strip(),
"date": release_date.strip(),
"changes": normalize_changes(changes, path),
}
def version_sort_key(version: str) -> tuple[int, ...]:
version = version.removeprefix("v")
return tuple(int(part) for part in version.split("."))
def unreleased_fragment_paths() -> list[Path]:
if not UNRELEASED_DIR.exists():
return []
return sorted(path for path in UNRELEASED_DIR.glob("*.json") if path.is_file())
def release_file_paths() -> list[Path]:
if not RELEASES_DIR.exists():
return []
return sorted(path for path in RELEASES_DIR.glob("*.json") if path.is_file())
def unreleased_changes() -> list[str]:
changes: list[str] = []
for path in unreleased_fragment_paths():
changes.extend(read_unreleased_fragment(path))
return changes
def release_entries() -> list[dict[str, object]]:
releases = [read_release_file(path) for path in release_file_paths()]
seen_versions = {str(release["version"]) for release in releases}
if LEGACY_CHANGELOG_PATH.exists():
data = read_json(LEGACY_CHANGELOG_PATH)
if isinstance(data, dict):
for release in data.get("releases", []):
if not isinstance(release, dict):
raise ChangelogError(f"{LEGACY_CHANGELOG_PATH} contains a non-object release")
normalized = read_release_file_from_legacy(release)
version = str(normalized["version"])
if version not in seen_versions:
releases.append(normalized)
seen_versions.add(version)
return sorted(
releases, key=lambda release: (str(release["date"]), version_sort_key(str(release["version"]))), reverse=True
)
def legacy_changelog() -> dict[str, object]:
return {
"unreleased": unreleased_changes(),
"releases": release_entries(),
}
def validate() -> None:
seen_versions: set[str] = set()
for path in unreleased_fragment_paths():
read_unreleased_fragment(path)
for path in release_file_paths():
release = read_release_file(path)
version = str(release["version"])
if version in seen_versions:
raise ChangelogError(f"duplicate release version {version}")
seen_versions.add(version)
if path.stem != version:
raise ChangelogError(f"{path} filename must match its version field")
def format_changes(changes: list[str], output_format: str) -> str:
if output_format == "json":
return json.dumps(changes)
if output_format == "pipe":
return "|".join(changes)
return "\n".join(f"- {change}" for change in changes)
def consolidate(version: str, release_date: str, *, write: bool) -> dict[str, object]:
"""Fold unreleased fragments into releases/<version>.json.
If that version file already exists and there are no unreleased fragments,
leave it untouched. Retries after a partial tag-release must not clobber a
previously consolidated 0.12.N entry with the generic fallback string.
"""
release_path = RELEASES_DIR / f"{version}.json"
fragments = unreleased_fragment_paths()
if release_path.is_file() and not fragments:
existing = read_json(release_path)
if not isinstance(existing, dict):
raise ChangelogError(f"{release_path} must contain a JSON object")
normalized = {
"version": str(existing.get("version", version)).strip() or version,
"date": str(existing.get("date", release_date)).strip() or release_date,
"changes": normalize_changes(existing.get("changes", []), release_path),
}
if write:
# Keep legacy CHANGELOG.json aligned without rewriting the release file.
write_json(LEGACY_CHANGELOG_PATH, legacy_changelog())
return normalized
changes = unreleased_changes() or ["Bug fixes and improvements"]
release = {
"version": version,
"date": release_date,
"changes": changes,
}
if write:
write_json(release_path, release)
for path in fragments:
path.unlink()
write_json(LEGACY_CHANGELOG_PATH, legacy_changelog())
return release
def migrate_from_legacy(*, write: bool) -> None:
data = read_json(LEGACY_CHANGELOG_PATH)
if not isinstance(data, dict):
raise ChangelogError(f"{LEGACY_CHANGELOG_PATH} must contain a JSON object")
for release in data.get("releases", []):
if not isinstance(release, dict):
raise ChangelogError(f"{LEGACY_CHANGELOG_PATH} contains a non-object release")
normalized = read_release_file_from_legacy(release)
if write:
write_json(RELEASES_DIR / f"{normalized['version']}.json", normalized)
unreleased = normalize_changes(data.get("unreleased", []), LEGACY_CHANGELOG_PATH)
for index, change in enumerate(unreleased, start=1):
filename = f"{date.today().strftime('%Y%m%d')}-{index:02d}.json"
if write:
write_json(UNRELEASED_DIR / filename, {"change": change})
def read_release_file_from_legacy(data: dict[str, object]) -> dict[str, object]:
version = data.get("version")
release_date = data.get("date")
changes = data.get("changes")
if not isinstance(version, str) or not version.strip():
raise ChangelogError(f"{LEGACY_CHANGELOG_PATH} contains a release without a version")
if not isinstance(release_date, str) or not release_date.strip():
raise ChangelogError(f"{LEGACY_CHANGELOG_PATH} contains release {version} without a date")
return {
"version": version.strip(),
"date": release_date.strip(),
"changes": normalize_changes(changes, LEGACY_CHANGELOG_PATH),
}
def main() -> int:
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(dest="command", required=True)
output_parser = argparse.ArgumentParser(add_help=False)
output_parser.add_argument("--format", choices=["markdown", "json", "pipe"], default="markdown")
subparsers.add_parser("validate")
subparsers.add_parser("generate-legacy")
subparsers.add_parser("migrate-from-legacy")
subparsers.add_parser("unreleased", parents=[output_parser])
subparsers.add_parser("latest-release", parents=[output_parser])
consolidate_parser = subparsers.add_parser("consolidate")
consolidate_parser.add_argument("--version", required=True)
consolidate_parser.add_argument("--date", default=date.today().strftime("%Y-%m-%d"))
consolidate_parser.add_argument("--write", action="store_true")
for command in ("generate-legacy", "migrate-from-legacy"):
subparsers.choices[command].add_argument("--write", action="store_true")
args = parser.parse_args()
try:
if args.command == "validate":
validate()
elif args.command == "generate-legacy":
data = legacy_changelog()
if args.write:
write_json(LEGACY_CHANGELOG_PATH, data)
else:
print(json.dumps(data, indent=2, ensure_ascii=False))
elif args.command == "migrate-from-legacy":
migrate_from_legacy(write=args.write)
elif args.command == "unreleased":
print(format_changes(unreleased_changes(), args.format))
elif args.command == "latest-release":
releases = release_entries()
changes = releases[0]["changes"] if releases else ["Bug fixes and improvements"]
print(format_changes(list(changes), args.format))
elif args.command == "consolidate":
release = consolidate(args.version, args.date, write=args.write)
print(json.dumps(release, indent=2, ensure_ascii=False))
except ChangelogError as exc:
print(f"FAIL: {exc}", file=sys.stderr)
return 1
return 0
if __name__ == "__main__":
raise SystemExit(main())