Repository navigation
Expand file tree
/
Copy pathextract_xml_inventory.py
More file actions
424 lines (375 loc) · 16.7 KB
/
Copy pathextract_xml_inventory.py
File metadata and controls
424 lines (375 loc) · 16.7 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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
#!/usr/bin/env python3
"""Generate an element/attribute inventory of the in-repo XML corpora.
Scans skins, pads, samplerbanks, and mapper XML with a tolerant tokenizer
(built-in skin XML is not strict XML: raw `&`, `&&`, and `>` appear inside
quoted attribute values), cross-checks element names against the reference
docs, and writes the data artifact `docs/skin-xml-inventory.json`.
Query it with `just get-xml-element` / `list-skin-elements` / `xml-stats`;
no Markdown view is written to disk.
Scope, and the reason `undocumented` reads 0: this measures *mentions of the
elements shipped files happen to use*, so an element no shipped file writes is
invisible here however thoroughly the reader supports it, and attributes and
behavior contracts are out of scope entirely (`clickthrough` is read by every
skin object, is in no shipped skin and no doc, and never moved this count). The
binary's own reader vocabulary is the other side of that blind spot, so
`totals.reader_vocabulary_unused` joins in the candidates from
`tools/extract_skin_readers.py` — build-anchored, and reported as stale rather
than listed when the installed build has moved past the vocabulary artifact.
Usage:
python3 tools/extract_xml_inventory.py # (re)write the report
python3 tools/extract_xml_inventory.py --check # fail on new undocumented elements
"""
from __future__ import annotations
import argparse
import plistlib
import re
import sys
from collections import Counter
import json
from dataclasses import dataclass, field
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
OUTPUT = ROOT / "docs" / "skin-xml-inventory.json"
READER_VOCABULARY = ROOT / "tests" / "skin-reader-vocabulary.json"
APP = Path("/Applications/VirtualDJ.app")
# family name -> (glob patterns, reference docs to cross-check)
# Catalog downloads are Tier 2 Published skins, but stay distinct from bundle
# copies: check_bundle_copies.py can verify the latter against the installed app.
# Preserve that distinction per element so an add-on-only name has a traceable
# file rather than inheriting an undifferentiated "shipped skin" count.
SKIN_SOURCES = (
("builtin", "examples/Skins/Built-In/**/*.xml"),
("addon", "examples/Skins/Official-Addons/**/*.xml"),
("official_example", "examples/Skins/SDK Example - Custom Browser Skin/skin.xml"),
("project", "examples/Skins/ModularSkeleton/build/*.xml"),
("project", "examples/Skins/GraveRaver/build/*.xml"),
("fixture", "tests/Skins/**/*.xml"),
)
FAMILIES: list[tuple[str, list[str], list[str]]] = [
(
"skins",
[pattern for _, pattern in SKIN_SOURCES],
["docs/Skin SDK.md", "docs/Skin Waveforms.md"],
),
(
"pads",
["examples/Pads/**/*.xml", "tests/Pads/*.xml"],
["docs/Pad Page XML.md", "docs/Example Pad XML Pages.md"],
),
(
"video_skins",
["examples/VideoSkins/**/*.xml"],
["docs/Skin SDK.md", "docs/Skin Waveforms.md"],
),
(
"samplerbanks",
["examples/Samplerbanks/**/*.xml"],
[],
),
(
"mappers",
["examples/Mappers/**/*.xml"],
["docs/Mapper XML.md"],
),
]
# Fixtures that deliberately carry names the parser is *not* expected to know —
# a candidate attribute under test, and its nonsense controls. Folding these
# into the inventory would make the corpus baseline agree with whatever is being
# probed against it, which is precisely what `extract_skin_readers.py` diffs.
# Probe fixtures are deliberately synthetic — they carry nonsense tags and
# attributes as controls — so counting them would corrupt the one thing this
# inventory measures: what the shipped corpus actually writes.
EXCLUDE = (
"tests/Skins/attribute-order-probe/",
"tests/Skins/sibling-validity-probe/",
"tests/Skins/element-validity-probe/",
"tests/Skins/attribute-validity-probe/",
"tests/Skins/script-validity-probe/",
"tests/Skins/condition-validity-probe/",
"tests/Skins/clickthrough-probe/",
"tests/Skins/reader-candidates-probe/",
# Deliberately misspelled element: parser-survival negative control.
"tests/Skins/runtime-probe/waveform-control.xml",
)
NAME_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_.:-]*")
@dataclass
class ElementStats:
uses: int = 0
files: set[str] = field(default_factory=set)
attributes: Counter = field(default_factory=Counter)
source_files: dict[str, set[str]] = field(default_factory=dict)
def scan_tags(text: str) -> list[tuple[str, list[str]]]:
"""Tolerantly tokenize open tags: returns (element, [attribute names]).
Quote-aware so `>` / `<` / raw `&` inside quoted attribute values (VDJScript
ternaries etc.) do not break tag detection. Skips comments, CDATA, prolog,
doctype, and closing tags.
"""
tags: list[tuple[str, list[str]]] = []
i = 0
n = len(text)
while True:
i = text.find("<", i)
if i == -1:
break
if text.startswith("<!--", i):
end = text.find("-->", i + 4)
i = n if end == -1 else end + 3
continue
if text.startswith("<![CDATA[", i):
end = text.find("]]>", i + 9)
i = n if end == -1 else end + 3
continue
if text.startswith("<?", i) or text.startswith("<!", i):
end = text.find(">", i)
i = n if end == -1 else end + 1
continue
if text.startswith("</", i):
end = text.find(">", i)
i = n if end == -1 else end + 1
continue
match = NAME_RE.match(text, i + 1)
if not match:
i += 1
continue
name = match.group(0).lower()
k = match.end()
attrs: list[str] = []
while k < n:
c = text[k]
if c == ">":
k += 1
break
if c in " \t\r\n/":
k += 1
continue
attr_match = NAME_RE.match(text, k)
if not attr_match:
k += 1
continue
attrs.append(attr_match.group(0).lower())
k = attr_match.end()
while k < n and text[k] in " \t\r\n":
k += 1
if k < n and text[k] == "=":
k += 1
while k < n and text[k] in " \t\r\n":
k += 1
if k < n and text[k] in "\"'":
quote = text[k]
end = text.find(quote, k + 1)
k = n if end == -1 else end + 1
else:
while k < n and text[k] not in " \t\r\n>":
k += 1
tags.append((name, attrs))
i = k
return tags
def is_device_definition(path: Path) -> bool:
tags = scan_tags(path.read_text(encoding="utf-8", errors="replace"))
return bool(tags) and tags[0][0] == "device"
def collect_family(patterns: list[str], family: str = "") -> tuple[dict[str, ElementStats], list[Path]]:
files: list[Path] = []
seen: set[Path] = set()
skin_sources = {pattern: kind for kind, pattern in SKIN_SOURCES} if family == "skins" else {}
source_by_file: dict[Path, str] = {}
for pattern in patterns:
for path in sorted(ROOT.glob(pattern)):
if any(str(path.relative_to(ROOT)).startswith(x) for x in EXCLUDE):
continue
if path.is_file() and path not in seen:
seen.add(path)
files.append(path)
if pattern in skin_sources:
source_by_file[path] = skin_sources[pattern]
# A controller add-on ships its <device> definition beside the mapper;
# definition vocabulary belongs to tests/controller-schema-inventory.json.
files = [p for p in files if not is_device_definition(p)]
stats: dict[str, ElementStats] = {}
for path in files:
text = path.read_text(encoding="utf-8", errors="replace")
rel = str(path.relative_to(ROOT))
for name, attrs in scan_tags(text):
entry = stats.setdefault(name, ElementStats())
entry.uses += 1
entry.files.add(rel)
entry.attributes.update(attrs)
if path in source_by_file:
entry.source_files.setdefault(source_by_file[path], set()).add(rel)
return stats, files
def load_doc_texts(doc_paths: list[str]) -> tuple[str, str, list[tuple[str, bool]]]:
"""Return (full doc text, fenced-code-block text, per-doc availability)."""
combined: list[str] = []
availability: list[tuple[str, bool]] = []
for rel in doc_paths:
path = ROOT / rel
exists = path.is_file()
availability.append((rel, exists))
if exists:
combined.append(path.read_text(encoding="utf-8"))
text = "\n".join(combined)
fenced = "\n".join(re.findall(r"^```[^\n]*\n(.*?)^```", text, re.MULTILINE | re.DOTALL))
return text, fenced, availability
NUMBERED_ELEMENT = re.compile(r"^(shift_pad|pad|param)([1-9]|1[0-6])$", re.IGNORECASE)
def is_documented(name: str, doc_text: str, fenced_text: str) -> bool:
"""Documented = backticked `<name>` mention (headings included) or a
`<name ...>` tag inside a fenced code block. Numbered pad-family elements
(pad2..pad16, shift_padN, paramN) count as documented when their
1-numbered representative is documented."""
if not doc_text:
return False
numbered = NUMBERED_ELEMENT.match(name)
if numbered and numbered.group(2) != "1":
return is_documented(numbered.group(1) + "1", doc_text, fenced_text)
escaped = re.escape(name)
if re.search(r"`</?" + escaped + r"[\s/>`]", doc_text, re.IGNORECASE):
return True
return bool(re.search(r"</?" + escaped + r"[\s/>]", fenced_text, re.IGNORECASE))
def format_attributes(attributes: Counter) -> str:
if not attributes:
return "—"
parts = [
f"`{attr}` ({count})"
for attr, count in sorted(attributes.items(), key=lambda kv: (-kv[1], kv[0]))
]
return ", ".join(parts)
def installed_build() -> str | None:
"""CFBundleVersion of the installed app, or None when it is not here."""
try:
with open(APP / "Contents/Info.plist", "rb") as fh:
return plistlib.load(fh).get("CFBundleVersion")
except (OSError, plistlib.InvalidFileException):
return None
def reader_vocabulary_unused() -> dict:
"""The reader-vocabulary names no shipped file writes — this inventory's
own blind spot, named beside the count that cannot see it.
Build-anchored the way `extract_skin_readers.py --check` is: the names are
only listed while the vocabulary artifact and the installed app agree on a
build, because a reader vocabulary read off one build says nothing about
another. On a mismatch the field says so instead of listing names.
"""
try:
summary = json.loads(READER_VOCABULARY.read_text(encoding="utf-8"))["summary"]
except (OSError, KeyError, json.JSONDecodeError):
return {"status": "unavailable",
"note": f"{READER_VOCABULARY.relative_to(ROOT)} not extracted; "
f"run `just skin-readers`"}
build = summary.get("build", "?")
running = installed_build()
if running is None:
return {"status": "unverified", "build": build,
"note": "VirtualDJ is not installed here, so the vocabulary's "
"build could not be confirmed against a running app",
"names": summary.get("candidates", [])}
if running != build:
return {"status": "stale", "build": build, "installed_build": running,
"note": f"vocabulary was read off build {build}, installed is "
f"{running}; re-extract with `just skin-readers` before "
f"reading these names as this build's blind spot"}
return {"status": "current", "build": build,
"names": summary.get("candidates", [])}
def build_inventory() -> dict:
families: dict[str, dict] = {}
total_elements = 0
total_undocumented = 0
for family, patterns, doc_paths in FAMILIES:
stats, files = collect_family(patterns, family)
doc_text, fenced_text, availability = load_doc_texts(doc_paths)
ordered = sorted(stats.items(), key=lambda kv: (-kv[1].uses, kv[0]))
undocumented: list[str] = []
elements: dict[str, dict] = {}
for name, entry in ordered:
documented = None
if doc_paths:
documented = is_documented(name, doc_text, fenced_text)
if not documented:
undocumented.append(name)
elements[name] = {
"uses": entry.uses,
"files": len(entry.files),
"documented": documented,
"attributes": dict(sorted(entry.attributes.items(),
key=lambda kv: (-kv[1], kv[0]))),
}
if family == "skins":
elements[name]["source_files"] = {
kind: sorted(paths) for kind, paths in sorted(entry.source_files.items())
}
families[family] = {
"files_scanned": len(files),
"docs_checked": [{"path": rel, "exists": exists}
for rel, exists in availability],
"elements": elements,
"undocumented": undocumented,
}
total_elements += len(ordered)
total_undocumented += len(undocumented)
return {
"_meta": {
"generated_by": "tools/extract_xml_inventory.py",
"note": "Element/attribute inventory of every offline XML corpus, "
"cross-checked against the reference docs. Built-in skin XML is "
"not strict XML (raw `&`, `&&`, `>` inside quoted values), so this "
"comes from a tolerant quote-aware tokenizer, not an XML parser. "
"Query via `just get-xml-element` / `list-skin-elements` / "
"`xml-stats`; do not generate a Markdown copy.",
},
"totals": {
"elements": total_elements,
# `undocumented` counts only elements a shipped file writes; the
# reader accepts names no shipped file uses, and those are here.
"undocumented": total_undocumented,
"reader_vocabulary_unused": reader_vocabulary_unused(),
},
"families": families,
}
def serialize(inventory: dict) -> str:
return json.dumps(inventory, indent=1, ensure_ascii=False) + "\n"
def run_check(inventory: dict) -> int:
"""Fail when an element becomes undocumented that was not already."""
if not OUTPUT.is_file():
OUTPUT.write_text(serialize(inventory), encoding="utf-8")
print(f"{OUTPUT.relative_to(ROOT)}: did not exist, wrote initial inventory")
return 0
report = json.loads(OUTPUT.read_text(encoding="utf-8"))
committed = report.get("families", {})
failures: list[str] = []
# Not a failure — a build bump is not a broken inventory — but the blind
# spot must never read as current when it is not. Same shape as
# `extract_skin_readers.py --check`, which skips rather than fails.
was = report.get("totals", {}).get("reader_vocabulary_unused", {})
now = inventory["totals"]["reader_vocabulary_unused"]
if was.get("status") != now.get("status") or was.get("names") != now.get("names"):
print(f"XML inventory notice: reader_vocabulary_unused is {was.get('status')} "
f"in the committed report, {now.get('status')} on a re-join — "
f"refresh with `python3 tools/extract_xml_inventory.py`")
for family, data in inventory["families"].items():
was = set(committed.get(family, {}).get("undocumented", []))
new = sorted(set(data["undocumented"]) - was)
if new:
failures.append(f"{family}: new undocumented elements: {', '.join(new)}")
if failures:
for failure in failures:
print(failure, file=sys.stderr)
print("Document the elements or regenerate with "
"`python3 tools/extract_xml_inventory.py`.", file=sys.stderr)
return 1
print("XML inventory check passed")
return 0
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument(
"--check",
action="store_true",
help="exit nonzero if a new undocumented element appears vs the committed report",
)
args = parser.parse_args()
inventory = build_inventory()
if args.check:
return run_check(inventory)
OUTPUT.write_text(serialize(inventory), encoding="utf-8")
print(f"Wrote {OUTPUT.relative_to(ROOT)} "
f"({inventory['totals']['elements']} elements, "
f"{inventory['totals']['undocumented']} undocumented)")
return 0
if __name__ == "__main__":
raise SystemExit(main())