publish.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #!/usr/bin/env python3
  2. """
  3. Python SDK publishing helper.
  4. - Builds sdist and wheel using `python -m build` into dist/
  5. - Uploads using twine. Configure either TestPyPI or PyPI via environment:
  6. Environment variables:
  7. REPOSITORY : "pypi" (default) or "testpypi"
  8. PYPI_TOKEN : API token (e.g., pypi-XXXX). For TestPyPI, use the TestPyPI token.
  9. Examples:
  10. REPOSITORY=testpypi PYPI_TOKEN=${{TEST_PYPI_API_TOKEN}} uv run --project packages/sdk/python python packages/sdk/python/scripts/publish.py
  11. """
  12. from __future__ import annotations
  13. import os
  14. import subprocess
  15. from pathlib import Path
  16. def run(cmd: list[str], cwd: Path | None = None) -> None:
  17. print("$", " ".join(cmd))
  18. subprocess.run(cmd, cwd=str(cwd) if cwd else None, check=True)
  19. def main() -> int:
  20. sdk_dir = Path(__file__).resolve().parent.parent
  21. repo = os.environ.get("REPOSITORY", "pypi").strip()
  22. token = os.environ.get("PYPI_TOKEN")
  23. if not token:
  24. print("ERROR: PYPI_TOKEN not set", flush=True)
  25. return 1
  26. dist = sdk_dir / "dist"
  27. if dist.exists():
  28. for f in dist.iterdir():
  29. f.unlink()
  30. # Build
  31. run(["python", "-m", "build"], cwd=sdk_dir)
  32. # Upload
  33. repo_url = {
  34. "pypi": "https://upload.pypi.org/legacy/",
  35. "testpypi": "https://test.pypi.org/legacy/",
  36. }.get(repo, repo)
  37. env = os.environ.copy()
  38. env["TWINE_USERNAME"] = "__token__"
  39. env["TWINE_PASSWORD"] = token
  40. print(f"Uploading to {repo_url}")
  41. subprocess.run(
  42. ["python", "-m", "twine", "check", "dist/*"], cwd=sdk_dir, check=True
  43. )
  44. subprocess.run(
  45. ["python", "-m", "twine", "upload", "--repository-url", repo_url, "dist/*"],
  46. cwd=sdk_dir,
  47. check=True,
  48. env=env,
  49. )
  50. print("Publish complete")
  51. return 0
  52. if __name__ == "__main__":
  53. raise SystemExit(main())