hatch-ziglang 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,59 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: ["main"]
6
+ pull_request:
7
+ branches: ["main"]
8
+
9
+ permissions: {}
10
+
11
+ jobs:
12
+ tests:
13
+ name: "Python ${{ matrix.python-version }}"
14
+ runs-on: ubuntu-latest
15
+ permissions:
16
+ contents: read
17
+ strategy:
18
+ fail-fast: false
19
+ matrix:
20
+ python-version: ["3.10", "3.11", "3.12", "3.13", "3.14"]
21
+ steps:
22
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
23
+ with:
24
+ persist-credentials: false
25
+
26
+ - uses: astral-sh/setup-uv@08807647e7069bb48b6ef5acd8ec9567f424441b # v8.1.0
27
+ with:
28
+ python-version: "${{ matrix.python-version }}"
29
+ enable-cache: true
30
+
31
+ - name: Install dependencies
32
+ run: uv sync --group dev
33
+
34
+ - name: Lint
35
+ run: |
36
+ uv run ruff check .
37
+ uv run ruff format --check .
38
+
39
+ - name: Type check
40
+ run: uv run mypy src
41
+
42
+ - name: Run tests
43
+ run: uv run coverage run -m pytest
44
+
45
+ - name: Enforce coverage
46
+ run: uv run coverage report
47
+
48
+ # https://github.com/marketplace/actions/alls-green#why
49
+ check:
50
+ name: All green
51
+ if: always()
52
+ needs: [tests]
53
+ runs-on: ubuntu-latest
54
+ permissions: {}
55
+ steps:
56
+ - name: Decide whether the needed jobs succeeded or failed
57
+ uses: re-actors/alls-green@afee1c1eac2a506084c274e9c02c8e0687b48d9e # v1.2.2
58
+ with:
59
+ jobs: "${{ toJSON(needs) }}"
@@ -0,0 +1,60 @@
1
+ name: Publish
2
+
3
+ on:
4
+ push:
5
+ tags: ["*"]
6
+ workflow_dispatch:
7
+
8
+ permissions: {}
9
+
10
+ jobs:
11
+ build:
12
+ runs-on: ubuntu-latest
13
+ timeout-minutes: 10
14
+ permissions:
15
+ contents: read
16
+ steps:
17
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
18
+ with:
19
+ persist-credentials: false
20
+ fetch-depth: 0 # uv-dynamic-versioning derives the version from commit distance
21
+
22
+ - uses: astral-sh/setup-uv@08807647e7069bb48b6ef5acd8ec9567f424441b # v8.1.0
23
+ with:
24
+ python-version: "3.12"
25
+ enable-cache: false
26
+
27
+ - name: Build distributions
28
+ run: uv build
29
+
30
+ - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
31
+ with:
32
+ name: dist
33
+ path: dist/*
34
+
35
+ publish:
36
+ name: Publish to PyPI
37
+ runs-on: ubuntu-latest
38
+ needs: [build]
39
+ if: startsWith(github.ref, 'refs/tags/')
40
+
41
+ permissions:
42
+ id-token: write # trusted publishing (OIDC), no API token
43
+
44
+ environment:
45
+ name: pypi
46
+ url: https://pypi.org/project/hatch-ziglang
47
+
48
+ steps:
49
+ - name: Download distributions
50
+ uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
51
+ with:
52
+ name: dist
53
+ path: dist
54
+
55
+ - uses: astral-sh/setup-uv@08807647e7069bb48b6ef5acd8ec9567f424441b # v8.1.0
56
+ with:
57
+ enable-cache: false
58
+
59
+ - name: Publish to PyPI
60
+ run: uv publish --trusted-publishing always
@@ -0,0 +1,9 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ .venv/
4
+ dist/
5
+ .coverage
6
+ .coverage.*
7
+ .mypy_cache/
8
+ .pytest_cache/
9
+ .ruff_cache/
@@ -0,0 +1,28 @@
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2026, Marcelo Trylesinski
4
+
5
+ Redistribution and use in source and binary forms, with or without
6
+ modification, are permitted provided that the following conditions are met:
7
+
8
+ 1. Redistributions of source code must retain the above copyright notice, this
9
+ list of conditions and the following disclaimer.
10
+
11
+ 2. Redistributions in binary form must reproduce the above copyright notice,
12
+ this list of conditions and the following disclaimer in the documentation
13
+ and/or other materials provided with the distribution.
14
+
15
+ 3. Neither the name of the copyright holder nor the names of its
16
+ contributors may be used to endorse or promote products derived from
17
+ this software without specific prior written permission.
18
+
19
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
23
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
25
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
27
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,59 @@
1
+ Metadata-Version: 2.4
2
+ Name: hatch-ziglang
3
+ Version: 0.1.0
4
+ Summary: A Hatch build hook that compiles a Zig extension into the wheel.
5
+ Author-email: Marcelo Trylesinski <marcelotryle@gmail.com>
6
+ License-Expression: BSD-3-Clause
7
+ License-File: LICENSE
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Framework :: Hatch
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Zig
12
+ Requires-Python: >=3.10
13
+ Requires-Dist: hatchling
14
+ Description-Content-Type: text/markdown
15
+
16
+ # hatch-ziglang
17
+
18
+ A [Hatch](https://hatch.pypa.io/) build hook that compiles a [Zig](https://ziglang.org/) extension
19
+ into the wheel, against the building interpreter, with no out-of-band step.
20
+
21
+ `uv build` / `pip wheel` / cibuildwheel produce a correct, platform-tagged wheel: the `.so` is built
22
+ during the wheel build against `sys.executable`, and your `build.zig` installs it into the package as
23
+ `_<package><EXT_SUFFIX>`.
24
+
25
+ ## Usage
26
+
27
+ Add the build requirement and configure the hook in `pyproject.toml`:
28
+
29
+ ```toml
30
+ [build-system]
31
+ requires = ["hatchling", "hatch-ziglang", "ziglang==0.16.0"]
32
+ build-backend = "hatchling.build"
33
+
34
+ [tool.hatch.build.targets.wheel.hooks.zig]
35
+ package = "yourpkg"
36
+ optimize = "ReleaseFast" # optional; Zig -Doptimize mode (default ReleaseFast)
37
+ ```
38
+
39
+ | key | required | description |
40
+ | ---------- | -------- | -------------------------------------------------------------------------- |
41
+ | `package` | yes | the import package directory; artifact is `<package>/_<package><EXT_SUFFIX>` |
42
+ | `optimize` | no | Zig `-Doptimize` mode (default `ReleaseFast`) |
43
+
44
+ `HATCH_ZIG_BUILD_MODE` overrides `optimize` at build time.
45
+
46
+ ## What `build.zig` receives
47
+
48
+ The hook runs `zig build -Doptimize=<mode> [-Dtarget=...]` and passes the interpreter paths through
49
+ two environment variables your `build.zig` reads:
50
+
51
+ - `HATCH_ZIG_PYTHON_INCLUDE` - the building interpreter's `platinclude`
52
+ - `HATCH_ZIG_EXT_SUFFIX` - the building interpreter's `EXT_SUFFIX` (e.g. `.cpython-312-darwin.so`)
53
+
54
+ On macOS under cibuildwheel, the hook reads `ARCHFLAGS` and `MACOSX_DEPLOYMENT_TARGET` to emit a
55
+ matching `-Dtarget=<arch>-macos[.<min>]`, so the compiled `.so` and the wheel tag agree and delocate
56
+ accepts the repaired wheel.
57
+
58
+ Zig is resolved from a `zig` on `PATH`, falling back to the `ziglang` pip package (`python -m ziglang`),
59
+ which works inside cibuildwheel's manylinux containers.
@@ -0,0 +1,44 @@
1
+ # hatch-ziglang
2
+
3
+ A [Hatch](https://hatch.pypa.io/) build hook that compiles a [Zig](https://ziglang.org/) extension
4
+ into the wheel, against the building interpreter, with no out-of-band step.
5
+
6
+ `uv build` / `pip wheel` / cibuildwheel produce a correct, platform-tagged wheel: the `.so` is built
7
+ during the wheel build against `sys.executable`, and your `build.zig` installs it into the package as
8
+ `_<package><EXT_SUFFIX>`.
9
+
10
+ ## Usage
11
+
12
+ Add the build requirement and configure the hook in `pyproject.toml`:
13
+
14
+ ```toml
15
+ [build-system]
16
+ requires = ["hatchling", "hatch-ziglang", "ziglang==0.16.0"]
17
+ build-backend = "hatchling.build"
18
+
19
+ [tool.hatch.build.targets.wheel.hooks.zig]
20
+ package = "yourpkg"
21
+ optimize = "ReleaseFast" # optional; Zig -Doptimize mode (default ReleaseFast)
22
+ ```
23
+
24
+ | key | required | description |
25
+ | ---------- | -------- | -------------------------------------------------------------------------- |
26
+ | `package` | yes | the import package directory; artifact is `<package>/_<package><EXT_SUFFIX>` |
27
+ | `optimize` | no | Zig `-Doptimize` mode (default `ReleaseFast`) |
28
+
29
+ `HATCH_ZIG_BUILD_MODE` overrides `optimize` at build time.
30
+
31
+ ## What `build.zig` receives
32
+
33
+ The hook runs `zig build -Doptimize=<mode> [-Dtarget=...]` and passes the interpreter paths through
34
+ two environment variables your `build.zig` reads:
35
+
36
+ - `HATCH_ZIG_PYTHON_INCLUDE` - the building interpreter's `platinclude`
37
+ - `HATCH_ZIG_EXT_SUFFIX` - the building interpreter's `EXT_SUFFIX` (e.g. `.cpython-312-darwin.so`)
38
+
39
+ On macOS under cibuildwheel, the hook reads `ARCHFLAGS` and `MACOSX_DEPLOYMENT_TARGET` to emit a
40
+ matching `-Dtarget=<arch>-macos[.<min>]`, so the compiled `.so` and the wheel tag agree and delocate
41
+ accepts the repaired wheel.
42
+
43
+ Zig is resolved from a `zig` on `PATH`, falling back to the `ziglang` pip package (`python -m ziglang`),
44
+ which works inside cibuildwheel's manylinux containers.
@@ -0,0 +1,74 @@
1
+ [build-system]
2
+ requires = ["hatchling", "uv-dynamic-versioning>=0.8.0"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "hatch-ziglang"
7
+ description = "A Hatch build hook that compiles a Zig extension into the wheel."
8
+ readme = "README.md"
9
+ license = "BSD-3-Clause"
10
+ license-files = ["LICENSE"]
11
+ requires-python = ">=3.10"
12
+ authors = [{ name = "Marcelo Trylesinski", email = "marcelotryle@gmail.com" }]
13
+ classifiers = [
14
+ "Development Status :: 3 - Alpha",
15
+ "Framework :: Hatch",
16
+ "Programming Language :: Python :: 3",
17
+ "Programming Language :: Zig",
18
+ ]
19
+ dependencies = ["hatchling"]
20
+ dynamic = ["version"]
21
+
22
+ [project.entry-points.hatch]
23
+ zig = "hatch_ziglang.hooks"
24
+
25
+ [dependency-groups]
26
+ dev = ["pytest>=8.0", "coverage>=7.0", "ruff", "mypy"]
27
+
28
+ [tool.hatch.version]
29
+ source = "uv-dynamic-versioning"
30
+
31
+ [tool.uv-dynamic-versioning]
32
+ vcs = "git"
33
+ style = "pep440"
34
+ bump = true
35
+ metadata = false
36
+ fallback-version = "0.0.0"
37
+
38
+ [tool.pytest.ini_options]
39
+ addopts = "-rxXs --strict-config --strict-markers"
40
+ xfail_strict = true
41
+ testpaths = ["tests"]
42
+ filterwarnings = ["error"]
43
+
44
+ [tool.coverage.run]
45
+ source_pkgs = ["hatch_ziglang", "tests"]
46
+ branch = true
47
+ parallel = true
48
+
49
+ [tool.coverage.report]
50
+ precision = 2
51
+ fail_under = 100
52
+ show_missing = true
53
+ skip_covered = true
54
+ exclude_lines = [
55
+ "pragma: no cover",
56
+ "if TYPE_CHECKING:",
57
+ "raise NotImplementedError",
58
+ "@overload",
59
+ ]
60
+
61
+ [tool.ruff]
62
+ line-length = 120
63
+
64
+ [tool.ruff.lint]
65
+ select = ["E", "F", "I", "FA", "UP", "RUF100"]
66
+
67
+ [tool.ruff.lint.isort]
68
+ combine-as-imports = true
69
+
70
+ [tool.mypy]
71
+ strict = true
72
+ warn_unused_ignores = true
73
+ show_error_codes = true
74
+ files = ["src"]
@@ -0,0 +1,5 @@
1
+ from __future__ import annotations
2
+
3
+ from hatch_ziglang.plugin import ZigBuildHook
4
+
5
+ __all__ = ["ZigBuildHook"]
@@ -0,0 +1,10 @@
1
+ from __future__ import annotations
2
+
3
+ from hatchling.plugin import hookimpl
4
+
5
+ from hatch_ziglang.plugin import ZigBuildHook
6
+
7
+
8
+ @hookimpl
9
+ def hatch_register_build_hook() -> type[ZigBuildHook]:
10
+ return ZigBuildHook
@@ -0,0 +1,113 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import shutil
5
+ import subprocess
6
+ import sys
7
+ import sysconfig
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ from hatchling.builders.hooks.plugin.interface import BuildHookInterface
12
+
13
+ # cibuildwheel builds every macOS wheel on the arm64 runner and asks for a
14
+ # specific arch through ARCHFLAGS; translate it into a Zig cross-compile target
15
+ # so the produced `.so` matches the wheel tag delocate enforces.
16
+ _MACOS_ZIG_ARCH = {"arm64": "aarch64-macos", "x86_64": "x86_64-macos"}
17
+
18
+
19
+ def _zig_target_args() -> list[str]:
20
+ archflags = os.environ.get("ARCHFLAGS", "")
21
+ arches = archflags.split()[1::2] # "-arch x86_64 -arch arm64" -> ["x86_64", "arm64"]
22
+ if len(arches) != 1 or sys.platform != "darwin":
23
+ return []
24
+ arch = _MACOS_ZIG_ARCH.get(arches[0])
25
+ if not arch:
26
+ return []
27
+ # Pin the binary's minimum macOS to MACOSX_DEPLOYMENT_TARGET (set by
28
+ # cibuildwheel) so the wheel tag and the `.so`'s required OS version agree
29
+ # and delocate accepts the repaired wheel.
30
+ min_version = os.environ.get("MACOSX_DEPLOYMENT_TARGET")
31
+ target = f"{arch}.{min_version}" if min_version else arch
32
+ return [f"-Dtarget={target}"]
33
+
34
+
35
+ def _zig_command() -> list[str]:
36
+ """Resolve how to invoke Zig: a `zig` on PATH, else the `ziglang` pip package.
37
+
38
+ The pip fallback (`python -m ziglang`) works identically on the host and inside
39
+ cibuildwheel's manylinux containers, where a host-installed `zig` isn't visible.
40
+ """
41
+ if shutil.which("zig"):
42
+ return ["zig"]
43
+ try:
44
+ import ziglang # type: ignore[import-not-found] # noqa: F401
45
+ except ImportError:
46
+ raise RuntimeError(
47
+ "Zig toolchain not found: install Zig and put it on PATH, or `pip install ziglang`."
48
+ ) from None
49
+ return [sys.executable, "-m", "ziglang"]
50
+
51
+
52
+ class ZigBuildHook(BuildHookInterface[Any]):
53
+ """Compile a Zig extension against the building interpreter during the wheel build.
54
+
55
+ This makes `uv build` / `pip wheel` / cibuildwheel produce a correct, platform-tagged
56
+ wheel with no out-of-band step: the `.so` is built here, against `sys.executable`, and
57
+ `build.zig` installs it into `<package>/` as `_<package><EXT_SUFFIX>`.
58
+
59
+ Configured in `[tool.hatch.build.targets.wheel.hooks.zig]`:
60
+
61
+ package the import package directory; the artifact is `<package>/_<package><EXT_SUFFIX>`
62
+ optimize Zig `-Doptimize` mode (default ReleaseFast); overridable via HATCH_ZIG_BUILD_MODE
63
+
64
+ `build.zig` receives the interpreter paths through `HATCH_ZIG_PYTHON_INCLUDE` and
65
+ `HATCH_ZIG_EXT_SUFFIX`.
66
+ """
67
+
68
+ PLUGIN_NAME = "zig"
69
+
70
+ @property
71
+ def _package(self) -> str:
72
+ package = self.config.get("package")
73
+ if not package:
74
+ raise ValueError("hatch-zig requires `package` in [tool.hatch.build.targets.wheel.hooks.zig]")
75
+ return str(package)
76
+
77
+ @property
78
+ def _optimize(self) -> str:
79
+ return os.environ.get("HATCH_ZIG_BUILD_MODE", str(self.config.get("optimize", "ReleaseFast")))
80
+
81
+ def initialize(self, version: str, build_data: dict[str, Any]) -> None:
82
+ if self.target_name != "wheel":
83
+ return
84
+
85
+ root = Path(self.root)
86
+ include = sysconfig.get_path("platinclude")
87
+ ext_suffix = sysconfig.get_config_var("EXT_SUFFIX")
88
+ if not include or not ext_suffix:
89
+ raise RuntimeError("could not resolve platinclude / EXT_SUFFIX from the building interpreter")
90
+
91
+ env = {**os.environ, "HATCH_ZIG_PYTHON_INCLUDE": include, "HATCH_ZIG_EXT_SUFFIX": ext_suffix}
92
+ subprocess.run(
93
+ [*_zig_command(), "build", f"-Doptimize={self._optimize}", *_zig_target_args()],
94
+ cwd=root,
95
+ env=env,
96
+ check=True,
97
+ )
98
+
99
+ artifact = f"{self._package}/_{self._package}{ext_suffix}"
100
+ if not (root / artifact).exists():
101
+ raise RuntimeError(f"zig build did not produce {artifact}")
102
+
103
+ # Tag the wheel for this interpreter + platform rather than py3-none-any.
104
+ build_data["pure_python"] = False
105
+ build_data["infer_tag"] = True
106
+ build_data["artifacts"].append(artifact)
107
+
108
+ def clean(self, versions: list[str]) -> None:
109
+ root = Path(self.root)
110
+ for suffix in ("so", "pyd"):
111
+ for path in root.glob(f"{self._package}/_{self._package}*.{suffix}"):
112
+ path.unlink()
113
+ print(f"removed compiled extensions; building Zig core via {sys.executable}", file=sys.stderr)
File without changes
@@ -0,0 +1,157 @@
1
+ from __future__ import annotations
2
+
3
+ import sysconfig
4
+ from pathlib import Path
5
+ from typing import Any
6
+ from unittest import mock
7
+
8
+ import pytest
9
+
10
+ from hatch_ziglang.hooks import hatch_register_build_hook
11
+ from hatch_ziglang.plugin import ZigBuildHook, _zig_command, _zig_target_args
12
+
13
+
14
+ def make_hook(root: Path, config: dict[str, Any], target_name: str = "wheel") -> ZigBuildHook:
15
+ return ZigBuildHook(
16
+ str(root),
17
+ config,
18
+ None,
19
+ None,
20
+ str(root),
21
+ target_name,
22
+ )
23
+
24
+
25
+ def test_entry_point_registers_hook() -> None:
26
+ assert hatch_register_build_hook() is ZigBuildHook
27
+ assert ZigBuildHook.PLUGIN_NAME == "zig"
28
+
29
+
30
+ def test_package_required(tmp_path: Path) -> None:
31
+ hook = make_hook(tmp_path, {})
32
+ with pytest.raises(ValueError, match="requires `package`"):
33
+ _ = hook._package
34
+
35
+
36
+ def test_optimize_default_and_override(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
37
+ hook = make_hook(tmp_path, {"package": "foo"})
38
+ monkeypatch.delenv("HATCH_ZIG_BUILD_MODE", raising=False)
39
+ assert hook._optimize == "ReleaseFast"
40
+
41
+ hook = make_hook(tmp_path, {"package": "foo", "optimize": "ReleaseSafe"})
42
+ assert hook._optimize == "ReleaseSafe"
43
+
44
+ monkeypatch.setenv("HATCH_ZIG_BUILD_MODE", "Debug")
45
+ assert hook._optimize == "Debug"
46
+
47
+
48
+ def test_initialize_skips_non_wheel(tmp_path: Path) -> None:
49
+ hook = make_hook(tmp_path, {"package": "foo"}, target_name="sdist")
50
+ build_data: dict[str, Any] = {"artifacts": []}
51
+ with mock.patch("hatch_ziglang.plugin.subprocess.run") as run:
52
+ hook.initialize("1.0", build_data)
53
+ run.assert_not_called()
54
+ assert build_data == {"artifacts": []}
55
+
56
+
57
+ def test_initialize_builds_and_tags(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
58
+ ext_suffix = sysconfig.get_config_var("EXT_SUFFIX")
59
+ (tmp_path / "foo").mkdir()
60
+ artifact = tmp_path / "foo" / f"_foo{ext_suffix}"
61
+ monkeypatch.delenv("ARCHFLAGS", raising=False)
62
+
63
+ hook = make_hook(tmp_path, {"package": "foo"})
64
+ build_data: dict[str, Any] = {"artifacts": []}
65
+
66
+ def fake_run(cmd: list[str], **kwargs: Any) -> None:
67
+ artifact.write_bytes(b"")
68
+ assert "-Doptimize=ReleaseFast" in cmd
69
+ assert kwargs["env"]["HATCH_ZIG_PYTHON_INCLUDE"]
70
+ assert kwargs["env"]["HATCH_ZIG_EXT_SUFFIX"] == ext_suffix
71
+
72
+ with mock.patch("hatch_ziglang.plugin._zig_command", return_value=["zig"]):
73
+ with mock.patch("hatch_ziglang.plugin.subprocess.run", side_effect=fake_run):
74
+ hook.initialize("1.0", build_data)
75
+
76
+ assert build_data["pure_python"] is False
77
+ assert build_data["infer_tag"] is True
78
+ assert f"foo/_foo{ext_suffix}" in build_data["artifacts"]
79
+
80
+
81
+ def test_initialize_missing_artifact(tmp_path: Path) -> None:
82
+ hook = make_hook(tmp_path, {"package": "foo"})
83
+ with mock.patch("hatch_ziglang.plugin._zig_command", return_value=["zig"]):
84
+ with mock.patch("hatch_ziglang.plugin.subprocess.run"):
85
+ with pytest.raises(RuntimeError, match="did not produce"):
86
+ hook.initialize("1.0", {"artifacts": []})
87
+
88
+
89
+ def test_initialize_missing_interpreter_paths(tmp_path: Path) -> None:
90
+ hook = make_hook(tmp_path, {"package": "foo"})
91
+ with mock.patch("hatch_ziglang.plugin.sysconfig.get_path", return_value=None):
92
+ with pytest.raises(RuntimeError, match="platinclude"):
93
+ hook.initialize("1.0", {"artifacts": []})
94
+
95
+
96
+ def test_clean_removes_extensions(tmp_path: Path) -> None:
97
+ (tmp_path / "foo").mkdir()
98
+ so = tmp_path / "foo" / "_foo.cpython-312-darwin.so"
99
+ pyd = tmp_path / "foo" / "_foo.cp312-win_amd64.pyd"
100
+ so.write_bytes(b"")
101
+ pyd.write_bytes(b"")
102
+
103
+ hook = make_hook(tmp_path, {"package": "foo"})
104
+ hook.clean(["1.0"])
105
+
106
+ assert not so.exists()
107
+ assert not pyd.exists()
108
+
109
+
110
+ def test_zig_command_prefers_path() -> None:
111
+ with mock.patch("hatch_ziglang.plugin.shutil.which", return_value="/usr/bin/zig"):
112
+ assert _zig_command() == ["zig"]
113
+
114
+
115
+ def test_zig_command_falls_back_to_ziglang() -> None:
116
+ with mock.patch("hatch_ziglang.plugin.shutil.which", return_value=None):
117
+ with mock.patch.dict("sys.modules", {"ziglang": mock.Mock()}):
118
+ assert _zig_command()[1:] == ["-m", "ziglang"]
119
+
120
+
121
+ def test_zig_command_missing_toolchain() -> None:
122
+ with mock.patch("hatch_ziglang.plugin.shutil.which", return_value=None):
123
+ with mock.patch.dict("sys.modules", {"ziglang": None}):
124
+ with pytest.raises(RuntimeError, match="Zig toolchain not found"):
125
+ _zig_command()
126
+
127
+
128
+ def test_zig_target_args_non_macos(monkeypatch: pytest.MonkeyPatch) -> None:
129
+ monkeypatch.setenv("ARCHFLAGS", "-arch arm64")
130
+ monkeypatch.setattr("hatch_ziglang.plugin.sys.platform", "linux")
131
+ assert _zig_target_args() == []
132
+
133
+
134
+ def test_zig_target_args_no_single_arch(monkeypatch: pytest.MonkeyPatch) -> None:
135
+ monkeypatch.setattr("hatch_ziglang.plugin.sys.platform", "darwin")
136
+ monkeypatch.setenv("ARCHFLAGS", "-arch arm64 -arch x86_64")
137
+ assert _zig_target_args() == []
138
+
139
+
140
+ def test_zig_target_args_unknown_arch(monkeypatch: pytest.MonkeyPatch) -> None:
141
+ monkeypatch.setattr("hatch_ziglang.plugin.sys.platform", "darwin")
142
+ monkeypatch.setenv("ARCHFLAGS", "-arch ppc64")
143
+ assert _zig_target_args() == []
144
+
145
+
146
+ def test_zig_target_args_with_min_version(monkeypatch: pytest.MonkeyPatch) -> None:
147
+ monkeypatch.setattr("hatch_ziglang.plugin.sys.platform", "darwin")
148
+ monkeypatch.setenv("ARCHFLAGS", "-arch x86_64")
149
+ monkeypatch.setenv("MACOSX_DEPLOYMENT_TARGET", "11.0")
150
+ assert _zig_target_args() == ["-Dtarget=x86_64-macos.11.0"]
151
+
152
+
153
+ def test_zig_target_args_without_min_version(monkeypatch: pytest.MonkeyPatch) -> None:
154
+ monkeypatch.setattr("hatch_ziglang.plugin.sys.platform", "darwin")
155
+ monkeypatch.setenv("ARCHFLAGS", "-arch arm64")
156
+ monkeypatch.delenv("MACOSX_DEPLOYMENT_TARGET", raising=False)
157
+ assert _zig_target_args() == ["-Dtarget=aarch64-macos"]