#!/usr/bin/env python3 """Generate Python gRPC stubs for hth.api.v1 into the SDK package. Best-effort helper used by `make proto`. Requires grpcio-tools. Generated modules live under: host/sdk/python/hth_sdk/generated/hth/api/v1/ Imports are rewritten from `hth.api.v1` to `hth_sdk.generated.hth.api.v1` so the SDK can be installed without putting a top-level `hth` package on sys.path. """ from __future__ import annotations import re import sys from pathlib import Path HOST_ROOT = Path(__file__).resolve().parents[1] PROTO = HOST_ROOT / "api" / "proto" / "hth" / "api" / "v1" / "hth.proto" OUT = HOST_ROOT / "sdk" / "python" / "hth_sdk" / "generated" PACKAGE_PREFIX = "hth_sdk.generated" def _rewrite_imports(text: str) -> str: # grpc_tools typically emits: from hth.api.v1 import hth_pb2 as ... text = re.sub( r"^from hth\.api\.v1 import (\w+)", rf"from {PACKAGE_PREFIX}.hth.api.v1 import \1", text, flags=re.M, ) text = re.sub( r"^import hth\.api\.v1\.(\w+) as (\w+)", rf"from {PACKAGE_PREFIX}.hth.api.v1 import \1 as \2", text, flags=re.M, ) return text def _touch_packages(root: Path) -> None: current = root current.mkdir(parents=True, exist_ok=True) (current / "__init__.py").touch() for part in ("hth", "api", "v1"): current = current / part current.mkdir(parents=True, exist_ok=True) init = current / "__init__.py" if not init.exists(): init.write_text("# generated package\n", encoding="utf-8") def main() -> int: if not PROTO.is_file(): print(f"missing proto: {PROTO}", file=sys.stderr) return 2 try: import grpc_tools from grpc_tools import protoc except ImportError: print( "grpcio-tools is not installed. Install it and re-run:\n" " python3 -m pip install grpcio grpcio-tools protobuf\n" " python3 host/tools/gen_python_stubs.py", file=sys.stderr, ) return 3 _touch_packages(OUT) well_known = Path(grpc_tools.__file__).resolve().parent / "_proto" proto_include = str(HOST_ROOT / "api" / "proto") argv = [ "grpc_tools.protoc", f"-I{proto_include}", f"-I{well_known}", f"--python_out={OUT}", f"--grpc_python_out={OUT}", str(PROTO), ] rc = protoc.main(argv) if rc != 0: print(f"protoc failed with {rc}", file=sys.stderr) return rc v1 = OUT / "hth" / "api" / "v1" if not v1.is_dir(): print(f"expected generated dir missing: {v1}", file=sys.stderr) return 4 for path in sorted(v1.glob("*.py")): original = path.read_text(encoding="utf-8") rewritten = _rewrite_imports(original) if rewritten != original: path.write_text(rewritten, encoding="utf-8") print(f"rewrote imports: {path.relative_to(HOST_ROOT)}") else: print(f"generated: {path.relative_to(HOST_ROOT)}") print("python stubs ok") return 0 if __name__ == "__main__": raise SystemExit(main())