|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +One-off: prune unused categories from already-built version manifests. |
| 4 | +
|
| 5 | +The build now emits only the categories actually referenced by at least one |
| 6 | +notebook (see lib/notebooks.py:generate_version_manifest), but versions that |
| 7 | +were built before that change still carry the full 9-category list in their |
| 8 | +manifest. Running this script rewrites those manifests in place so we don't |
| 9 | +have to wait for each version's `.build-ok` to invalidate via a real change. |
| 10 | +
|
| 11 | +Notebooks, outputs, and api.json are not touched. |
| 12 | +
|
| 13 | +Usage: |
| 14 | + python scripts/prune-manifest-categories.py # apply |
| 15 | + python scripts/prune-manifest-categories.py --dry-run # preview |
| 16 | +""" |
| 17 | + |
| 18 | +from __future__ import annotations |
| 19 | + |
| 20 | +import argparse |
| 21 | +import json |
| 22 | +import sys |
| 23 | +from pathlib import Path |
| 24 | + |
| 25 | + |
| 26 | +STATIC_DIR = Path(__file__).resolve().parent.parent / "static" |
| 27 | + |
| 28 | + |
| 29 | +def prune(manifest_path: Path, dry_run: bool) -> tuple[int, int]: |
| 30 | + """Return (before, after) category count for this manifest.""" |
| 31 | + with open(manifest_path, "r", encoding="utf-8") as f: |
| 32 | + manifest = json.load(f) |
| 33 | + |
| 34 | + notebooks = manifest.get("notebooks", []) |
| 35 | + categories = manifest.get("categories", []) |
| 36 | + used_ids = {n["category"] for n in notebooks} |
| 37 | + pruned = [c for c in categories if c["id"] in used_ids] |
| 38 | + |
| 39 | + before, after = len(categories), len(pruned) |
| 40 | + if before == after: |
| 41 | + return before, after |
| 42 | + |
| 43 | + if not dry_run: |
| 44 | + manifest["categories"] = pruned |
| 45 | + with open(manifest_path, "w", encoding="utf-8") as f: |
| 46 | + json.dump(manifest, f, indent=2, ensure_ascii=False) |
| 47 | + f.write("\n") |
| 48 | + return before, after |
| 49 | + |
| 50 | + |
| 51 | +def main() -> int: |
| 52 | + parser = argparse.ArgumentParser(description=__doc__) |
| 53 | + parser.add_argument("--dry-run", action="store_true") |
| 54 | + args = parser.parse_args() |
| 55 | + |
| 56 | + total_before = total_after = touched = 0 |
| 57 | + for manifest_path in sorted(STATIC_DIR.glob("*/v*/manifest.json")): |
| 58 | + before, after = prune(manifest_path, args.dry_run) |
| 59 | + rel = manifest_path.relative_to(STATIC_DIR.parent) |
| 60 | + if before != after: |
| 61 | + touched += 1 |
| 62 | + print(f" {rel}: {before} → {after} categories") |
| 63 | + total_before += before |
| 64 | + total_after += after |
| 65 | + |
| 66 | + action = "would prune" if args.dry_run else "pruned" |
| 67 | + print(f"\n{touched} manifest(s) {action}, total categories {total_before} → {total_after}.") |
| 68 | + return 0 |
| 69 | + |
| 70 | + |
| 71 | +if __name__ == "__main__": |
| 72 | + sys.exit(main()) |
0 commit comments