|
| 1 | +# SPDX-License-Identifier: GPL-3.0-or-later |
| 2 | +# SPDX-FileCopyrightText: 2026 sp00ktober |
| 3 | +"""Build the extension zip into dist/; `test` also runs tests/ inside Blender. |
| 4 | +
|
| 5 | +uv run apps/blender/build.py [build | test [PYTEST_ARGS]] [--blender PATH] |
| 6 | +""" |
| 7 | + |
| 8 | +import argparse |
| 9 | +import json |
| 10 | +import os |
| 11 | +import re |
| 12 | +import shutil |
| 13 | +import subprocess |
| 14 | +import sys |
| 15 | +import tempfile |
| 16 | +import tomllib |
| 17 | +from pathlib import Path |
| 18 | +from typing import Any |
| 19 | + |
| 20 | +HERE = Path(__file__).resolve().parent |
| 21 | +ROOT = HERE.parents[1] |
| 22 | +SOURCE = HERE / "src" / "mhfu_blender" |
| 23 | +DIST = HERE / "dist" |
| 24 | +CACHE = HERE / ".cache" |
| 25 | +PROJECT = tomllib.loads((HERE / "pyproject.toml").read_text())["project"] |
| 26 | +ID = tomllib.loads((SOURCE / "blender_manifest.toml").read_text())["id"] |
| 27 | +REPO = "user_default" # Blender's built-in local repository |
| 28 | +PROVIDED = {"numpy"} # Blender's own; a bundled copy would shadow it for every extension |
| 29 | +MACOS = "/Applications/Blender.app/Contents/MacOS/Blender" |
| 30 | + |
| 31 | + |
| 32 | +def run(*args: str | Path, env: dict[str, str] | None = None, capture: bool = False) -> str: |
| 33 | + sys.stdout.flush() # keeps our lines in order with the command's |
| 34 | + pipe = subprocess.PIPE if capture else None |
| 35 | + done = subprocess.run( |
| 36 | + [str(a) for a in args], check=True, text=True, cwd=ROOT, env=env, stdout=pipe |
| 37 | + ) |
| 38 | + return done.stdout or "" |
| 39 | + |
| 40 | + |
| 41 | +def extension(blender: str, *args: str | Path, env: dict[str, str] | None = None) -> None: |
| 42 | + run(blender, "--command", "extension", *args, env=env) |
| 43 | + |
| 44 | + |
| 45 | +def locked(*args: str) -> list[dict[str, Any]]: |
| 46 | + """uv.lock's packages for these `uv export` arguments, as pylock.toml entries.""" |
| 47 | + out = run( |
| 48 | + "uv", "export", "--frozen", "--format=pylock.toml", "--no-emit-project", *args, capture=True |
| 49 | + ) |
| 50 | + packages: list[dict[str, Any]] = tomllib.loads(out)["packages"] |
| 51 | + return packages |
| 52 | + |
| 53 | + |
| 54 | +def stage_wheels(wheels: Path) -> None: |
| 55 | + """The dependency closure as pure wheels: workspace members built, the rest as uv.lock pins.""" |
| 56 | + members, pins, skipped = [], [], set() |
| 57 | + for package in locked("--package", PROJECT["name"], "--no-default-groups"): |
| 58 | + name = package["name"] |
| 59 | + pure = [w for w in package.get("wheels", []) if w["url"].endswith("-none-any.whl")] |
| 60 | + if "directory" in package: |
| 61 | + members.append(name) |
| 62 | + elif pure and name not in PROVIDED: |
| 63 | + pins.append(f"{name} @ {pure[0]['url']} --hash=sha256:{pure[0]['hashes']['sha256']}\n") |
| 64 | + else: |
| 65 | + skipped.add(name) |
| 66 | + for name in members: |
| 67 | + run("uv", "build", "--quiet", "--package", name, "--wheel", "--out-dir", wheels) |
| 68 | + requirements = wheels.parent / "requirements.txt" |
| 69 | + requirements.write_text("".join(pins)) |
| 70 | + run("uvx", "pip", "download", "--quiet", "--no-deps", "--dest", wheels, "-r", requirements) |
| 71 | + print("skipped (Blender's own, or no pure wheel):", ", ".join(sorted(skipped))) |
| 72 | + |
| 73 | + |
| 74 | +def build(blender: str) -> Path: |
| 75 | + """Stage the source with its wheels, build the zip and validate it.""" |
| 76 | + archive = DIST / f"{ID}-{PROJECT['version']}.zip" |
| 77 | + with tempfile.TemporaryDirectory() as tmp: |
| 78 | + stage = Path(tmp) / ID |
| 79 | + shutil.copytree(SOURCE, stage, ignore=shutil.ignore_patterns("__pycache__")) |
| 80 | + stage_wheels(stage / "wheels") |
| 81 | + wheels = sorted(f"./wheels/{w.name}" for w in (stage / "wheels").glob("*.whl")) |
| 82 | + print("bundled:", ", ".join(w.removeprefix("./wheels/") for w in wheels)) |
| 83 | + manifest = stage / "blender_manifest.toml" |
| 84 | + text = manifest.read_text() |
| 85 | + table = text.index("\n[") + 1 # top-level keys go before the first table |
| 86 | + keys = f'version = "{PROJECT["version"]}"\nwheels = {json.dumps(wheels)}\n\n' |
| 87 | + manifest.write_text(text[:table] + keys + text[table:]) |
| 88 | + DIST.mkdir(exist_ok=True) |
| 89 | + extension(blender, "build", "--source-dir", stage, "--output-filepath", archive) |
| 90 | + extension(blender, "validate", archive) |
| 91 | + return archive |
| 92 | + |
| 93 | + |
| 94 | +def _marker(package: dict[str, Any]) -> str: |
| 95 | + return f"; {package['marker']}" if "marker" in package else "" |
| 96 | + |
| 97 | + |
| 98 | +def pytest_dir(python: str) -> Path: |
| 99 | + """pytest at uv.lock's pins for Blender's Python, installed once under .cache/.""" |
| 100 | + pins = [p for p in locked("--only-group", "dev", "--no-emit-workspace") if "version" in p] |
| 101 | + version = next(p["version"] for p in pins if p["name"] == "pytest") |
| 102 | + target = CACHE / f"pytest-{version}-py{python}" |
| 103 | + if target.is_dir(): |
| 104 | + return target |
| 105 | + CACHE.mkdir(exist_ok=True) |
| 106 | + with tempfile.TemporaryDirectory(dir=CACHE) as tmp: # renamed into place once complete |
| 107 | + constraints = Path(tmp) / "constraints.txt" |
| 108 | + constraints.write_text("".join(f"{p['name']}=={p['version']}{_marker(p)}\n" for p in pins)) |
| 109 | + install = Path(tmp) / "pytest" |
| 110 | + run("uv", "pip", "install", "--quiet", "--only-binary=:all:", "--target", install, |
| 111 | + "--python-version", python, "-c", constraints, "pytest") # fmt: skip |
| 112 | + install.rename(target) |
| 113 | + return target |
| 114 | + |
| 115 | + |
| 116 | +def test(blender: str, archive: Path, pytest_args: list[str]) -> int: |
| 117 | + """Install the zip into a throwaway profile and run pytest inside Blender; pytest's code.""" |
| 118 | + with tempfile.TemporaryDirectory() as profile: |
| 119 | + env = {**os.environ, "BLENDER_USER_RESOURCES": profile} |
| 120 | + extension(blender, "install-file", "-r", REPO, "-e", archive, env=env) |
| 121 | + probe = "import sys; print('PYTHON=%d.%d' % sys.version_info[:2])" |
| 122 | + out = run(blender, "-b", "--factory-startup", "--python-expr", probe, env=env, capture=True) |
| 123 | + python = re.search(r"^PYTHON=(\S+)$", out, re.M) |
| 124 | + assert python, out |
| 125 | + paths = [str(pytest_dir(python[1])), str(ROOT / "packages" / "modkit-testing" / "src")] |
| 126 | + args = [str(HERE / "tests"), "-p", "modkit_testing", "-p", "no:cacheprovider"] |
| 127 | + args += ["-W", "ignore::pytest.PytestConfigWarning", *pytest_args] # root's asyncio keys |
| 128 | + expr = f"import sys; sys.path[:0] = {paths}; import pytest; sys.exit(pytest.main({args}))" |
| 129 | + env["MHFU_BLENDER_EXTENSION"] = f"bl_ext.{REPO}.{ID}" |
| 130 | + command = [blender, "-b", "--factory-startup", "--python-exit-code", "1"] |
| 131 | + return subprocess.run([*command, "--python-expr", expr], cwd=ROOT, env=env).returncode |
| 132 | + |
| 133 | + |
| 134 | +def main() -> int: |
| 135 | + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) |
| 136 | + parser.add_argument("command", nargs="?", choices=["build", "test"], default="build") |
| 137 | + default = os.environ.get("BLENDER") or (MACOS if sys.platform == "darwin" else "blender") |
| 138 | + parser.add_argument("--blender", default=default, help="its binary (default: %(default)s)") |
| 139 | + args, pytest_args = parser.parse_known_args() |
| 140 | + if pytest_args and args.command != "test": |
| 141 | + parser.error(f"unrecognized arguments: {' '.join(pytest_args)}") |
| 142 | + archive = build(args.blender) |
| 143 | + print(f"{archive} ({archive.stat().st_size / 1e6:.1f} MB)") |
| 144 | + return test(args.blender, archive, pytest_args) if args.command == "test" else 0 |
| 145 | + |
| 146 | + |
| 147 | +if __name__ == "__main__": |
| 148 | + try: |
| 149 | + sys.exit(main()) |
| 150 | + except subprocess.CalledProcessError as error: # the command has printed why |
| 151 | + sys.exit(error.returncode) |
0 commit comments