turkic-ocr-code / scripts /r5_ref /ref_code_log.py
treoa's picture
Release 1
24aaa76
Raw History Blame
1.74 kB
"""R5 REF: writes code_log.tsv (rule 0.11): one row per method-code file with its sha256, line count and how it was read.
Input: a JSON file {"groups": [{"kind", "revision", "root", "files": [relative paths] or "list_file": path of a text file with absolute paths,
"read_as_text": {"default": "...", "<relative path prefix>": "..."}, "executed": true/false, "notes": "..."}]}
Output: TSV with columns kind, repo_at_revision, path, sha256, lines, read_as_text, executed, notes.
Usage: python ref_code_log.py <groups.json> <out.tsv>
"""
import hashlib
import json
import os
import sys
spec = json.load(open(sys.argv[1], encoding="utf-8"))
rows = []
for g in spec["groups"]:
root = g["root"]
if "list_file" in g:
paths = [p.strip() for p in open(g["list_file"], encoding="utf-8") if p.strip()]
rels = [os.path.relpath(p, root) for p in paths]
else:
rels = g["files"]
for rel in rels:
p = os.path.join(root, rel)
if not os.path.exists(p):
rows.append((g["kind"], g["revision"], rel, "MISSING", "", "", str(g.get("executed")), "file not found"))
continue
data = open(p, "rb").read()
mode = g["read_as_text"].get("default", "")
for pre, m in g["read_as_text"].items():
if pre != "default" and rel.startswith(pre):
mode = m
rows.append((g["kind"], g["revision"], rel, hashlib.sha256(data).hexdigest(), str(data.count(b"\n")), mode, str(g.get("executed")), g.get("notes", "")))
with open(sys.argv[2], "w", encoding="utf-8") as f:
f.write("kind\trepo_at_revision\tpath\tsha256\tlines\tread_as_text\texecuted\tnotes\n")
for r in rows:
f.write("\t".join(r) + "\n")
print(len(rows), "rows")