hatch-prebuilt 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,299 @@
1
+ """Build Python wheels that install prebuilt executables unchanged.
2
+
3
+ A wheel repository describes its tool in a small `hatch_build.py`: a
4
+ :class:`Recipe` subclass that lists the platforms and says how to get the
5
+ files for one version and platform. This package does the rest: picks the
6
+ version and platform, checks every executable, works out the wheel tag, and
7
+ gives hatchling the files, so pip and uv install the executables unchanged
8
+ into the environment's bin/ (Scripts\\ on Windows), with no Python wrapper in
9
+ between::
10
+
11
+ # hatch_build.py
12
+ from pathlib import Path
13
+ from hatch_prebuilt import Platform, Recipe, Staged
14
+
15
+ class MyTool(Recipe):
16
+ name = "mytool"
17
+ version_file = "mytool_version.txt"
18
+ platform_variable = "MYTOOL_PLATFORM"
19
+ platforms = (Platform("linux-x86_64", "manylinux_2_17_x86_64", "elf-x86_64", "linux", "x86_64"),)
20
+
21
+ def stage(self, platform, version):
22
+ ...
23
+ return Staged(scripts={"mytool": binary}, licenses={"LICENSE": text})
24
+
25
+ RECIPE = MyTool(Path(__file__).parent)
26
+ get_metadata_hook, get_build_hook = RECIPE.hooks()
27
+
28
+ if __name__ == "__main__":
29
+ raise SystemExit(RECIPE.main())
30
+
31
+ and pyproject.toml enables both hooks::
32
+
33
+ [project]
34
+ dynamic = ["version"]
35
+ license-files = ["upstream/LICENSE"]
36
+
37
+ [tool.hatch.metadata.hooks.custom]
38
+ [tool.hatch.build.targets.wheel]
39
+ bypass-selection = true
40
+ [tool.hatch.build.targets.wheel.hooks.custom]
41
+
42
+ `python hatch_build.py platforms` prints the platform names, one per line,
43
+ for CI to build each one with ``<platform_variable>=<name> python -m build
44
+ --wheel``.
45
+ """
46
+
47
+ from __future__ import annotations
48
+
49
+ import json
50
+ import os
51
+ import platform as host
52
+ import re
53
+ import shutil
54
+ import sys
55
+ from collections.abc import Mapping, Sequence
56
+ from dataclasses import dataclass, field
57
+ from pathlib import Path
58
+ from typing import Any, Callable
59
+
60
+ from .binary import check_binary, extract, macos_tag
61
+ from .download import cached_download, check_sha512, http_get, log, verify_minisign
62
+
63
+ __all__ = [
64
+ "Platform",
65
+ "Recipe",
66
+ "Staged",
67
+ "cached_download",
68
+ "check_binary",
69
+ "check_sha512",
70
+ "extract",
71
+ "http_get",
72
+ "log",
73
+ "macos_tag",
74
+ "verify_minisign",
75
+ ]
76
+
77
+
78
+ @dataclass(frozen=True)
79
+ class Platform:
80
+ """One wheel: a platform the recipe has executables for."""
81
+
82
+ name: str
83
+ """The platform's name in the repository, e.g. ``linux-amd64``."""
84
+ tag: str
85
+ """The wheel's platform tag (a compressed tag set is fine). ``{macos}`` is
86
+ replaced with the minimum macOS version that the executables declare."""
87
+ check: str
88
+ """What every executable must be, see :func:`check_binary`."""
89
+ os: str
90
+ """``linux``, ``macos`` or ``windows``: picks the platform of the build
91
+ machine when no platform is given."""
92
+ arch: str
93
+ """``x86_64``, ``arm64``, ``riscv64``, ``s390x`` or ``universal`` (macOS)."""
94
+ extra: Mapping[str, Any] = field(default_factory=dict)
95
+ """Anything else the recipe needs, e.g. the upstream archive name."""
96
+
97
+ @property
98
+ def exe(self) -> str:
99
+ """The executable suffix: ``.exe`` on Windows."""
100
+ return ".exe" if self.os == "windows" else ""
101
+
102
+
103
+ @dataclass
104
+ class Staged:
105
+ """The files of one wheel, as :meth:`Recipe.stage` returns them."""
106
+
107
+ scripts: dict[str, bytes]
108
+ """Executables, by file name (with .exe on Windows), for bin/."""
109
+ licenses: dict[str, bytes] = field(default_factory=dict)
110
+ """License files, by file name. They are written to upstream/, where
111
+ pyproject.toml's ``license-files`` finds them."""
112
+ data: dict[str, bytes] = field(default_factory=dict)
113
+ """Other files, by path in the environment, e.g. share/man/man1/x.1."""
114
+
115
+
116
+ class Recipe:
117
+ """What a wheel repository packages. Subclass it in hatch_build.py."""
118
+
119
+ name: str = ""
120
+ """The tool's name, for messages."""
121
+ version_file: str = ""
122
+ """The file that holds the wheel version, relative to the repository."""
123
+ version_variable: str = ""
124
+ """An environment variable that overrides the version file, so CI can
125
+ build other versions. Empty means the version file only."""
126
+ version_pattern: str = r"\d+(\.\d+)+(\.post\d+)?"
127
+ """What a wheel version looks like."""
128
+ platform_variable: str = ""
129
+ """The environment variable that names the platform to build."""
130
+ platforms: Sequence[Platform] = ()
131
+
132
+ def __init__(self, root: Path) -> None:
133
+ self.root = Path(root).resolve()
134
+ self.stage_dir = self.root / "upstream"
135
+ self.cache = self.root / ".cache" / "downloads"
136
+
137
+ # --- what a recipe implements ------------------------------------------
138
+
139
+ def stage(self, platform: Platform, version: str) -> Staged:
140
+ """Download and verify the files of one version for one platform."""
141
+ raise NotImplementedError
142
+
143
+ def upstream_version(self, version: str) -> str:
144
+ """The upstream version inside a wheel version: 4.14.3.post1 -> 4.14.3."""
145
+ return version.split(".post")[0]
146
+
147
+ def commands(self) -> dict[str, Callable[[list[str]], int]]:
148
+ """Extra commands for ``python hatch_build.py <command> [args]``."""
149
+ return {}
150
+
151
+ # --- versions and platforms --------------------------------------------
152
+
153
+ def wheel_version(self) -> str:
154
+ version = os.environ.get(self.version_variable, "") if self.version_variable else ""
155
+ if not version:
156
+ version = (self.root / self.version_file).read_text().strip()
157
+ if not re.fullmatch(self.version_pattern, version):
158
+ raise ValueError(f"bad version {version!r} for {self.name}")
159
+ return version
160
+
161
+ def get_platform(self, name: str) -> Platform:
162
+ for platform in self.platforms:
163
+ if platform.name == name:
164
+ return platform
165
+ choices = ", ".join(p.name for p in self.platforms)
166
+ raise ValueError(f"{self.name} has no platform {name!r}; choose one of {choices}")
167
+
168
+ def host_platform(self) -> Platform:
169
+ machine = host.machine().lower()
170
+ arch = {"amd64": "x86_64", "aarch64": "arm64"}.get(machine, machine)
171
+ os_name = {"darwin": "macos", "win32": "windows"}.get(sys.platform, sys.platform)
172
+ if os_name.startswith("linux"):
173
+ os_name = "linux"
174
+ for platform in self.platforms:
175
+ if platform.os == os_name and platform.arch in (arch, "universal"):
176
+ return platform
177
+ raise ValueError(
178
+ f"{self.name} has no platform for this machine ({os_name} {arch}); "
179
+ f"set {self.platform_variable} to one of " + ", ".join(p.name for p in self.platforms)
180
+ )
181
+
182
+ def selected_platform(self) -> Platform:
183
+ name = os.environ.get(self.platform_variable, "") if self.platform_variable else ""
184
+ return self.get_platform(name) if name else self.host_platform()
185
+
186
+ # --- staging -------------------------------------------------------------
187
+
188
+ def build_stage(self, platform: Platform, version: str) -> str:
189
+ """Stage the files of one wheel in upstream/; return its platform tag."""
190
+ log(f"{self.name} {version} for {platform.name}")
191
+ if os.name == "nt" and platform.os != "windows":
192
+ # The wheel takes each file's mode from the file system, and
193
+ # Windows has no executable bit to give the scripts.
194
+ raise ValueError(
195
+ f"build the {platform.name} wheel on Linux or macOS: on Windows its "
196
+ "executables would lose their executable bit"
197
+ )
198
+ staged = self.stage(platform, version)
199
+ if not staged.scripts:
200
+ raise ValueError(f"{self.name}: no executables for {platform.name}")
201
+ minimums: set[str] = set()
202
+ for script, data in staged.scripts.items():
203
+ try:
204
+ minimum = check_binary(data, platform.check)
205
+ except ValueError as exc:
206
+ raise ValueError(f"{script} for {platform.name}: {exc}") from None
207
+ if minimum:
208
+ minimums.add(minimum)
209
+ tag = macos_tag(platform.tag, minimums)
210
+
211
+ shutil.rmtree(self.stage_dir, ignore_errors=True)
212
+ for subdir, files in (
213
+ ("bin", staged.scripts),
214
+ ("data", staged.data),
215
+ ("", staged.licenses),
216
+ ):
217
+ for name, data in files.items():
218
+ if ".." in Path(name).parts or Path(name).is_absolute():
219
+ raise ValueError(f"unsafe path {name!r}")
220
+ path = self.stage_dir / subdir / name
221
+ path.parent.mkdir(parents=True, exist_ok=True)
222
+ path.write_bytes(data)
223
+ if subdir == "bin":
224
+ path.chmod(0o755)
225
+ manifest = {
226
+ "tag": tag,
227
+ "scripts": sorted(staged.scripts),
228
+ "data": sorted(staged.data),
229
+ }
230
+ (self.stage_dir / "wheel.json").write_text(json.dumps(manifest, indent=2))
231
+ return tag
232
+
233
+ # --- hatchling hooks ---------------------------------------------------
234
+
235
+ def hooks(self) -> tuple[Callable[[], type], Callable[[], type]]:
236
+ """The hatchling hooks, as ``get_metadata_hook, get_build_hook``.
237
+
238
+ hatchling is only imported when it asks for a hook, so
239
+ ``python hatch_build.py`` works without it.
240
+ """
241
+ return self._metadata_hook, self._build_hook
242
+
243
+ def _metadata_hook(self) -> type:
244
+ from hatchling.metadata.plugin.interface import MetadataHookInterface
245
+
246
+ recipe = self
247
+
248
+ class PrebuiltMetadataHook(MetadataHookInterface):
249
+ """Set the version and stage the files before hatchling reads
250
+ `license-files`."""
251
+
252
+ def update(self, metadata: dict) -> None:
253
+ version = recipe.wheel_version()
254
+ metadata["version"] = version
255
+ recipe.build_stage(recipe.selected_platform(), version)
256
+
257
+ return PrebuiltMetadataHook
258
+
259
+ def _build_hook(self) -> type:
260
+ from hatchling.builders.hooks.plugin.interface import BuildHookInterface
261
+
262
+ recipe = self
263
+
264
+ class PrebuiltBuildHook(BuildHookInterface):
265
+ """Put the staged files into the wheel."""
266
+
267
+ def initialize(self, version: str, build_data: dict) -> None:
268
+ if self.target_name != "wheel":
269
+ raise RuntimeError(f"{recipe.name} is published as wheels only")
270
+ manifest_file = recipe.stage_dir / "wheel.json"
271
+ if not manifest_file.is_file():
272
+ raise RuntimeError(f"{manifest_file} is missing; the metadata hook did not run")
273
+ manifest = json.loads(manifest_file.read_text())
274
+ build_data["pure_python"] = False
275
+ build_data["tag"] = f"py3-none-{manifest['tag']}"
276
+ for name in manifest["scripts"]:
277
+ build_data["shared_scripts"][str(recipe.stage_dir / "bin" / name)] = name
278
+ for name in manifest["data"]:
279
+ build_data["shared_data"][str(recipe.stage_dir / "data" / name)] = name
280
+
281
+ return PrebuiltBuildHook
282
+
283
+ # --- command line ------------------------------------------------------
284
+
285
+ def main(self, argv: list[str] | None = None) -> int:
286
+ """``python hatch_build.py platforms | <recipe command> [args]``."""
287
+ args = sys.argv[1:] if argv is None else argv
288
+ commands: dict[str, Callable[[list[str]], int]] = {
289
+ "platforms": self._print_platforms,
290
+ **self.commands(),
291
+ }
292
+ if not args or args[0] not in commands:
293
+ print(f"usage: python hatch_build.py {' | '.join(commands)}", file=sys.stderr)
294
+ return 2
295
+ return commands[args[0]](args[1:])
296
+
297
+ def _print_platforms(self, args: list[str]) -> int:
298
+ print("\n".join(p.name for p in self.platforms))
299
+ return 0
@@ -0,0 +1,139 @@
1
+ """Checking that a file is an executable for the expected platform."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import io
6
+ import struct
7
+ import tarfile
8
+ import zipfile
9
+
10
+ ELF_MACHINES = {"x86_64": 62, "aarch64": 183, "riscv64": 243, "s390x": 22, "ppc64le": 21}
11
+ MACHO_CPUS = {"x86_64": 0x01000007, "arm64": 0x0100000C}
12
+ PE_MACHINES = {"x86_64": 0x8664, "arm64": 0xAA64}
13
+
14
+
15
+ def check_binary(data: bytes, expected: str) -> str | None:
16
+ """Fail if data is not an executable of the expected kind.
17
+
18
+ expected is one of:
19
+
20
+ - ``elf-<arch>``: a static ELF executable (no program interpreter);
21
+ - ``elf-dynamic-<arch>``: any ELF executable;
22
+ - ``macho-<arch>``: a thin 64-bit Mach-O executable;
23
+ - ``macho-universal``: a universal Mach-O with x86_64 and arm64 slices;
24
+ - ``pe-<arch>``: a Windows PE executable.
25
+
26
+ Returns the minimum macOS version of a thin Mach-O binary, as "11_0".
27
+ """
28
+ kind, _, arch = expected.partition("-")
29
+ if kind == "elf":
30
+ static = not arch.startswith("dynamic-")
31
+ arch = arch.removeprefix("dynamic-")
32
+ if data[:4] != b"\x7fELF":
33
+ raise ValueError("not an ELF file")
34
+ endian = "<" if data[5] == 1 else ">"
35
+ machine = struct.unpack(endian + "H", data[18:20])[0]
36
+ if machine != ELF_MACHINES[arch]:
37
+ raise ValueError(f"ELF machine {machine}, expected {expected}")
38
+ if static and _elf_has_interpreter(data, endian):
39
+ raise ValueError("expected a static binary, found a program interpreter")
40
+ return None
41
+ if expected == "macho-universal":
42
+ if data[:4] != b"\xca\xfe\xba\xbe":
43
+ raise ValueError("not a universal Mach-O binary")
44
+ count = struct.unpack(">I", data[4:8])[0]
45
+ cpus = {struct.unpack(">I", data[8 + 20 * i : 12 + 20 * i])[0] for i in range(count)}
46
+ if cpus != set(MACHO_CPUS.values()):
47
+ raise ValueError(f"unexpected Mach-O slices {sorted(map(hex, cpus))}")
48
+ return None
49
+ if kind == "macho":
50
+ if data[:4] != b"\xcf\xfa\xed\xfe":
51
+ raise ValueError("not a 64-bit Mach-O binary")
52
+ if struct.unpack("<I", data[4:8])[0] != MACHO_CPUS[arch]:
53
+ raise ValueError(f"not an {arch} Mach-O binary")
54
+ ncmds = struct.unpack("<I", data[16:20])[0]
55
+ offset = 32
56
+ for _ in range(ncmds):
57
+ cmd, size = struct.unpack("<II", data[offset : offset + 8])
58
+ if cmd == 0x32: # LC_BUILD_VERSION: platform, minos, ...
59
+ minos = struct.unpack("<I", data[offset + 12 : offset + 16])[0]
60
+ return f"{minos >> 16}_{(minos >> 8) & 0xFF}"
61
+ if cmd == 0x24: # LC_VERSION_MIN_MACOSX: version, sdk
62
+ minos = struct.unpack("<I", data[offset + 8 : offset + 12])[0]
63
+ return f"{minos >> 16}_{(minos >> 8) & 0xFF}"
64
+ offset += size
65
+ raise ValueError("Mach-O binary declares no minimum macOS version")
66
+ if kind == "pe":
67
+ if data[:2] != b"MZ":
68
+ raise ValueError("not a PE file")
69
+ pe = struct.unpack("<I", data[0x3C:0x40])[0]
70
+ if (
71
+ data[pe : pe + 4] != b"PE\0\0"
72
+ or struct.unpack("<H", data[pe + 4 : pe + 6])[0] != PE_MACHINES[arch]
73
+ ):
74
+ raise ValueError(f"not an {arch} PE file")
75
+ return None
76
+ raise ValueError(f"unknown check {expected!r}")
77
+
78
+
79
+ def _elf_has_interpreter(data: bytes, endian: str) -> bool:
80
+ """Whether an ELF file has a PT_INTERP program header, i.e. needs a
81
+ dynamic loader."""
82
+ if data[4] == 2: # ELF64
83
+ phoff = struct.unpack(endian + "Q", data[0x20:0x28])[0]
84
+ phentsize, phnum = struct.unpack(endian + "HH", data[0x36:0x3A])
85
+ else: # ELF32
86
+ phoff = struct.unpack(endian + "I", data[0x1C:0x20])[0]
87
+ phentsize, phnum = struct.unpack(endian + "HH", data[0x2A:0x2E])
88
+ for i in range(phnum):
89
+ start = phoff + i * phentsize
90
+ if start + 4 > len(data):
91
+ raise ValueError("truncated ELF program headers")
92
+ if struct.unpack(endian + "I", data[start : start + 4])[0] == 3: # PT_INTERP
93
+ return True
94
+ return False
95
+
96
+
97
+ def macos_tag(template: str, minimums: set[str]) -> str:
98
+ """Fill {macos} in a platform tag with the newest of the binaries' minimums.
99
+
100
+ A wheel can only claim the newest minimum of all its binaries, and since
101
+ macOS 11 the minor version is not part of the tag.
102
+ """
103
+ if "{macos}" not in template:
104
+ return template
105
+ if not minimums:
106
+ raise ValueError(f"{template} needs the minimum macOS version of a binary")
107
+ newest = max(minimums, key=lambda v: tuple(map(int, v.split("_"))))
108
+ major = int(newest.split("_")[0])
109
+ return template.format(macos=f"{major}_0" if major >= 11 else newest)
110
+
111
+
112
+ def extract(data: bytes, kind: str, prefix: str = "") -> dict[str, bytes]:
113
+ """Return {path: content} of the files in a tar.gz or zip archive.
114
+
115
+ With a prefix, only the files under prefix/ are returned, with paths
116
+ relative to it. Paths that leave the archive (..) are refused.
117
+ """
118
+ start = f"{prefix}/" if prefix else ""
119
+ files: dict[str, bytes] = {}
120
+
121
+ def add(name: str, read) -> None:
122
+ if ".." in name.split("/") or name.startswith("/"):
123
+ raise ValueError(f"unsafe path {name!r} in the archive")
124
+ if name.startswith(start):
125
+ files[name[len(start) :]] = read()
126
+
127
+ if kind == "tar.gz":
128
+ with tarfile.open(fileobj=io.BytesIO(data), mode="r:gz") as tar:
129
+ for member in tar.getmembers():
130
+ if member.isfile():
131
+ add(member.name, lambda m=member: tar.extractfile(m).read()) # type: ignore[union-attr]
132
+ elif kind == "zip":
133
+ with zipfile.ZipFile(io.BytesIO(data)) as archive:
134
+ for info in archive.infolist():
135
+ if not info.is_dir():
136
+ add(info.filename, lambda i=info: archive.read(i))
137
+ else:
138
+ raise ValueError(f"unknown archive kind {kind!r}")
139
+ return files
@@ -0,0 +1,93 @@
1
+ """Downloading files and checking that they are the files we expect."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import hashlib
7
+ import re
8
+ import sys
9
+ import time
10
+ import urllib.request
11
+ from pathlib import Path
12
+
13
+ USER_AGENT = "hatch-prebuilt (https://github.com/cpp-linter/hatch-prebuilt)"
14
+
15
+
16
+ def log(msg: str) -> None:
17
+ print(msg, file=sys.stderr, flush=True)
18
+
19
+
20
+ def http_get(url: str, *, attempts: int = 4) -> bytes:
21
+ """Download url, retrying network errors with a growing pause."""
22
+ last_error: Exception | None = None
23
+ for attempt in range(attempts):
24
+ try:
25
+ request = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})
26
+ with urllib.request.urlopen(request, timeout=120) as resp:
27
+ return resp.read()
28
+ except OSError as exc: # URLError, timeouts, resets
29
+ last_error = exc
30
+ if attempt + 1 < attempts:
31
+ time.sleep(2 ** (attempt + 1))
32
+ raise RuntimeError(f"failed to download {url}: {last_error}")
33
+
34
+
35
+ def cached_download(url: str, path: Path) -> bytes:
36
+ """Download url to path once; later calls read path."""
37
+ if not path.is_file():
38
+ log(f"downloading {url}")
39
+ path.parent.mkdir(parents=True, exist_ok=True)
40
+ path.write_bytes(http_get(url))
41
+ return path.read_bytes()
42
+
43
+
44
+ def check_sha512(data: bytes, expected: str, label: str) -> None:
45
+ digest = hashlib.sha512(data).hexdigest()
46
+ if digest != expected.lower():
47
+ raise ValueError(f"{label}: SHA-512 {digest} does not match {expected}")
48
+ log(f" SHA-512 OK: {label}")
49
+
50
+
51
+ def verify_minisign(data: bytes, file_name: str, minisig: bytes, public_key: str) -> str:
52
+ """Check a minisign signature of data; return its trusted comment.
53
+
54
+ Needs the `cryptography` package (the `minisign` extra).
55
+ """
56
+ from cryptography.exceptions import InvalidSignature
57
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
58
+
59
+ key = base64.b64decode(public_key)
60
+ if len(key) != 42 or key[:2] != b"Ed":
61
+ raise ValueError("bad minisign public key")
62
+ key_id, verifier = key[2:10], Ed25519PublicKey.from_public_bytes(key[10:])
63
+
64
+ lines = minisig.decode("utf-8").splitlines()
65
+ if len(lines) < 4 or not lines[2].startswith("trusted comment: "):
66
+ raise ValueError(f"{file_name}: malformed .minisig file")
67
+ sig = base64.b64decode(lines[1])
68
+ if len(sig) != 74:
69
+ raise ValueError(f"{file_name}: malformed signature")
70
+ algorithm, sig_key_id, signature = sig[:2], sig[2:10], sig[10:]
71
+ if sig_key_id != key_id:
72
+ raise ValueError(f"{file_name}: signed with an unknown key")
73
+ if algorithm == b"ED": # prehashed, the minisign default since 0.11
74
+ message = hashlib.blake2b(data, digest_size=64).digest()
75
+ elif algorithm == b"Ed":
76
+ message = data
77
+ else:
78
+ raise ValueError(f"{file_name}: unknown signature algorithm")
79
+
80
+ trusted_comment = lines[2][len("trusted comment: ") :]
81
+ global_signature = base64.b64decode(lines[3])
82
+ try:
83
+ verifier.verify(signature, message)
84
+ verifier.verify(global_signature, signature + trusted_comment.encode())
85
+ except InvalidSignature:
86
+ raise ValueError(f"{file_name}: BAD SIGNATURE") from None
87
+
88
+ # The trusted comment names the signed file; make sure it was not swapped.
89
+ match = re.search(r"(?:^|\t)file:([^\t]+)", trusted_comment)
90
+ if match and match.group(1) != file_name:
91
+ raise ValueError(f"{file_name}: signature is for {match.group(1)!r}, not this file")
92
+ log(f" signature OK: {file_name}")
93
+ return trusted_comment
@@ -0,0 +1,217 @@
1
+ """Recipes for tools from the cpp-linter/clang-tools-static-binaries releases.
2
+
3
+ sources.json in the wheel repository pins the SHA-512 of every file the
4
+ repository can package; the build refuses a download that does not match.
5
+ ``python hatch_build.py update`` adds the newest release of every LLVM major
6
+ version from the static binaries' index.json to it, after checking the index
7
+ against each release's SHA512SUMS. The releases are immutable, so entries
8
+ already in sources.json never change.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ from collections.abc import Sequence
15
+ from typing import ClassVar
16
+
17
+ from . import Platform, Recipe, Staged
18
+ from .binary import extract
19
+ from .download import cached_download, check_sha512, http_get
20
+
21
+ REPOSITORY = "cpp-linter/clang-tools-static-binaries"
22
+ DOWNLOAD_URL = f"https://github.com/{REPOSITORY}/releases/download/{{tag}}/{{name}}"
23
+ INDEX_URL = "https://cpp-linter.github.io/clang-tools-static-binaries/index.json"
24
+
25
+ # The Linux binaries are fully static, so one wheel serves glibc and musl
26
+ # distributions alike. The macOS tag carries the minimum macOS version that
27
+ # the binaries declare.
28
+ PLATFORMS = [
29
+ Platform(
30
+ "linux-amd64",
31
+ "manylinux_2_17_x86_64.manylinux2014_x86_64.musllinux_1_1_x86_64",
32
+ "elf-x86_64",
33
+ "linux",
34
+ "x86_64",
35
+ ),
36
+ Platform(
37
+ "linux-arm64",
38
+ "manylinux_2_17_aarch64.manylinux2014_aarch64.musllinux_1_1_aarch64",
39
+ "elf-aarch64",
40
+ "linux",
41
+ "arm64",
42
+ ),
43
+ Platform("macos-amd64", "macosx_{macos}_x86_64", "macho-x86_64", "macos", "x86_64"),
44
+ Platform("macos-arm64", "macosx_{macos}_arm64", "macho-arm64", "macos", "arm64"),
45
+ Platform("windows-amd64", "win_amd64", "pe-x86_64", "windows", "x86_64"),
46
+ Platform("windows-arm64", "win_arm64", "pe-arm64", "windows", "arm64"),
47
+ ]
48
+
49
+
50
+ class StaticBinariesRecipe(Recipe):
51
+ """Package some tools of one LLVM version from the static binaries.
52
+
53
+ The wheel version is the LLVM version, optionally with a packaging
54
+ revision (23.1.6.1). Set ``tools`` (the first one names the package) and,
55
+ for clangd, ``resource_headers`` to add clang's builtin headers under
56
+ lib/clang/<major>/include, where clangd looks for them.
57
+ """
58
+
59
+ tools: ClassVar[Sequence[str]] = ()
60
+ resource_headers: bool = False
61
+ min_major: int = 12
62
+ """The oldest LLVM major version that ``update`` adds to sources.json."""
63
+ license_file = "LICENSE.TXT"
64
+ version_file = "llvm_version.txt"
65
+ version_variable = "LLVM_VERSION"
66
+ platform_variable = "LLVM_PLATFORM"
67
+ version_pattern = r"\d+\.\d+\.\d+(\.[1-9]\d*)?"
68
+ platforms = PLATFORMS
69
+
70
+ @property
71
+ def sources_file(self):
72
+ return self.root / "sources.json"
73
+
74
+ def upstream_version(self, version: str) -> str:
75
+ """The LLVM version inside a wheel version: 23.1.6.1 -> 23.1.6."""
76
+ return ".".join(version.split(".")[:3])
77
+
78
+ def load_sources(self) -> dict:
79
+ return json.loads(self.sources_file.read_text(encoding="utf-8"))
80
+
81
+ def download(self, tag: str, name: str, sha512: str) -> bytes:
82
+ path = self.cache / tag / name
83
+ data = cached_download(DOWNLOAD_URL.format(tag=tag, name=name), path)
84
+ try:
85
+ check_sha512(data, sha512, f"{tag}/{name}")
86
+ except ValueError:
87
+ path.unlink()
88
+ raise
89
+ return data
90
+
91
+ def stage(self, platform: Platform, version: str) -> Staged:
92
+ llvm = self.upstream_version(version)
93
+ versions = self.load_sources()["versions"]
94
+ if llvm not in versions:
95
+ raise ValueError(
96
+ f"LLVM {llvm} is not in sources.json; run `python hatch_build.py update`"
97
+ f" (known: {', '.join(versions)})"
98
+ )
99
+ entry = versions[llvm]
100
+ extras = ["license"] + (["resource_headers"] if self.resource_headers else [])
101
+ if not self._complete(entry, extras):
102
+ raise ValueError(
103
+ f"sources.json does not pin every file of {', '.join(self.tools)} for LLVM"
104
+ f" {llvm}; run `python hatch_build.py update`"
105
+ )
106
+ tag, pins = entry["tag"], entry["files"][platform.name]
107
+ major = llvm.split(".")[0]
108
+ scripts = {
109
+ f"{tool}{platform.exe}": self.download(
110
+ tag, f"{tool}-{major}_{platform.name}{platform.exe}", pins[tool]
111
+ )
112
+ for tool in self.tools
113
+ }
114
+ licenses = {self.license_file: self.download(tag, self.license_file, entry["license"])}
115
+ data: dict[str, bytes] = {}
116
+ if self.resource_headers:
117
+ archive = self.download(
118
+ tag, f"clang-resource-headers-{major}.tar.gz", entry["resource_headers"]
119
+ )
120
+ prefix = f"lib/clang/{major}/include/"
121
+ for name, content in extract(archive, "tar.gz").items():
122
+ if not name.startswith(prefix):
123
+ raise ValueError(f"unexpected file {name} in the headers")
124
+ data[name] = content
125
+ if not data:
126
+ raise ValueError("the headers archive is empty")
127
+ return Staged(scripts=scripts, licenses=licenses, data=data)
128
+
129
+ def update_sources(self) -> list[str]:
130
+ """Add the newest release of each LLVM major in index.json to sources.json."""
131
+ index = json.loads(http_get(INDEX_URL))
132
+ sources = self.load_sources() if self.sources_file.is_file() else {"versions": {}}
133
+ extras = ["license"] + (["resource_headers"] if self.resource_headers else [])
134
+ added = []
135
+ for major, release in index["versions"].items():
136
+ existing = sources["versions"].get(release["version"])
137
+ if int(major) < self.min_major or (existing and self._complete(existing, extras)):
138
+ continue
139
+ if not all(tool in release["tools"] for tool in self.tools):
140
+ continue # built before the static binaries had these tools
141
+ sums = {}
142
+ for line in http_get(release["sha512sums_url"]).decode().splitlines():
143
+ if line.strip():
144
+ digest, name = line.split()
145
+ sums[name.lstrip("*")] = digest.lower()
146
+ files: dict[str, dict[str, str]] = {}
147
+ for platform in self.platforms:
148
+ files[platform.name] = {}
149
+ for tool in self.tools:
150
+ item = release["tools"][tool][platform.name]
151
+ if sums.get(item["name"]) != item["sha512"]:
152
+ raise ValueError(
153
+ f"{release['tag']}: SHA512SUMS disagrees on {item['name']}"
154
+ )
155
+ files[platform.name][tool] = item["sha512"]
156
+ entry = {"tag": release["tag"]}
157
+ for key in extras:
158
+ if sums.get(release[key]["name"]) != release[key]["sha512"]:
159
+ raise ValueError(
160
+ f"{release['tag']}: SHA512SUMS disagrees on {release[key]['name']}"
161
+ )
162
+ entry[key] = release[key]["sha512"]
163
+ entry["files"] = files
164
+ if existing:
165
+ # A tool was added to the recipe: keep the pins already
166
+ # recorded, which must not change.
167
+ for name, pin in _pins(existing):
168
+ if dict(_pins(entry)).get(name, pin) != pin:
169
+ raise ValueError(f"{release['tag']}: the SHA-512 of {name} changed")
170
+ sources["versions"][release["version"]] = entry
171
+ added.append(release["version"])
172
+
173
+ def key(version: str) -> tuple[int, ...]:
174
+ return tuple(int(part) for part in version.split("."))
175
+
176
+ sources = {
177
+ "comment": (
178
+ "SHA-512 of the files packaged from the cpp-linter/clang-tools-static-"
179
+ "binaries releases, from its index.json. Written by "
180
+ "`python hatch_build.py update`."
181
+ ),
182
+ "tools": list(self.tools),
183
+ "versions": dict(
184
+ sorted(sources["versions"].items(), key=lambda kv: key(kv[0]), reverse=True)
185
+ ),
186
+ }
187
+ self.sources_file.write_text(json.dumps(sources, indent=2) + "\n", encoding="utf-8")
188
+ return added
189
+
190
+ def _complete(self, entry: dict, extras: list[str]) -> bool:
191
+ """Whether a sources.json entry pins every file the recipe packages."""
192
+ return all(key in entry for key in extras) and all(
193
+ tool in entry["files"].get(platform.name, {})
194
+ for platform in self.platforms
195
+ for tool in self.tools
196
+ )
197
+
198
+ def commands(self):
199
+ def versions(args: list[str]) -> int:
200
+ print("\n".join(self.load_sources()["versions"]))
201
+ return 0
202
+
203
+ def update(args: list[str]) -> int:
204
+ print("\n".join(self.update_sources()))
205
+ return 0
206
+
207
+ return {"versions": versions, "update": update}
208
+
209
+
210
+ def _pins(entry: dict):
211
+ """(file, SHA-512) of every pin in a sources.json entry."""
212
+ for key in ("license", "resource_headers"):
213
+ if key in entry:
214
+ yield key, entry[key]
215
+ for platform, tools in entry["files"].items():
216
+ for tool, pin in tools.items():
217
+ yield f"{tool} for {platform}", pin
@@ -0,0 +1,137 @@
1
+ Metadata-Version: 2.5
2
+ Name: hatch-prebuilt
3
+ Version: 0.1.0
4
+ Summary: Build Python wheels that install prebuilt executables unchanged, with hatchling
5
+ Project-URL: Source, https://github.com/cpp-linter/hatch-prebuilt
6
+ Project-URL: Issues, https://github.com/cpp-linter/hatch-prebuilt/issues
7
+ Author-email: Xianpeng Shen <xianpeng.shen@gmail.com>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: binary,hatch,hatchling,packaging,wheel
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Framework :: Hatch
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Topic :: Software Development :: Build Tools
16
+ Classifier: Topic :: System :: Archiving :: Packaging
17
+ Requires-Python: >=3.9
18
+ Requires-Dist: hatchling>=1.27
19
+ Provides-Extra: minisign
20
+ Requires-Dist: cryptography>=42; extra == 'minisign'
21
+ Description-Content-Type: text/markdown
22
+
23
+ # hatch-prebuilt
24
+
25
+ [![PyPI](https://img.shields.io/pypi/v/hatch-prebuilt?labelColor=454a63&color=007ec6)](https://pypi.org/project/hatch-prebuilt/)
26
+ [![ci](https://img.shields.io/github/actions/workflow/status/cpp-linter/hatch-prebuilt/test.yml?branch=main&label=ci&labelColor=454a63)](https://github.com/cpp-linter/hatch-prebuilt/actions/workflows/test.yml)
27
+ [![part of cpp-linter](https://img.shields.io/badge/part%20of-cpp--linter-ffc20a?labelColor=454a63)](https://cpp-linter.github.io/)
28
+
29
+ Build Python wheels that install prebuilt executables unchanged, with
30
+ [hatchling](https://hatch.pypa.io/latest/). `pip install` or `uv pip install` puts the executable
31
+ straight into the environment's `bin/` (`Scripts\` on Windows), with no Python wrapper in
32
+ between, so starting it costs nothing extra.
33
+
34
+ The [cpp-linter](https://github.com/cpp-linter) wheel repositories use it:
35
+ [ccache-wheel](https://github.com/cpp-linter/ccache-wheel) (`ccache-bin`),
36
+ [llvm-cov-wheel](https://github.com/cpp-linter/llvm-cov-wheel) (`llvm-cov`) and
37
+ [clangd-wheel](https://github.com/cpp-linter/clangd-wheel) (`clangd-bin`).
38
+
39
+ ## What it does
40
+
41
+ A wheel repository describes its tool in `hatch_build.py`: which platforms it has, and how to
42
+ download and verify the files of one version for one platform. hatch-prebuilt does the rest:
43
+
44
+ - picks the version (from a version file, or an environment variable so CI can build older
45
+ versions) and the platform (from an environment variable, or the build machine);
46
+ - checks that every executable is a binary for that platform: ELF machine and static linking,
47
+ Mach-O architecture or universal slices, PE machine;
48
+ - works out the wheel tag, including the minimum macOS version the binaries declare;
49
+ - stages the license files where `license-files` finds them, and gives hatchling the executables
50
+ as shared scripts and any other files (man pages, headers) as shared data.
51
+
52
+ It also has the download helpers the recipes share: retrying downloads, a download cache, SHA-512
53
+ pins, minisign signatures (`hatch-prebuilt[minisign]`) and archive extraction.
54
+
55
+ ## A recipe
56
+
57
+ ```python
58
+ # hatch_build.py
59
+ from pathlib import Path
60
+
61
+ from hatch_prebuilt import Platform, Recipe, Staged, cached_download, check_sha512
62
+
63
+ URL = "https://example.com/mytool-{version}-{platform}{exe}"
64
+ SHA512 = {...}
65
+
66
+
67
+ class MyTool(Recipe):
68
+ name = "mytool"
69
+ version_file = "mytool_version.txt"
70
+ platform_variable = "MYTOOL_PLATFORM"
71
+ platforms = (
72
+ Platform(
73
+ "linux-x86_64",
74
+ "manylinux_2_17_x86_64.musllinux_1_1_x86_64",
75
+ "elf-x86_64",
76
+ "linux",
77
+ "x86_64",
78
+ ),
79
+ Platform("macos-arm64", "macosx_{macos}_arm64", "macho-arm64", "macos", "arm64"),
80
+ Platform("windows-x86_64", "win_amd64", "pe-x86_64", "windows", "x86_64"),
81
+ )
82
+
83
+ def stage(self, platform, version):
84
+ url = URL.format(version=version, platform=platform.name, exe=platform.exe)
85
+ binary = cached_download(url, self.cache / Path(url).name)
86
+ check_sha512(binary, SHA512[platform.name], url)
87
+ return Staged(scripts={f"mytool{platform.exe}": binary}, licenses={"LICENSE": ...})
88
+
89
+
90
+ RECIPE = MyTool(Path(__file__).parent)
91
+ get_metadata_hook, get_build_hook = RECIPE.hooks()
92
+
93
+ if __name__ == "__main__":
94
+ raise SystemExit(RECIPE.main())
95
+ ```
96
+
97
+ ```toml
98
+ # pyproject.toml
99
+ [build-system]
100
+ requires = ["hatchling>=1.27", "hatch-prebuilt>=0.1,<1"]
101
+ build-backend = "hatchling.build"
102
+
103
+ [project]
104
+ name = "mytool-bin"
105
+ dynamic = ["version"]
106
+ license-files = ["upstream/LICENSE"]
107
+
108
+ [tool.hatch.metadata.hooks.custom]
109
+
110
+ [tool.hatch.build.targets.wheel]
111
+ bypass-selection = true
112
+
113
+ [tool.hatch.build.targets.wheel.hooks.custom]
114
+ ```
115
+
116
+ Then `python hatch_build.py platforms` lists the platforms, and
117
+ `MYTOOL_PLATFORM=<platform> python -m build --wheel` builds one wheel, for any platform, on
118
+ Linux or macOS (Windows cannot give the executables their executable bit). The shared
119
+ [`binary-wheels.yml`](https://github.com/cpp-linter/.github/blob/main/.github/workflows/binary-wheels.yml)
120
+ workflow builds and tests all of them, and
121
+ [`templates/binary-wheel/`](https://github.com/cpp-linter/.github/tree/main/templates/binary-wheel)
122
+ is a complete wheel repository to start from.
123
+
124
+ Tools from the
125
+ [clang-tools-static-binaries](https://github.com/cpp-linter/clang-tools-static-binaries)
126
+ releases need even less: `hatch_prebuilt.static_binaries.StaticBinariesRecipe` knows the
127
+ platforms, the file names and the SHA-512 pins in `sources.json`, so the recipe only names the
128
+ tools.
129
+
130
+ ## Contributing
131
+
132
+ See the [contributing guide](https://github.com/cpp-linter/.github/blob/main/CONTRIBUTING.md).
133
+ `uv run --group test pytest` runs the tests.
134
+
135
+ ## License
136
+
137
+ [MIT](LICENSE)
@@ -0,0 +1,8 @@
1
+ hatch_prebuilt/__init__.py,sha256=bokQn5fO3Z-ulVp5r2SOwX5WbsdwLN_CogXYQaRUa7k,11823
2
+ hatch_prebuilt/binary.py,sha256=T4EgonpHg4EaKPEIzikAhg2_dnCvTkfThn3tqCq90D0,5971
3
+ hatch_prebuilt/download.py,sha256=5_6JMQVkag2ALDjI7JO71JZMqHO-e0tl9oLCOBDNYII,3603
4
+ hatch_prebuilt/static_binaries.py,sha256=b8X0v_FjFYFF8If3CurSzNcqa-zLEWeMswOU9YX67oE,9264
5
+ hatch_prebuilt-0.1.0.dist-info/METADATA,sha256=vWe24oOz_zGZ_xexugs-dq7WPOquGyfijtNH8p2Knto,5573
6
+ hatch_prebuilt-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
7
+ hatch_prebuilt-0.1.0.dist-info/licenses/LICENSE,sha256=v6uyi6BtgoBCqdHk647_glQsuHkJQ_SuIRwkKdqTlbw,1067
8
+ hatch_prebuilt-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 cpp-linter
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.