# SPDX-License-Identifier: MIT """Census of the Apple II disk library and firmware, read in place. APPLE2_DISK_DIRS=dir1:dir2 python -I scripts/census.py disks MAME_ROMPATH=... python -I scripts/census.py firmware disks: walks every folder named in APPLE2_DISK_DIRS (os.pathsep-separated), opens each zip (and zips inside zips, in memory), classifies every image by extension and size, and reads each WOZ file's header and INFO chunk (WOZ reference 2.1) plus the names in its META chunk. Nothing is extracted to disk or copied. Writes per-image rows to reference/census/disks.tsv (git-ignored) and prints the totals. firmware: hashes, by SHA-1, every file inside the MAME sets of the Apple II family (machines and the slot-card devices) found under MAME_ROMPATH, and inside any extra folders named in APPLE2_FIRMWARE_DIRS. Prints one row per file; nothing is copied. """ from __future__ import annotations import collections import csv import hashlib import io import os import struct import sys import zipfile from pathlib import Path ROOT = Path(__file__).resolve().parents[1] OUT = ROOT / "reference" / "census" IMAGE_EXT = {".woz", ".dsk", ".do", ".po", ".nib", ".2mg", ".2img", ".d13", ".hdv", ".a2r", ".moof", ".wav", ".dc42", ".dc", ".image", ".img", ".shk", ".sdk", ".bxy", ".bny"} # fmt: skip HARDWARE = ["II", "II+", "IIe", "IIc", "IIe enh", "IIgs", "IIc+", "III", "III+"] BOOT = {0: "unknown", 1: "16-sector", 2: "13-sector", 3: "both"} NESTED_LIMIT = 400 << 20 MACHINES = ["apple2", "apple2p", "apple2jp", "apple2e", "apple2ee", "apple2ep", "apple2c", "apple2c0", "apple2c3", "apple2c4", "apple2cp", "apple2gs", "apple2gsr0", "apple2gsr1", "apple2gsr3p"] # fmt: skip DEVICES = ["a2diskiing", "diskii13", "a2mockbd", "mockingboardd", "a2thunpl", "a2ssc", "a2mouse", "a2iwm", "a2superdrive", "a2ramfac", "a2aplcrd"] # fmt: skip def woz_info(data: bytes) -> dict: """The WOZ header and INFO chunk (WOZ reference 2.1, 'INFO Chunk').""" row: dict = {"woz": "bad header"} if len(data) < 12 or data[:3] != b"WOZ" or data[4:8] != b"\xff\x0a\x0d\x0a": return row row["woz"] = data[:4].decode("ascii", "replace") offset, chunks, meta = 12, [], "" while offset + 8 <= len(data): name, size = data[offset:offset + 4], struct.unpack_from("= 37: row["info_version"] = body[0] row["disk_type"] = {1: '5.25"', 2: '3.5"'}.get(body[1], body[1]) row["write_protected"] = body[2] row["synchronized"] = body[3] row["cleaned"] = body[4] row["creator"] = body[5:37].decode("utf-8", "replace").strip() if body[0] >= 2 and len(body) >= 46: row["sides"] = body[37] row["boot"] = BOOT.get(body[38], body[38]) row["bit_timing"] = body[39] hw = struct.unpack_from("> i & 1) row["ram_k"] = struct.unpack_from(" dict: ext = os.path.splitext(name)[1].lower() row = {"ext": ext, "size": len(data)} if data[:3] == b"WOZ": row.update(woz_info(data)) elif data[:4] == b"2IMG": fmt = struct.unpack_from("= 16 else -1 row["kind"] = {0: "2mg DOS order", 1: "2mg ProDOS order", 2: "2mg nibbles"}.get(fmt, "2mg ?") elif ext in (".dsk", ".do", ".po") and len(data) == 143360: row["kind"] = "5.25 16-sector sectors" elif ext == ".d13" or len(data) == 116480: row["kind"] = "5.25 13-sector sectors" elif ext == ".nib" and len(data) == 232960: row["kind"] = "5.25 nibbles (6656 per track)" elif ext == ".po" and len(data) == 819200: row["kind"] = "3.5 800K ProDOS order" return row def walk_zip(label: str, archive: zipfile.ZipFile, rows: list, depth: int = 0) -> None: for info in archive.infolist(): if info.is_dir(): continue name = info.filename ext = os.path.splitext(name)[1].lower() if ext == ".zip" and depth < 3 and info.file_size <= NESTED_LIMIT: try: inner = zipfile.ZipFile(io.BytesIO(archive.read(info))) except (zipfile.BadZipFile, OSError, NotImplementedError) as error: rows.append({"zip": label, "member": name, "error": str(error)}) continue walk_zip(f"{label}/{name}", inner, rows, depth + 1) elif ext in IMAGE_EXT: try: data = archive.read(info) except (zipfile.BadZipFile, OSError, NotImplementedError) as error: rows.append({"zip": label, "member": name, "error": str(error)}) continue rows.append({"zip": label, "member": name, **classify(name, data)}) else: rows.append({"zip": label, "member": name, "ext": ext, "size": info.file_size, "kind": "other"}) # fmt: skip def disks() -> int: dirs = [d for d in os.environ.get("APPLE2_DISK_DIRS", "").split(os.pathsep) if d] if not dirs: sys.exit("set APPLE2_DISK_DIRS to the disk-image folders (os.pathsep-separated)") OUT.mkdir(parents=True, exist_ok=True) rows: list[dict] = [] for top in dirs: top_path = Path(top) collection = top_path.name for path in sorted(top_path.rglob("*")): if not path.is_file(): continue label = f"{collection}/{path.relative_to(top_path)}" if path.suffix.lower() == ".zip": try: walk_zip(label, zipfile.ZipFile(path), rows) except (zipfile.BadZipFile, OSError) as error: rows.append({"zip": label, "error": str(error)}) elif path.suffix.lower() in IMAGE_EXT: rows.append({"zip": label, "member": path.name, **classify(path.name, path.read_bytes())}) # fmt: skip print(f"scanned {collection}: {len(rows)} rows so far", flush=True) fields = sorted({key for row in rows for key in row}) with (OUT / "disks.tsv").open("w", newline="", encoding="utf-8") as handle: writer = csv.DictWriter(handle, fields, delimiter="\t") writer.writeheader() writer.writerows(rows) by_collection = collections.defaultdict(collections.Counter) for row in rows: by_collection[row["zip"].split("/")[0]][row.get("ext", "?")] += 1 for name, counter in by_collection.items(): print(name, sum(counter.values()), dict(counter.most_common(12))) wozzes = [row for row in rows if "woz" in row] print("WOZ files:", len(wozzes)) for key in ("woz", "disk_type", "boot", "bit_timing", "hardware", "ram_k", "synchronized", "cleaned", "write_protected", "info_version"): # fmt: skip print(f" {key}:", dict(collections.Counter(str(r.get(key, "-")) for r in wozzes).most_common(14))) creators = collections.Counter(str(r.get("creator", "-")).split(" v")[0] for r in wozzes) print(" creator:", dict(creators.most_common(8))) chunks = collections.Counter(c for r in wozzes for c in str(r.get("chunks", "")).split(",")) print(" chunks:", dict(chunks)) kinds = collections.Counter(str(r.get("kind", "-")) for r in rows if "woz" not in r) print("other kinds:", dict(kinds.most_common(12))) errors = [row for row in rows if "error" in row] print("errors:", len(errors)) return 0 def firmware() -> int: rompath = os.environ.get("MAME_ROMPATH") if not rompath: sys.exit("set MAME_ROMPATH to the MAME ROM folder") places = [Path(rompath) / f"{name}.zip" for name in MACHINES + DEVICES] for extra in os.environ.get("APPLE2_FIRMWARE_DIRS", "").split(os.pathsep): if extra: places += sorted(Path(extra).glob("apple2*.zip")) for place in places: if not place.exists(): print(f"MISSING\t{place.name}") continue with zipfile.ZipFile(place) as archive: for info in archive.infolist(): digest = hashlib.sha1(archive.read(info)).hexdigest() print(f"{digest}\t{info.file_size}\t{place.name}\t{info.filename}") return 0 if __name__ == "__main__": if len(sys.argv) != 2 or sys.argv[1] not in ("disks", "firmware"): sys.exit(__doc__) sys.exit(disks() if sys.argv[1] == "disks" else firmware())