"""Build or verify the SHA-256 manifest for the Deja Cue dataset.""" from __future__ import annotations import argparse import hashlib import json from pathlib import Path from typing import Any ROOT = Path(__file__).resolve().parent DATA_ROOT = ROOT / "data" MANIFEST = ROOT / "DATA_MANIFEST.json" def sha256_file(path: Path) -> str: """Return a streaming SHA-256 digest for one file.""" digest = hashlib.sha256() with path.open("rb") as handle: for block in iter(lambda: handle.read(1024 * 1024), b""): digest.update(block) return digest.hexdigest() def build_manifest() -> dict[str, Any]: """Describe every regular file below data/ in stable path order.""" files = sorted( (path for path in DATA_ROOT.rglob("*") if path.is_file()), key=lambda path: path.relative_to(ROOT).as_posix(), ) entries = [ { "path": path.relative_to(ROOT).as_posix(), "bytes": path.stat().st_size, "sha256": sha256_file(path), } for path in files ] return { "schema_version": 1, "kind": "deja_cue_data_manifest", "algorithm": "sha256", "file_count": len(entries), "total_bytes": sum(entry["bytes"] for entry in entries), "files": entries, } def validate_manifest(observed: dict[str, Any], expected: dict[str, Any]) -> None: """Raise when schema, paths, sizes, or hashes differ.""" for key in ("schema_version", "kind", "algorithm", "file_count", "total_bytes"): if expected.get(key) != observed.get(key): raise ValueError(f"Manifest field differs: {key}") expected_files = expected.get("files") observed_files = observed.get("files") if not isinstance(expected_files, list) or expected_files != observed_files: raise ValueError("Manifest file list differs") def main() -> None: """Write a new manifest or validate the committed one.""" parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "--write", action="store_true", help="replace DATA_MANIFEST.json with the current data file list", ) args = parser.parse_args() observed = build_manifest() if args.write: MANIFEST.write_text( json.dumps(observed, indent=2, ensure_ascii=True) + "\n", encoding="ascii", newline="\n", ) else: expected = json.loads(MANIFEST.read_text(encoding="ascii")) validate_manifest(observed, expected) print( json.dumps( { "passed": True, "file_count": observed["file_count"], "total_bytes": observed["total_bytes"], }, sort_keys=True, ) ) if __name__ == "__main__": main()