generate.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. #!/usr/bin/env python3
  2. """
  3. Generate the Opencode Python SDK using openapi-python-client and place it under src/opencode_ai.
  4. Steps:
  5. - Generate OpenAPI JSON from the local CLI (bun dev generate)
  6. - Run openapi-python-client (via `uvx` if available, else fallback to PATH)
  7. - Copy the generated module into src/opencode_ai
  8. Requires:
  9. - Bun installed (for `bun dev generate`)
  10. - uv installed (recommended) to run `uvx openapi-python-client`
  11. """
  12. from __future__ import annotations
  13. import argparse
  14. import json
  15. import shutil
  16. import subprocess
  17. import sys
  18. from pathlib import Path
  19. from urllib.request import urlopen
  20. def run(cmd: list[str], cwd: Path | None = None) -> subprocess.CompletedProcess:
  21. print("$", " ".join(cmd))
  22. return subprocess.run(cmd, cwd=str(cwd) if cwd else None, check=True, capture_output=True, text=True)
  23. def find_repo_root(start: Path) -> Path:
  24. p = start
  25. for _ in range(10):
  26. if (p / ".git").exists() or (p / "sst.config.ts").exists():
  27. return p
  28. if p.parent == p:
  29. break
  30. p = p.parent
  31. # Fallback: assume 4 levels up from scripts/
  32. return start.parents[4]
  33. def write_json(path: Path, content: str) -> None:
  34. # Validate JSON before writing
  35. json.loads(content)
  36. path.write_text(content)
  37. def main() -> int:
  38. parser = argparse.ArgumentParser(description="Generate the Opencode Python SDK from OpenAPI spec.")
  39. parser.add_argument(
  40. "--source", choices=["cli", "server"], default="cli", help="Where to fetch the OpenAPI spec from"
  41. )
  42. parser.add_argument(
  43. "--server-url",
  44. default="http://localhost:4096/doc",
  45. help="OpenAPI document URL when --source=server",
  46. )
  47. parser.add_argument(
  48. "--out-spec",
  49. default=None,
  50. help="Output path for the OpenAPI spec (defaults to packages/sdk/python/openapi.json)",
  51. )
  52. parser.add_argument(
  53. "--only-spec",
  54. action="store_true",
  55. help="Only fetch and write the OpenAPI spec without generating the client",
  56. )
  57. args = parser.parse_args()
  58. script_dir = Path(__file__).resolve().parent
  59. sdk_dir = script_dir.parent
  60. repo_root = find_repo_root(script_dir)
  61. opencode_dir = repo_root / "packages" / "opencode"
  62. openapi_json = Path(args.out_spec) if args.out_spec else (sdk_dir / "openapi.json")
  63. build_dir = sdk_dir / ".build"
  64. out_pkg_dir = sdk_dir / "src" / "opencode_ai"
  65. build_dir.mkdir(parents=True, exist_ok=True)
  66. (sdk_dir / "src").mkdir(parents=True, exist_ok=True)
  67. # 1) Obtain OpenAPI spec
  68. if args.source == "server":
  69. print(f"Fetching OpenAPI spec from {args.server_url} ...")
  70. try:
  71. with urlopen(args.server_url) as resp:
  72. if resp.status != 200:
  73. print(f"ERROR: GET {args.server_url} -> HTTP {resp.status}", file=sys.stderr)
  74. return 1
  75. text = resp.read().decode("utf-8")
  76. except Exception as e:
  77. print(f"ERROR: Failed to fetch from server: {e}", file=sys.stderr)
  78. return 1
  79. try:
  80. write_json(openapi_json, text)
  81. except json.JSONDecodeError as je:
  82. print("ERROR: Response from server was not valid JSON:", file=sys.stderr)
  83. print(str(je), file=sys.stderr)
  84. return 1
  85. print(f"Wrote OpenAPI spec to {openapi_json}")
  86. else:
  87. print("Generating OpenAPI spec via 'bun dev generate' ...")
  88. try:
  89. proc = run(["bun", "dev", "generate"], cwd=opencode_dir)
  90. except subprocess.CalledProcessError as e:
  91. print(e.stdout)
  92. print(e.stderr, file=sys.stderr)
  93. print(
  94. "ERROR: Failed to run 'bun dev generate'. Ensure Bun is installed and available in PATH.",
  95. file=sys.stderr,
  96. )
  97. return 1
  98. try:
  99. write_json(openapi_json, proc.stdout)
  100. except json.JSONDecodeError as je:
  101. print("ERROR: Output from 'bun dev generate' was not valid JSON:", file=sys.stderr)
  102. print(str(je), file=sys.stderr)
  103. return 1
  104. print(f"Wrote OpenAPI spec to {openapi_json}")
  105. if args.only_spec:
  106. print("Spec written; skipping client generation (--only-spec).")
  107. return 0
  108. # 2) Run openapi-python-client
  109. print("Running openapi-python-client generate ...")
  110. # Prefer uvx if available
  111. use_uvx = shutil.which("uvx") is not None
  112. cmd = (["uvx", "openapi-python-client", "generate"] if use_uvx else ["openapi-python-client", "generate"]) + [
  113. "--path",
  114. str(openapi_json),
  115. "--output-path",
  116. str(build_dir),
  117. "--overwrite",
  118. "--config",
  119. str(sdk_dir / "openapi-python-client.yaml"),
  120. ]
  121. try:
  122. run(cmd, cwd=sdk_dir)
  123. except subprocess.CalledProcessError as e:
  124. print(e.stdout)
  125. print(e.stderr, file=sys.stderr)
  126. print(
  127. "ERROR: Failed to run openapi-python-client. Install uv and try again: curl -LsSf https://astral.sh/uv/install.sh | sh",
  128. file=sys.stderr,
  129. )
  130. return 1
  131. # 3) Locate generated module directory and copy to src/opencode_ai
  132. generated_module: Path | None = None
  133. for candidate in build_dir.rglob("__init__.py"):
  134. if candidate.parent.name.startswith("."):
  135. continue
  136. siblings = {p.name for p in candidate.parent.glob("*.py")}
  137. if "client.py" in siblings or "api_client.py" in siblings:
  138. generated_module = candidate.parent
  139. break
  140. if not generated_module:
  141. print("ERROR: Could not locate generated module directory in .build", file=sys.stderr)
  142. return 1
  143. print(f"Found generated module at {generated_module}")
  144. # Clean target then copy
  145. if out_pkg_dir.exists():
  146. shutil.rmtree(out_pkg_dir)
  147. shutil.copytree(generated_module, out_pkg_dir)
  148. # Inject local extras from template if present
  149. extras_template = sdk_dir / "templates" / "extras.py"
  150. if extras_template.exists():
  151. (out_pkg_dir / "extras.py").write_text(extras_template.read_text())
  152. # Patch __init__ to export OpenCodeClient if present
  153. init_path = out_pkg_dir / "__init__.py"
  154. if init_path.exists() and (out_pkg_dir / "extras.py").exists():
  155. init_text = (
  156. '"""A client library for accessing opencode\n\n'
  157. "This package is generated by openapi-python-client.\n"
  158. "A thin convenience wrapper `OpenCodeClient` is also provided.\n"
  159. '"""\n\n'
  160. "from .client import AuthenticatedClient, Client\n"
  161. "from .extras import OpenCodeClient\n\n"
  162. "__all__ = (\n"
  163. ' "AuthenticatedClient",\n'
  164. ' "Client",\n'
  165. ' "OpenCodeClient",\n'
  166. ")\n"
  167. )
  168. init_path.write_text(init_text)
  169. print(f"Copied generated client to {out_pkg_dir}")
  170. # 4) Format generated code
  171. try:
  172. run(["uv", "run", "--project", str(sdk_dir), "ruff", "check", "--select", "I", "--fix", str(out_pkg_dir)])
  173. run(["uv", "run", "--project", str(sdk_dir), "black", str(out_pkg_dir)])
  174. except subprocess.CalledProcessError as e:
  175. print("WARNING: formatting failed; continuing", file=sys.stderr)
  176. print(e.stdout)
  177. print(e.stderr, file=sys.stderr)
  178. print("Done.")
  179. return 0
  180. if __name__ == "__main__":
  181. raise SystemExit(main())