# SPDX-License-Identifier: MIT """Census of the Spectrum firmware and software libraries, read in place (docs/census.md). MAME_ROMPATH=... python -I scripts/census.py firmware NO_INTRO_DIR=... python -I scripts/census.py nointro SPECTRUM_TOSEC_DIR=... python -I scripts/census.py tosec Nothing is copied: zip archives are opened read-only, their members hashed or only listed. ``firmware`` hashes every member of the five Sinclair/Amstrad romsets and compares each SHA-1 with what ``mame -listroms`` expects (MAME is used here only as a catalogue of dump hashes). ``nointro`` counts the No-Intro "Sinclair - ZX Spectrum +3" set (one zip per disc image). ``tosec`` lists the members of the TOSEC-derived archives a folder holds (the Hardware Target Game Database's "MiSTer Spectrum Add-On" bundles), by extension and by TOSEC flag, without extracting anything. """ from __future__ import annotations import argparse import collections import hashlib import os import re import subprocess import sys import zipfile from pathlib import Path DRIVERS = ("spectrum", "spec128", "specpls2", "specpl2a", "specpls3") NO_INTRO_SET = "Sinclair - ZX Spectrum +3" def need(variable: str) -> Path: value = os.environ.get(variable) if not value: sys.exit(f"set {variable}") return Path(value) def mame_listing(driver: str) -> dict[str, str]: """Member name -> SHA-1 as MAME 0.285 lists them for one driver.""" try: text = subprocess.run(["mame", "-listroms", driver], capture_output=True, text=True, check=False).stdout # fmt: skip except FileNotFoundError: return {} pattern = re.compile(r"^(\S+)\s+\d+\s+CRC\(\w+\)\s+SHA1\((\w+)\)", re.M) return {match[1]: match[2] for match in pattern.finditer(text)} def firmware() -> int: root = need("MAME_ROMPATH") for driver in DRIVERS: path = root / f"{driver}.zip" if not path.exists(): print(f"{driver}: MISSING ({driver}.zip not under MAME_ROMPATH)") continue expected = mame_listing(driver) print(f"{driver}: {path.name}") with zipfile.ZipFile(path) as archive: for info in sorted(archive.infolist(), key=lambda i: i.filename): digest = hashlib.sha1(archive.read(info)).hexdigest() verdict = ("matches MAME's listing" if expected.get(info.filename) == digest else "not in MAME's listing under this name") # fmt: skip print(f" {info.filename:28} {info.file_size:6} sha1 {digest} {verdict}") return 0 def nointro() -> int: folder = need("NO_INTRO_DIR") / NO_INTRO_SET if not folder.is_dir(): sys.exit(f"{NO_INTRO_SET!r} is not under NO_INTRO_DIR") zips = sorted(folder.glob("*.zip")) regions: collections.Counter[str] = collections.Counter() flags: collections.Counter[str] = collections.Counter() inner: collections.Counter[str] = collections.Counter() for path in zips: tags = re.findall(r"\(([^)]*)\)", path.stem) regions[tags[0] if tags else "?"] += 1 for tag in tags[1:]: flags[tag] += 1 with zipfile.ZipFile(path) as archive: for name in archive.namelist(): inner[Path(name).suffix.lower()] += 1 print(f"{NO_INTRO_SET}: {len(zips)} zips") print(" regions:", dict(regions.most_common())) print(" other tags:", dict(flags.most_common(12))) print(" member extensions:", dict(inner.most_common())) return 0 def tosec() -> int: folder = need("SPECTRUM_TOSEC_DIR") for path in sorted(folder.glob("*.zip")): extensions: collections.Counter[str] = collections.Counter() flags: collections.Counter[str] = collections.Counter() machines: collections.Counter[str] = collections.Counter() with zipfile.ZipFile(path) as archive: names = [n for n in archive.namelist() if not n.endswith("/")] for name in names: stem = Path(name).name extensions[Path(stem).suffix.lower()] += 1 for flag in re.findall(r"\[([a-z]+)\d*[^\]]*\]", stem): flags[flag] += 1 if "[!]" in stem: flags["!"] += 1 for tag in re.findall(r"\(([^)]*(?:16K|48K|128K|\+2A?|\+3|Pentagon|Scorpion)[^)]*)\)", stem): machines[tag] += 1 print(f"{path.name}: {len(names)} files") print(" extensions:", dict(extensions.most_common(8))) print(" TOSEC flags:", dict(flags.most_common(10))) print(" machine tags:", dict(machines.most_common(8))) if extensions.get(".z80"): print(" .z80 machines (header):", dict(z80_machines(path).most_common())) if extensions.get(".dsk"): print(" .dsk kinds (signature):", dict(dsk_kinds(path).most_common())) return 0 def dsk_kinds(path: Path) -> collections.Counter[str]: """Standard ("MV - CPC") against extended ("EXTENDED CPC DSK") disc images.""" counts: collections.Counter[str] = collections.Counter() with zipfile.ZipFile(path) as archive: for name in archive.namelist(): if name.lower().endswith(".dsk"): with archive.open(name) as handle: signature = handle.read(8) counts[{b"MV - CPC": "standard", b"EXTENDED": "extended"}.get(signature, "other")] += 1 return counts # Byte 34 of a version 2 or 3 .z80 header, as reference/docs/wos-faq-z80format.htm # tabulates it; bit 7 of byte 37 turns 48K into 16K, 128K into +2 and +3 into +2A. Z80_V2 = {0: "48K", 1: "48K", 2: "SamRam", 3: "128K", 4: "128K"} Z80_V3 = {0: "48K", 1: "48K", 2: "SamRam", 3: "48K", 4: "128K", 5: "128K", 6: "128K", 7: "+3", 8: "+3", 9: "Pentagon", 10: "Scorpion", 11: "Didaktik", 12: "+2", 13: "+2A", 14: "TC2048", 15: "TC2068", 128: "TS2068"} # fmt: skip MODIFIED = {"48K": "16K", "128K": "+2", "+3": "+2A"} def z80_machines(path: Path) -> collections.Counter[str]: """The machine each .z80 snapshot in an archive names in its header.""" counts: collections.Counter[str] = collections.Counter() with zipfile.ZipFile(path) as archive: for name in archive.namelist(): if not name.lower().endswith(".z80"): continue with archive.open(name) as handle: header = handle.read(38) if len(header) < 30: counts["short file"] += 1 elif header[6] | header[7]: counts["48K (v1)"] += 1 elif len(header) < 38: counts["short file"] += 1 else: length = header[30] | header[31] << 8 table = Z80_V2 if length == 23 else Z80_V3 machine = table.get(header[34], f"mode {header[34]}") if header[37] & 0x80: machine = MODIFIED.get(machine, machine) counts[f"{machine} (v{2 if length == 23 else 3})"] += 1 return counts def main() -> int: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("what", choices=("firmware", "nointro", "tosec")) return {"firmware": firmware, "nointro": nointro, "tosec": tosec}[parser.parse_args().what]() if __name__ == "__main__": sys.exit(main())