示例工程 28-packaging-distribution

28-packaging-distribution/01-build-and-inspect/build_and_inspect.py

python · 1.9 KB

"""构建 wheel 并检查包内容与 dist-info 文件。"""
 
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 = "1.2.3"
requires-python = ">=3.12"
 
[project.scripts]
demo = "demo_pkg:main"
"""
 
INIT = """\
def main() -> None:
    print("hello from demo")
"""
 
 
def uv_available() -> bool:
    return shutil.which("uv") is not None
 
 
def inspect_wheel() -> 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()
        return {
            "wheel": wheel.name,
            "module": "demo_pkg/__init__.py" in names,
            "metadata": any(name.endswith(".dist-info/METADATA") for name in names),
            "record": any(name.endswith(".dist-info/RECORD") for name in names),
            "entry_points": any(name.endswith(".dist-info/entry_points.txt") for name in names),
        }
 
 
def main() -> None:
    if not uv_available():
        print("uv: missing")
        return
    facts = inspect_wheel()
    for key, value in facts.items():
        print(f"{key}: {value}")
 
 
if __name__ == "__main__":
    main()