"""Read a Factorio save's game version and mod list without running the game. The header of `/level-init.dat` (or `level.dat0`, zlib-deflated in >= 0.17; plain `level.dat` before) starts with the version as 4 x u16 LE (major, minor, patch, build). Further in comes the mod list: count (space-optimised uint: u8, or 0xFF + u32), then per mod a string (len u8|0xFF+u32, bytes), version as 3 space-optimised u16 (u8, or 0xFF + u16), and a u32 CRC. The list always contains `base`, and `base` also appears once earlier as the scenario's base mod, so the list is located as the `\\x04base` occurrence that parses as a complete, plausible mod list. Usage: python3 -I save_meta.py SAVE.zip [...] -> one JSON line per save """ import json import struct import sys import zipfile import zlib DLC = {"base", "elevated-rails", "quality", "recycler", "space-age"} def header_bytes(z: zipfile.ZipFile) -> bytes: names = z.namelist() for want in ("level-init.dat", "level.dat0", "level.dat"): hit = [n for n in names if n.split("/")[-1] == want] if hit: with z.open(hit[0]) as f: raw = f.read(4 << 20) try: return zlib.decompressobj().decompress(raw, 4 << 20) except zlib.error: return raw raise ValueError("no level data in zip") def _uint(b, i, wide): if b[i] != 0xFF: return b[i], i + 1 return (struct.unpack_from(" dict: with zipfile.ZipFile(path) as z: b = header_bytes(z) has_replay = any(n.endswith("replay.dat") for n in z.namelist()) level_bytes = sum(i.file_size for i in z.infolist() if "/level.dat" in i.filename) version = ".".join(map(str, struct.unpack_from("<4H", b, 0)[:3])) mods = None pos = b.find(b"\x04base") while pos != -1 and mods is None: # The count sits right before the first mod name; `base` is normally first, but scan back a little # in case other mods precede it. for back in range(1, 400): if pos - back < 8: break mods = parse_mods(b, pos - back) if mods: break pos = b.find(b"\x04base", pos + 1) names = [n for n, _ in mods] if mods else None return { "factorio_version": version, "mods": dict(mods) if mods else None, "vanilla": names is not None and set(names) <= DLC, "space_age": names is not None and "space-age" in names, "has_replay": has_replay, "level_dat_bytes": level_bytes, } if __name__ == "__main__": for p in sys.argv[1:]: try: print(json.dumps({"file": p, **meta(p)})) except Exception as e: # noqa: BLE001 print(json.dumps({"file": p, "error": repr(e)}))