File size: 1,657 Bytes
c8beaf3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Copy byte-bearing rows selected by a rows-by-licence TSV from an extracted archive."""

from __future__ import annotations

import argparse
import csv
import hashlib
import shutil
from pathlib import Path


def sha256_file(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as handle:
        for chunk in iter(lambda: handle.read(8 * 1024 * 1024), b""):
            digest.update(chunk)
    return digest.hexdigest()


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("row_list", type=Path)
    parser.add_argument("extracted_archive", type=Path)
    parser.add_argument("output", type=Path)
    args = parser.parse_args()
    with args.row_list.open("r", encoding="utf-8", newline="") as handle:
        rows = list(csv.DictReader(handle, delimiter="\t"))
    copied = 0
    for row in rows:
        relative = row.get("p5_payload_rel_path", "")
        if not relative:
            continue
        source = (args.extracted_archive / relative).resolve()
        root = args.extracted_archive.resolve()
        if root not in source.parents or not source.is_file():
            raise ValueError(f"unsafe or missing source path: {relative}")
        if sha256_file(source) != row["sha256"]:
            raise ValueError(f"SHA-256 mismatch: {relative}")
        target = args.output / row["component"] / Path(relative).name
        target.parent.mkdir(parents=True, exist_ok=True)
        shutil.copy2(source, target)
        copied += 1
    print(f"PASS: copied {copied:,} verified byte-bearing rows")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())