Loading files
This file is pinned to the selected release. Download the original to open it in your design tool.
#!/usr/bin/env python3
"""Refresh the vendored snapshot of AMY's ``docs/*.md`` into ``refdocs/amy/``.
Why this exists: the ``amy`` submodule is **not** checked out in the Railway
deploy (``railway.json`` has no submodule init), so the AMYboard sketch
generator cannot read ``amy/docs`` directly in production. This script vendors a
committed snapshot of those Markdown docs so the generator's ``read_reference``
tool can serve them with zero network calls at request time.
The snapshot is sourced from the **pinned** amy commit (the gitlink recorded in
this repo), so it always matches the submodule pointer rather than amy's moving
``main``. Re-run this whenever you bump the amy pin (see the "AMY Submodule
Policy" in CLAUDE.md).
Source priority:
1. local submodule working tree (``amy/docs/*.md``), if checked out **at the
pinned SHA** (a submodule sitting on some other commit is ignored so the
snapshot can't silently track the wrong amy)
2. GitHub raw at the pinned amy SHA (read from ``git ls-tree HEAD amy``)
Usage:
python3 tulip/server/sync_amy_docs.py # refresh the snapshot
python3 tulip/server/sync_amy_docs.py --check # exit 1 if snapshot is stale
python3 tulip/server/sync_amy_docs.py --sha SHA # vendor from SHA, not the gitlink
"""
from __future__ import annotations
import argparse
import json
import subprocess
import sys
import urllib.request
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parents[2]
SUBMODULE_DOCS = REPO_ROOT / "amy" / "docs"
VENDOR_DIR = Path(__file__).resolve().parent / "refdocs" / "amy"
RAW_URL = "https://raw.githubusercontent.com/shorepine/amy/{sha}/docs/{name}"
TREE_API = "https://api.github.com/repos/shorepine/amy/git/trees/{sha}?recursive=1"
def pinned_sha() -> str:
"""The amy commit this repo's gitlink points at (``160000 commit <sha>\tamy``)."""
out = subprocess.check_output(
["git", "-C", str(REPO_ROOT), "ls-tree", "HEAD", "amy"], text=True
)
return out.split()[2]
def submodule_head() -> str | None:
"""The commit the amy submodule working tree is actually checked out at."""
try:
return subprocess.check_output(
["git", "-C", str(REPO_ROOT / "amy"), "rev-parse", "HEAD"],
text=True, stderr=subprocess.DEVNULL,
).strip()
except (subprocess.CalledProcessError, FileNotFoundError):
return None
def md_names_local() -> list[str]:
if not SUBMODULE_DOCS.is_dir():
return []
return sorted(p.name for p in SUBMODULE_DOCS.glob("*.md"))
def md_names_github(sha: str) -> list[str]:
with urllib.request.urlopen(TREE_API.format(sha=sha), timeout=30) as resp:
tree = json.load(resp)["tree"]
names = []
for entry in tree:
path = entry.get("path", "")
# top-level docs/*.md only
if (
entry.get("type") == "blob"
and path.startswith("docs/")
and path.endswith(".md")
and "/" not in path[len("docs/"):]
):
names.append(path[len("docs/"):])
return sorted(names)
def read_local(name: str) -> str:
return (SUBMODULE_DOCS / name).read_text(encoding="utf-8")
def read_github(sha: str, name: str) -> str:
with urllib.request.urlopen(RAW_URL.format(sha=sha, name=name), timeout=30) as resp:
return resp.read().decode("utf-8")
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--check", action="store_true",
help="verify refdocs/amy matches the pinned amy SHA; no writes")
ap.add_argument("--sha", metavar="SHA",
help="vendor from this amy commit instead of the pinned gitlink "
"(amy's tulipcc-pin workflow uses this to build the snapshot "
"for a pin bump before the gitlink moves)")
opts = ap.parse_args()
sha = opts.sha or pinned_sha()
use_local = (SUBMODULE_DOCS.is_dir() and md_names_local()
and submodule_head() == sha)
source = "local submodule" if use_local else "GitHub raw @ pinned SHA"
names = md_names_local() if use_local else md_names_github(sha)
if not names:
print("No amy/docs/*.md found from any source.", file=sys.stderr)
return 1
snapshot = {
name: (read_local(name) if use_local else read_github(sha, name))
for name in names
}
snapshot["_VENDORED_FROM.txt"] = (
"Auto-generated by tulip/server/sync_amy_docs.py — do not edit by hand.\n"
f"Source: amy@{sha}\n"
f"Files: {', '.join(names)}\n"
)
if opts.check:
on_disk = {p.name for p in VENDOR_DIR.glob("*.md")} if VENDOR_DIR.is_dir() else set()
stale = sorted(on_disk - set(names)) # removed upstream but still vendored
for name, text in snapshot.items():
path = VENDOR_DIR / name
if not path.exists() or path.read_text(encoding="utf-8") != text:
stale.append(name)
if stale:
print(f"refdocs/amy is stale vs pinned amy@{sha[:12]} "
"(run: python3 tulip/server/sync_amy_docs.py):")
for s in sorted(set(stale)):
print(f" {s}")
return 1
print(f"refdocs/amy is up to date with pinned amy@{sha[:12]}")
return 0
VENDOR_DIR.mkdir(parents=True, exist_ok=True)
# Clear stale snapshots so a removed doc doesn't linger.
for old in VENDOR_DIR.glob("*.md"):
old.unlink()
print(f"Vendoring {len(names)} amy doc(s) from {source} (amy@{sha[:12]}):")
for name in names:
text = snapshot[name]
(VENDOR_DIR / name).write_text(text, encoding="utf-8")
print(f" {name} ({len(text)} chars)")
(VENDOR_DIR / "_VENDORED_FROM.txt").write_text(
snapshot["_VENDORED_FROM.txt"], encoding="utf-8")
print(f"Wrote snapshot to {VENDOR_DIR.relative_to(REPO_ROOT)}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
a2ffd7aadThis file is pinned to the selected release. Download the original to open it in your design tool.