gen_python_stubs.py 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. #!/usr/bin/env python3
  2. """Generate Python gRPC stubs for hth.api.v1 into the SDK package.
  3. Best-effort helper used by `make proto`. Requires grpcio-tools.
  4. Generated modules live under:
  5. host/sdk/python/hth_sdk/generated/hth/api/v1/
  6. Imports are rewritten from `hth.api.v1` to `hth_sdk.generated.hth.api.v1`
  7. so the SDK can be installed without putting a top-level `hth` package on
  8. sys.path.
  9. """
  10. from __future__ import annotations
  11. import re
  12. import sys
  13. from pathlib import Path
  14. HOST_ROOT = Path(__file__).resolve().parents[1]
  15. PROTO = HOST_ROOT / "api" / "proto" / "hth" / "api" / "v1" / "hth.proto"
  16. OUT = HOST_ROOT / "sdk" / "python" / "hth_sdk" / "generated"
  17. PACKAGE_PREFIX = "hth_sdk.generated"
  18. def _rewrite_imports(text: str) -> str:
  19. # grpc_tools typically emits: from hth.api.v1 import hth_pb2 as ...
  20. text = re.sub(
  21. r"^from hth\.api\.v1 import (\w+)",
  22. rf"from {PACKAGE_PREFIX}.hth.api.v1 import \1",
  23. text,
  24. flags=re.M,
  25. )
  26. text = re.sub(
  27. r"^import hth\.api\.v1\.(\w+) as (\w+)",
  28. rf"from {PACKAGE_PREFIX}.hth.api.v1 import \1 as \2",
  29. text,
  30. flags=re.M,
  31. )
  32. return text
  33. def _touch_packages(root: Path) -> None:
  34. current = root
  35. current.mkdir(parents=True, exist_ok=True)
  36. (current / "__init__.py").touch()
  37. for part in ("hth", "api", "v1"):
  38. current = current / part
  39. current.mkdir(parents=True, exist_ok=True)
  40. init = current / "__init__.py"
  41. if not init.exists():
  42. init.write_text("# generated package\n", encoding="utf-8")
  43. def main() -> int:
  44. if not PROTO.is_file():
  45. print(f"missing proto: {PROTO}", file=sys.stderr)
  46. return 2
  47. try:
  48. import grpc_tools
  49. from grpc_tools import protoc
  50. except ImportError:
  51. print(
  52. "grpcio-tools is not installed. Install it and re-run:\n"
  53. " python3 -m pip install grpcio grpcio-tools protobuf\n"
  54. " python3 host/tools/gen_python_stubs.py",
  55. file=sys.stderr,
  56. )
  57. return 3
  58. _touch_packages(OUT)
  59. well_known = Path(grpc_tools.__file__).resolve().parent / "_proto"
  60. proto_include = str(HOST_ROOT / "api" / "proto")
  61. argv = [
  62. "grpc_tools.protoc",
  63. f"-I{proto_include}",
  64. f"-I{well_known}",
  65. f"--python_out={OUT}",
  66. f"--grpc_python_out={OUT}",
  67. str(PROTO),
  68. ]
  69. rc = protoc.main(argv)
  70. if rc != 0:
  71. print(f"protoc failed with {rc}", file=sys.stderr)
  72. return rc
  73. v1 = OUT / "hth" / "api" / "v1"
  74. if not v1.is_dir():
  75. print(f"expected generated dir missing: {v1}", file=sys.stderr)
  76. return 4
  77. for path in sorted(v1.glob("*.py")):
  78. original = path.read_text(encoding="utf-8")
  79. rewritten = _rewrite_imports(original)
  80. if rewritten != original:
  81. path.write_text(rewritten, encoding="utf-8")
  82. print(f"rewrote imports: {path.relative_to(HOST_ROOT)}")
  83. else:
  84. print(f"generated: {path.relative_to(HOST_ROOT)}")
  85. print("python stubs ok")
  86. return 0
  87. if __name__ == "__main__":
  88. raise SystemExit(main())