Files
troupe-standup/wizard-work/ledger/extract_git_tree_manifest.py

112 lines
3.7 KiB
Python

#!/usr/bin/env python3
"""Extract the committed file tree of the troupe repo into a verified manifest.
Source of truth: `git ls-files` (tracked files) in the repo root.
Outputs (in the same directory as this script, wizard-work/ledger/):
- 2026-10-29-git-tree-manifest.csv : relpath, ext, size_bytes, sha256
- 2026-10-29-git-tree-manifest.json : structured manifest
- 2026-10-29-git-tree-manifest.md : human-readable table
The independent re-derivation lives in verify_git_tree_manifest.py;
the committed CHECK runs that verifier and exits 0 iff it matches.
"""
import hashlib
import json
import os
import pathlib
REPO_ROOT = pathlib.Path(__file__).resolve().parent.parent.parent # troupe-standup
HERE = pathlib.Path(__file__).resolve().parent
OUT_DIR = HERE
def find_repo_root(start: pathlib.Path) -> pathlib.Path:
"""Walk up from `start` until a directory containing `.git` is found."""
current = start.resolve()
for _ in range(12):
if (current / ".git").exists():
return current
if current.parent == current:
break
current = current.parent
raise SystemExit(f"no .git found above {start}")
def sha256_of(path: pathlib.Path) -> str:
h = hashlib.sha256()
with path.open("rb") as fh:
for chunk in iter(lambda: fh.read(1024 * 1024), b""):
h.update(chunk)
return h.hexdigest()
def main() -> None:
REPO_ROOT = find_repo_root(HERE)
import subprocess
out = subprocess.run(
["git", "ls-files"], cwd=REPO_ROOT, check=True,
capture_output=True, text=True, env=os.environ,
).stdout.splitlines()
rows = []
for rel in sorted(out):
p = (REPO_ROOT / rel).resolve()
ext = p.suffix.lower() if p.suffix else "-"
rows.append({
"relpath": rel,
"ext": ext,
"size_bytes": p.stat().st_size,
"sha256": sha256_of(p),
})
ext_counts = {}
total_bytes = 0
for r in rows:
ext_counts[r["ext"]] = ext_counts.get(r["ext"], 0) + 1
total_bytes += r["size_bytes"]
manifest = {
"repo": str(REPO_ROOT),
"generated_at": __import__("datetime").datetime.now(__import__("datetime").UTC).isoformat(),
"tracked_file_count": len(rows),
"total_bytes": total_bytes,
"extension_counts": ext_counts,
"top_extensions": sorted(ext_counts.items(), key=lambda kv: (-kv[1], kv[0]))[:15],
"files": rows,
}
(OUT_DIR / "2026-10-29-git-tree-manifest.json").write_text(
json.dumps(manifest, indent=2) + "\n", encoding="utf-8"
)
with (OUT_DIR / "2026-10-29-git-tree-manifest.csv").open("w", encoding="utf-8",
newline="") as fh:
fh.write("relpath\text\tytes_sha256\n")
for r in rows:
fh.write(f'{r["relpath"]}\t{r["ext"]}\t{r["size_bytes"]}\t{r["sha256"]}\n')
lines = [
"# Git tree manifest — 2026-10-29",
"",
f"- repo: `{REPO_ROOT}`",
f"- tracked files: {manifest['tracked_file_count']}",
f"- total bytes: {manifest['total_bytes']:,}",
"",
"## Top extensions",
"",
"| extension | files |",
"|---|---|",
]
for ext, cnt in manifest["top_extensions"]:
lines.append(f"| {ext or '(no extension)'} | {cnt} |")
lines += ["", "## Full file list", "", "| # | relpath | ext | bytes |", "|---|---|---|---|"]
for i, r in enumerate(manifest["files"], 1):
lines.append(f"| {i} | {r['relpath']} | {r['ext']} | {r['size_bytes']} |")
(OUT_DIR / "2026-10-29-git-tree-manifest.md").write_text("\n".join(lines) + "\n", encoding="utf-8")
print(f"wrote {len(rows)} files -> {OUT_DIR}")
if __name__ == "__main__":
main()