-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsync_readme.py
More file actions
305 lines (257 loc) · 11.6 KB
/
Copy pathsync_readme.py
File metadata and controls
305 lines (257 loc) · 11.6 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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-2.0-or-later
"""Single-source README values from the codebase.
Reads authoritative values (test count, declared package version, policy
versions, transform count, CLI-command count, dataset-registry count) from
the source tree and rewrites the regions between named markers in
``README.md`` + ``CLAUDE.md``:
<!-- apmode:AUTO:<key> -->VALUE<!-- apmode:/AUTO:<key> -->
Usage:
uv run python scripts/sync_readme.py [--check]
``--check`` exits 1 if any value is out of date — suitable for CI.
Keys emitted:
version Declared package version (from pyproject ``fallback-version``
+ the ``[project.scripts]`` version-file if present, or the
nearest annotated tag with a rc suffix). We prefer the
changelog's most recent ``## [X.Y.Z]`` header because the
vcs-generated ``_version.py`` carries dev-revision suffixes
that are noisy to show to end users.
version_tag ``vX.Y.Z`` form for the badge.
tests Output of ``pytest --collect-only -q`` tail line.
tests_nonlive Collected tests minus those marked ``live`` (best-effort via
``-m 'not live'``); falls back to the raw count when the
deselect machinery errors.
policy_gate Gate-policy schema version (from ``policies/submission.json``
— all three lanes must match or the script errors).
policy_profiler Profiler policy version (``policies/profiler.json``).
profiler_manifest Profiler manifest schema version (int).
transforms Count of ``FormularTransform`` members (``dsl/transforms.py`` +
``dsl/prior_transforms.py``).
cli_cmds Count of ``@app.command`` decorators in ``cli.py``.
datasets Count of ``DatasetInfo(...)`` entries in ``data/datasets.py``.
backends Count of non-dunder files under ``src/apmode/backends/``
(bayes/ lives outside).
Exit codes: 0 success, 1 drift (``--check``) or tool failure.
"""
from __future__ import annotations
import argparse
import json
import re
import subprocess
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
README = ROOT / "README.md"
CLAUDE_MD = ROOT / "CLAUDE.md"
CITATION_CFF = ROOT / "CITATION.cff"
POLICY_DIR = ROOT / "policies"
CLI_FILE = ROOT / "src/apmode/cli.py"
DATASETS_FILE = ROOT / "src/apmode/data/datasets.py"
TRANSFORMS_FILES = [
ROOT / "src/apmode/dsl/transforms.py",
ROOT / "src/apmode/dsl/prior_transforms.py",
]
CHANGELOG = ROOT / "CHANGELOG.md"
BACKENDS_DIR = ROOT / "src/apmode/backends"
MARKER_RE = re.compile(
r"<!--\s*apmode:AUTO:(?P<key>[a-z0-9_]+)\s*-->"
r"(?P<body>.*?)"
r"<!--\s*apmode:/AUTO:(?P<close>[a-z0-9_]+)\s*-->",
re.DOTALL,
)
# BibTeX fields cannot host HTML-comment markers (they render literally inside
# a fenced ```bibtex block), so we target the ``version`` field of the
# ``@software{apmode2026, ...}`` entry with a dedicated line-level regex. The
# CITATION.cff file uses the same machinery for its top-level ``version:`` key.
BIBTEX_VERSION_RE = re.compile(
r"(?P<prefix>version\s*=\s*\{)(?P<body>[^}]*)(?P<suffix>\})",
)
CITATION_VERSION_RE = re.compile(
r"(?m)^(?P<prefix>version:\s*)(?P<body>\S+)\s*$",
)
def _shell(cmd: list[str]) -> str:
return subprocess.check_output(cmd, cwd=ROOT, text=True, stderr=subprocess.STDOUT)
def collect_tests() -> tuple[str, str]:
"""Return (total, non_live) test counts as strings."""
try:
out = _shell(["uv", "run", "pytest", "tests/", "--collect-only", "-q"])
except subprocess.CalledProcessError as e:
print(f"pytest collect failed: {e.output[-400:]}", file=sys.stderr)
return ("?", "?")
m = re.search(r"(\d+)\s+tests? collected", out)
total = m.group(1) if m else "?"
try:
out2 = _shell(["uv", "run", "pytest", "tests/", "--collect-only", "-q", "-m", "not live"])
m2 = re.search(r"(\d+)/\d+ tests collected", out2) or re.search(
r"(\d+)\s+tests? collected", out2
)
nonlive = m2.group(1) if m2 else total
except subprocess.CalledProcessError:
nonlive = total
return (total, nonlive)
def collect_version() -> tuple[str, str]:
"""Pull the canonical release version from the most recent CHANGELOG header."""
text = CHANGELOG.read_text()
m = re.search(r"^##\s+\[(?P<v>[0-9]+\.[0-9]+\.[0-9]+(?:-[a-z0-9]+)?)\]", text, re.M)
if not m:
return ("0.0.0", "v0.0.0")
v = m.group("v")
return (v, f"v{v}")
def collect_policy_versions() -> tuple[str, str, int]:
"""Return (gate_policy_version, profiler_policy_version, manifest_schema_version)."""
gate_versions = set()
for lane in ("submission", "discovery", "optimization"):
pj = json.loads((POLICY_DIR / f"{lane}.json").read_text())
gate_versions.add(pj["policy_version"])
if len(gate_versions) != 1:
raise SystemExit(
f"Gate policy versions diverge across lanes: {sorted(gate_versions)}. "
f"Fix policies/*.json before syncing the README."
)
profiler = json.loads((POLICY_DIR / "profiler.json").read_text())
return (
gate_versions.pop(),
profiler["policy_version"],
int(profiler["manifest_schema_version"]),
)
def collect_transform_count() -> int:
count = 0
for f in TRANSFORMS_FILES:
count += len(re.findall(r"^class\s+[A-Z]\w*\(BaseModel\):", f.read_text(), re.M))
return count
def collect_cli_command_count() -> int:
"""Count user-visible commands in `apmode --help`.
Includes both ``@app.command(...)`` decorators and Typer sub-apps
registered via ``register_rocrate_commands(app)`` (which attaches the
``bundle`` group as a single top-level command). The two helpers below
resolve to exactly what ``apmode --help`` prints.
"""
text = CLI_FILE.read_text()
n_decorated = len(re.findall(r"^@app\.command\(", text, re.M))
# Sub-apps: each ``register_*_commands(app)`` call attaches one more
# top-level group. Today that's ``register_rocrate_commands`` only.
n_subapps = len(re.findall(r"^register_\w+_commands\(app\)", text, re.M))
return n_decorated + n_subapps
def collect_dataset_count() -> int:
return CLI_FILE.read_text().count("DatasetInfo(") + DATASETS_FILE.read_text().count(
"DatasetInfo("
) # DatasetInfo only appears in datasets.py but the OR preserves safety
def collect_backend_count() -> int:
return sum(
1
for p in BACKENDS_DIR.iterdir()
if p.is_file() and p.suffix == ".py" and not p.name.startswith("_")
)
def build_values() -> dict[str, str]:
tests_total, tests_nonlive = collect_tests()
version, version_tag = collect_version()
gate_ver, profiler_ver, manifest_ver = collect_policy_versions()
# Badge keys wrap the full ``[]()`` span so the
# auto-update HTML comments live *outside* the URL. GitHub's markdown
# parser chokes on HTML comments inside an image URL and renders the
# whole `` as literal text.
#
# The badge markdown must live on its OWN line — not share a line with
# the ``<!-- apmode:AUTO:... -->`` markers. CommonMark HTML block rule 2
# treats any line beginning (after up to 3 spaces) with ``<!--`` as a raw
# HTML block, so `` <!-- x -->[]()<!-- /x -->`` on one
# line renders as literal text. Splitting the marker onto its own line
# keeps the badge line starting with ``[!`` so it parses as markdown.
#
# shields.io interprets a single ``-`` as the label/message/color
# separator in ``/badge/<label>-<message>-<color>``; any literal
# dash in the value must be doubled. A prerelease like ``v0.5.0-rc2``
# needs ``v0.5.0--rc2`` to render correctly.
shields_tag = version_tag.replace("-", "--")
badge_version = (
f"\n []()\n "
)
badge_tests = (
"\n "
f"[]()"
"\n "
)
return {
"version": version,
"version_tag": version_tag,
"badge_version": badge_version,
"badge_tests": badge_tests,
"tests": tests_total,
"tests_nonlive": tests_nonlive,
"policy_gate": gate_ver,
"policy_profiler": profiler_ver,
"profiler_manifest": str(manifest_ver),
"transforms": str(collect_transform_count()),
"cli_cmds": str(collect_cli_command_count()),
"datasets": str(DATASETS_FILE.read_text().count("DatasetInfo(")),
"backends": str(collect_backend_count()),
}
def replace_markers(text: str, values: dict[str, str]) -> tuple[str, list[tuple[str, str, str]]]:
changes: list[tuple[str, str, str]] = []
def repl(m: re.Match[str]) -> str:
key, body, close = m.group("key"), m.group("body"), m.group("close")
if key != close:
raise SystemExit(f"Marker mismatch: open={key} close={close}")
new = values.get(key, f"???:{key}")
if body != new:
changes.append((key, body, new))
return f"<!-- apmode:AUTO:{key} -->{new}<!-- apmode:/AUTO:{key} -->"
return MARKER_RE.sub(repl, text), changes
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument(
"--check",
action="store_true",
help="Exit 1 if README/CLAUDE.md is out of date instead of writing.",
)
args = parser.parse_args()
values = build_values()
print("Resolved values:")
for k, v in values.items():
print(f" {k:20s} = {v}")
any_drift = False
for path in (README, CLAUDE_MD):
if not path.exists():
continue
text = path.read_text()
new, changes = replace_markers(text, values)
if changes:
any_drift = True
print(f"\n{path.name}: {len(changes)} drift(s)")
for key, old, newv in changes:
old_s = old.replace("\n", "\\n")
print(f" {key}: {old_s!r} → {newv!r}")
if not args.check:
path.write_text(new)
print(f" → wrote {path.name}")
# BibTeX version field in README (can't host HTML markers inside a fenced
# code block — they render literally). Targeted regex substitution.
if README.exists():
text = README.read_text()
def _bib_repl(m: re.Match[str]) -> str:
return f"{m.group('prefix')}{values['version']}{m.group('suffix')}"
new = BIBTEX_VERSION_RE.sub(_bib_repl, text, count=1)
if new != text:
any_drift = True
print(f"\nREADME.md: bibtex version drift → {values['version']}")
if not args.check:
README.write_text(new)
# CITATION.cff (GitHub "Cite this repository" source).
if CITATION_CFF.exists():
text = CITATION_CFF.read_text()
def _cff_repl(m: re.Match[str]) -> str:
return f"{m.group('prefix')}{values['version']}"
new = CITATION_VERSION_RE.sub(_cff_repl, text, count=1)
if new != text:
any_drift = True
print(f"\nCITATION.cff: version drift → {values['version']}")
if not args.check:
CITATION_CFF.write_text(new)
if args.check and any_drift:
print("\nDrift detected. Run without --check to update.", file=sys.stderr)
return 1
if not any_drift:
print("\nNo drift. README is in sync with source of truth.")
return 0
if __name__ == "__main__":
raise SystemExit(main())