File size: 2,839 Bytes
24eaa43
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
"""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()