#!/usr/bin/env python3 """Check or regenerate the repository SHA-256 manifest using only the standard library.""" from __future__ import annotations import argparse,hashlib,json from pathlib import Path,PurePosixPath ROOT=Path(__file__).resolve().parents[1] SKIP_PARTS={"__pycache__",".pytest_cache",".git",".venv",".hf-uploader-venv","node_modules","htmlcov",".cache","build","dist"} SKIP_NAMES={"SHA256SUMS",".coverage",".DS_Store"} def inventory(root): for p in sorted(root.rglob("*")): rel=p.relative_to(root) if any(part in SKIP_PARTS or part.endswith((".egg-info",".dist-info")) for part in rel.parts):continue if p.name in SKIP_NAMES or p.suffix in {".pyc",".pyo"}:continue if p.is_symlink():raise ValueError("Symlinks are not accepted: "+rel.as_posix()) if p.is_file():yield p def write_manifest(root=ROOT): root=Path(root).resolve() lines=[hashlib.sha256(p.read_bytes()).hexdigest()+" "+p.relative_to(root).as_posix() for p in inventory(root)] (root/"SHA256SUMS").write_text("\n".join(lines)+"\n",encoding="utf-8") return len(lines) def verify_release(root=ROOT): root=Path(root).resolve();manifest=root/"SHA256SUMS" if not manifest.is_file():raise ValueError("SHA256SUMS is missing") expected={};errors=[] for line in manifest.read_text(encoding="utf-8").splitlines(): if not line.strip():continue digest,sep,name=line.partition(" ") if not sep or len(digest)!=64 or any(c not in "0123456789abcdef" for c in digest): raise ValueError("Malformed checksum entry") posix=PurePosixPath(name) if posix.is_absolute() or ".." in posix.parts or "\\" in name: raise ValueError("Unsafe checksum path") if name in expected:raise ValueError("Duplicate checksum entry") expected[name]=digest for name,digest in expected.items(): p=root/name if not p.resolve().is_relative_to(root): errors.append({"path":name,"reason":"outside repository"});continue if p.is_symlink() or not p.is_file(): errors.append({"path":name,"reason":"missing or non-regular file"});continue if hashlib.sha256(p.read_bytes()).hexdigest()!=digest: errors.append({"path":name,"reason":"hash mismatch"}) actual={p.relative_to(root).as_posix() for p in inventory(root)} errors.extend({"path":name,"reason":"unlisted extra file"} for name in sorted(actual-set(expected))) return {"ok":not errors,"manifest_entries":len(expected),"errors":errors, "paths":sorted(expected)+["SHA256SUMS"], "total_bytes":sum((root/name).stat().st_size for name in expected if (root/name).is_file())+manifest.stat().st_size} def main(): parser=argparse.ArgumentParser(description=__doc__) parser.add_argument("--write",action="store_true",help="regenerate after intentional edits") args=parser.parse_args() if args.write:print(json.dumps({"manifest_written":write_manifest()})) result=verify_release() print(json.dumps({k:v for k,v in result.items() if k!="paths"},indent=2)) return 0 if result["ok"] else 1 if __name__=="__main__":raise SystemExit(main())