示例工程 32-capstone-publishable-package

32-capstone-publishable-package/01-package-skeleton/package_skeleton.py

python · 2.4 KB

"""构建 src layout 包并验证文件与公共 API。"""
 
from __future__ import annotations
 
import os
import shutil
import subprocess
import sys
import tempfile
import zipfile
from pathlib import Path
 
PYPROJECT = """\
[build-system]
requires = ["uv_build>=0.9,<0.14"]
build-backend = "uv_build"
 
[project]
name = "capstone-pkg"
version = "1.0.0"
requires-python = ">=3.12"
 
[project.scripts]
capstone = "capstone_pkg.cli:main"
"""
 
INIT = """\
from .cli import main
from .core import add
 
__all__ = ["add", "main"]
__version__ = "1.0.0"
"""
 
CORE = """\
def add(left: int, right: int) -> int:
    return left + right
"""
 
CLI = """\
def main(argv: list[str] | None = None) -> int:
    return 0
"""
 
 
def uv_available() -> bool:
    return shutil.which("uv") is not None
 
 
def build_and_check() -> dict[str, object]:
    with tempfile.TemporaryDirectory() as tmp:
        root = Path(tmp)
        package = root / "src" / "capstone_pkg"
        package.mkdir(parents=True)
        (root / "pyproject.toml").write_text(PYPROJECT, encoding="utf-8")
        (package / "__init__.py").write_text(INIT, encoding="utf-8")
        (package / "core.py").write_text(CORE, encoding="utf-8")
        (package / "cli.py").write_text(CLI, 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()
            archive.extractall(root / "site")
        env = os.environ.copy()
        env["PYTHONPATH"] = str(root / "site")
        check = subprocess.run(
            [sys.executable, "-c", "import capstone_pkg; print(capstone_pkg.__all__)"],
            capture_output=True,
            text=True,
            env=env,
            check=False,
        )
        return {
            "wheel": wheel.name,
            "core": "capstone_pkg/core.py" in names,
            "cli": "capstone_pkg/cli.py" in names,
            "api": check.stdout.strip(),
        }
 
 
def main() -> None:
    if not uv_available():
        print("uv: missing")
        return
    facts = build_and_check()
    for key, value in facts.items():
        print(f"{key}: {value}")
 
 
if __name__ == "__main__":
    main()