hatch-ziglang 0.1.0__py3-none-any.whl

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,5 @@
1
+ from __future__ import annotations
2
+
3
+ from hatch_ziglang.plugin import ZigBuildHook
4
+
5
+ __all__ = ["ZigBuildHook"]
hatch_ziglang/hooks.py ADDED
@@ -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)
hatch_ziglang/py.typed ADDED
File without changes
@@ -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,9 @@
1
+ hatch_ziglang/__init__.py,sha256=qz4ZKjWmBW8Pf2P3CQDDGgG4uNy6MH4E1L_UMzyuHuo,110
2
+ hatch_ziglang/hooks.py,sha256=yXuaQjSsogyHjncTVHN0KUoy-CqDRbIOpFQXgF0T44Y,212
3
+ hatch_ziglang/plugin.py,sha256=QXCmteW_aQNqrLEJqTHLbMRPkBRZ5-N-kNtQ7pOevsI,4503
4
+ hatch_ziglang/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ hatch_ziglang-0.1.0.dist-info/METADATA,sha256=k6xlkfxOhfEMifdnuCCQrNHIL-55u9aQuHHHtr81wzU,2486
6
+ hatch_ziglang-0.1.0.dist-info/WHEEL,sha256=mffPy8wBnZQn2VnJUU5jE99KsxaSfiyMHV9Yt0aLVxs,87
7
+ hatch_ziglang-0.1.0.dist-info/entry_points.txt,sha256=Af31AaHRsiqgKnMGc8XBKzVGBX2S4jE3rnlopcZDkQE,34
8
+ hatch_ziglang-0.1.0.dist-info/licenses/LICENSE,sha256=kc2txe_3vm9n3Rz-GRj36CvCVyLpZD9WHaOEUtL2PPg,1506
9
+ hatch_ziglang-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.30.1
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [hatch]
2
+ zig = hatch_ziglang.hooks
@@ -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.