示例工程 27-pyproject-dependency-management
27-pyproject-dependency-management/01-minimal-pyproject/minimal_pyproject.py
"""用 uv_build 构建最小项目并检查 wheel 内容。"""
from __future__ import annotations
import shutil
import subprocess
import tempfile
import zipfile
from pathlib import Path
PYPROJECT = """\
[build-system]
requires = ["uv_build>=0.9,<0.14"]
build-backend = "uv_build"
[project]
name = "demo-pkg"
version = "0.1.0"
requires-python = ">=3.12"
[project.scripts]
demo = "demo_pkg:main"
"""
INIT = """\
def main() -> None:
print("hello")
"""
def uv_available() -> bool:
return shutil.which("uv") is not None
def build_demo() -> dict[str, object]:
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
(root / "src" / "demo_pkg").mkdir(parents=True)
(root / "pyproject.toml").write_text(PYPROJECT, encoding="utf-8")
(root / "src" / "demo_pkg" / "__init__.py").write_text(INIT, encoding="utf-8")
result = subprocess.run(
["uv", "build", "--wheel", "--offline"],
cwd=root,
capture_output=True,
text=True,
check=False,
)
if result.returncode != 0:
raise RuntimeError(result.stderr)
wheel = next((root / "dist").glob("*.whl"))
with zipfile.ZipFile(wheel) as archive:
names = archive.namelist()
entry_name = next(name for name in names if name.endswith("entry_points.txt"))
entry_text = archive.read(entry_name).decode()
return {
"wheel": wheel.name,
"module": "demo_pkg/__init__.py" in names,
"entry": "demo = demo_pkg:main" in entry_text,
}
def main() -> None:
if not uv_available():
print("uv: missing")
return
facts = build_demo()
print(f"wheel: {facts['wheel']}")
print(f"module: {facts['module']}")
print(f"entry: {facts['entry']}")
if __name__ == "__main__":
main()