hatch-native 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.
- hatch_native/__init__.py +9 -0
- hatch_native/config.py +137 -0
- hatch_native/external.py +114 -0
- hatch_native/headers.py +55 -0
- hatch_native/manifest.py +15 -0
- hatch_native/naming.py +16 -0
- hatch_native/symbols.py +172 -0
- hatch_native/tests/test_all.py +5 -0
- hatch_native/tests/test_shared.py +129 -0
- hatch_native/tests/test_symbols.py +31 -0
- hatch_native/validation.py +38 -0
- hatch_native-0.1.0.dist-info/METADATA +75 -0
- hatch_native-0.1.0.dist-info/RECORD +15 -0
- hatch_native-0.1.0.dist-info/WHEEL +4 -0
- hatch_native-0.1.0.dist-info/licenses/LICENSE +201 -0
hatch_native/__init__.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
|
2
|
+
|
|
3
|
+
from .config import ExternalLibraryConfig, LibraryValidationConfig, ValidationCommandConfig
|
|
4
|
+
from .external import LIBRARY_SOURCES, ExternalLibrary, LibrarySource, pkg_config_variable, resolve_external_library, resolve_library_source
|
|
5
|
+
from .headers import check_headers, header_symbols, prefixed_header_symbols
|
|
6
|
+
from .manifest import MANIFEST_VERSION, write_artifact_manifest
|
|
7
|
+
from .naming import shared_library_name
|
|
8
|
+
from .symbols import exported_symbols
|
|
9
|
+
from .validation import check_exports, run_validation_command
|
hatch_native/config.py
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
from pydantic import AliasChoices, BaseModel, ConfigDict, Field, field_validator, model_validator
|
|
7
|
+
|
|
8
|
+
__all__ = ("ExternalLibraryConfig", "LibraryValidationConfig", "ValidationCommandConfig")
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class ValidationCommandConfig(BaseModel):
|
|
12
|
+
"""A project-specific command used to validate a built artifact."""
|
|
13
|
+
|
|
14
|
+
model_config = ConfigDict(extra="ignore", populate_by_name=True)
|
|
15
|
+
|
|
16
|
+
command: list[str] = Field(description="Validation command argv list.")
|
|
17
|
+
working_directory: Path | None = Field(default=None, alias="working-directory", description="Validation command working directory.")
|
|
18
|
+
env: dict[str, str] = Field(default_factory=dict, description="Additional environment variables for this validation command.")
|
|
19
|
+
|
|
20
|
+
@field_validator("command", mode="before")
|
|
21
|
+
@classmethod
|
|
22
|
+
def validate_command(cls, values: Any) -> list[str]:
|
|
23
|
+
if isinstance(values, str):
|
|
24
|
+
raise TypeError("Validation command must be an argv list, not a shell string.")
|
|
25
|
+
return [str(value) for value in values]
|
|
26
|
+
|
|
27
|
+
@field_validator("working_directory", mode="before")
|
|
28
|
+
@classmethod
|
|
29
|
+
def validate_working_directory(cls, path: Path | None) -> Path | None:
|
|
30
|
+
if path is None:
|
|
31
|
+
return None
|
|
32
|
+
if not isinstance(path, Path):
|
|
33
|
+
path = Path(path)
|
|
34
|
+
return path
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class LibraryValidationConfig(BaseModel):
|
|
38
|
+
"""Header and export validation fields, named the same in every hatch native plugin.
|
|
39
|
+
|
|
40
|
+
Each field accepts its kebab-case name in pyproject.toml and its
|
|
41
|
+
snake_case name in Python.
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
expected_symbols: list[str] = Field(
|
|
45
|
+
default_factory=list,
|
|
46
|
+
validation_alias=AliasChoices("expected-symbols", "expected_symbols"),
|
|
47
|
+
description="Exported symbols expected in a copied library.",
|
|
48
|
+
)
|
|
49
|
+
header_symbol_prefix: str | None = Field(
|
|
50
|
+
default=None,
|
|
51
|
+
validation_alias=AliasChoices("header-symbol-prefix", "header_symbol_prefix"),
|
|
52
|
+
description="Expect every function in expected-headers whose name starts with this prefix to be exported.",
|
|
53
|
+
)
|
|
54
|
+
expected_headers: list[Path] = Field(
|
|
55
|
+
default_factory=list,
|
|
56
|
+
validation_alias=AliasChoices("expected-headers", "expected_headers"),
|
|
57
|
+
description="Header files expected to exist after build.",
|
|
58
|
+
)
|
|
59
|
+
expected_abi_strings: list[str] = Field(
|
|
60
|
+
default_factory=list,
|
|
61
|
+
validation_alias=AliasChoices("expected-abi-strings", "expected_abi_strings"),
|
|
62
|
+
description="ABI version strings or macros expected in the configured headers.",
|
|
63
|
+
)
|
|
64
|
+
validate_artifact: bool = Field(
|
|
65
|
+
default=False,
|
|
66
|
+
validation_alias=AliasChoices("validate", "validate_artifact"),
|
|
67
|
+
description="Load the copied library with ctypes.CDLL after copy. Requires a library built for the host.",
|
|
68
|
+
)
|
|
69
|
+
validation_commands: list[ValidationCommandConfig] = Field(
|
|
70
|
+
default_factory=list,
|
|
71
|
+
validation_alias=AliasChoices("validation-commands", "validation_commands"),
|
|
72
|
+
description="Project-specific validation commands to run after artifact copy.",
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
@field_validator("expected_symbols", "expected_abi_strings", mode="before")
|
|
76
|
+
@classmethod
|
|
77
|
+
def validate_validation_strings(cls, values: Any) -> list[str]:
|
|
78
|
+
if values is None:
|
|
79
|
+
return []
|
|
80
|
+
if isinstance(values, str):
|
|
81
|
+
return [values]
|
|
82
|
+
return [str(value) for value in values]
|
|
83
|
+
|
|
84
|
+
@field_validator("expected_headers", mode="before")
|
|
85
|
+
@classmethod
|
|
86
|
+
def validate_expected_headers(cls, values: Any) -> list[Path]:
|
|
87
|
+
if values is None:
|
|
88
|
+
return []
|
|
89
|
+
if isinstance(values, (str, Path)):
|
|
90
|
+
values = [values]
|
|
91
|
+
return [value if isinstance(value, Path) else Path(value) for value in values]
|
|
92
|
+
|
|
93
|
+
@field_validator("validation_commands", mode="before")
|
|
94
|
+
@classmethod
|
|
95
|
+
def validate_validation_commands(cls, values: Any) -> list[Any]:
|
|
96
|
+
if values is None:
|
|
97
|
+
return []
|
|
98
|
+
if isinstance(values, dict):
|
|
99
|
+
return [values]
|
|
100
|
+
if isinstance(values, list) and values and all(not isinstance(value, dict) for value in values):
|
|
101
|
+
return [{"command": values}]
|
|
102
|
+
return list(values)
|
|
103
|
+
|
|
104
|
+
@model_validator(mode="after")
|
|
105
|
+
def validate_header_symbol_prefix(self):
|
|
106
|
+
if self.header_symbol_prefix is not None and not self.expected_headers:
|
|
107
|
+
raise ValueError(f"Artifact '{getattr(self, 'name', None)}' must set expected-headers when using header-symbol-prefix.")
|
|
108
|
+
return self
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
class ExternalLibraryConfig(BaseModel):
|
|
112
|
+
"""Where to find a prebuilt library when it is not built by this project."""
|
|
113
|
+
|
|
114
|
+
pkg_config: str | None = Field(
|
|
115
|
+
default=None,
|
|
116
|
+
validation_alias=AliasChoices("pkg-config", "pkg_config"),
|
|
117
|
+
description="pkg-config module locating this library in external mode.",
|
|
118
|
+
)
|
|
119
|
+
library_root: Path | None = Field(
|
|
120
|
+
default=None,
|
|
121
|
+
validation_alias=AliasChoices("library-root", "library_root"),
|
|
122
|
+
description="Prefix with lib/ and include/ for this library in external mode.",
|
|
123
|
+
)
|
|
124
|
+
python_package: str | None = Field(
|
|
125
|
+
default=None,
|
|
126
|
+
validation_alias=AliasChoices("python-package", "python_package"),
|
|
127
|
+
description="Installed Python package shipping this library under lib/ and include/; linked from there instead of built.",
|
|
128
|
+
)
|
|
129
|
+
|
|
130
|
+
@field_validator("library_root", mode="before")
|
|
131
|
+
@classmethod
|
|
132
|
+
def validate_library_root(cls, path: Path | None) -> Path | None:
|
|
133
|
+
if path is None:
|
|
134
|
+
return None
|
|
135
|
+
if not isinstance(path, Path):
|
|
136
|
+
path = Path(path)
|
|
137
|
+
return path
|
hatch_native/external.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from importlib.util import find_spec
|
|
5
|
+
from os import environ
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from shlex import join as shell_join
|
|
8
|
+
from subprocess import run
|
|
9
|
+
from typing import Literal
|
|
10
|
+
|
|
11
|
+
from .naming import shared_library_name
|
|
12
|
+
|
|
13
|
+
__all__ = (
|
|
14
|
+
"LIBRARY_SOURCES",
|
|
15
|
+
"ExternalLibrary",
|
|
16
|
+
"LibrarySource",
|
|
17
|
+
"pkg_config_variable",
|
|
18
|
+
"resolve_external_library",
|
|
19
|
+
"resolve_library_source",
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
LibrarySource = Literal["bundled", "external", "static", "direct"]
|
|
23
|
+
LIBRARY_SOURCES: tuple[str, ...] = ("bundled", "external", "static", "direct")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass(frozen=True)
|
|
27
|
+
class ExternalLibrary:
|
|
28
|
+
"""A prebuilt C ABI library resolved outside the build."""
|
|
29
|
+
|
|
30
|
+
name: str
|
|
31
|
+
library: Path
|
|
32
|
+
library_dir: Path
|
|
33
|
+
include_dir: Path | None
|
|
34
|
+
link_name: str
|
|
35
|
+
package: str | None = None
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def resolve_library_source(configured: str, *, env_var: str) -> str:
|
|
39
|
+
"""Return `env_var` if set, else `configured`, rejecting anything but the four library-source modes."""
|
|
40
|
+
value = environ.get(env_var) or configured
|
|
41
|
+
if value not in LIBRARY_SOURCES:
|
|
42
|
+
raise ValueError(f"Unsupported {env_var}: {value}")
|
|
43
|
+
return value
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def pkg_config_variable(module: str, variable: str, *, label: str) -> Path:
|
|
47
|
+
"""Read one pkg-config variable, such as libdir or includedir, for `module`."""
|
|
48
|
+
command = ["pkg-config", f"--variable={variable}", module]
|
|
49
|
+
try:
|
|
50
|
+
completed = run(command, capture_output=True, text=True, check=False)
|
|
51
|
+
except FileNotFoundError as error:
|
|
52
|
+
raise RuntimeError(f"Artifact '{label}' needs pkg-config on PATH to resolve '{module}'.") from error
|
|
53
|
+
if completed.returncode != 0 or not completed.stdout.strip():
|
|
54
|
+
raise RuntimeError(f"Artifact '{label}' pkg-config lookup failed: {shell_join(command)}: {completed.stderr.strip()}")
|
|
55
|
+
return Path(completed.stdout.strip())
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def resolve_external_library(
|
|
59
|
+
name: str,
|
|
60
|
+
*,
|
|
61
|
+
label: str,
|
|
62
|
+
platform: str,
|
|
63
|
+
root_env_var: str,
|
|
64
|
+
root: Path | None = None,
|
|
65
|
+
package: str | None = None,
|
|
66
|
+
pkg_config: str | None = None,
|
|
67
|
+
) -> ExternalLibrary:
|
|
68
|
+
"""Locate a prebuilt library and its headers.
|
|
69
|
+
|
|
70
|
+
Lookup order: an explicit `root` prefix, an installed Python `package`
|
|
71
|
+
shipping `lib/` and `include/`, a `pkg_config` module, then `$PREFIX` or
|
|
72
|
+
`$CONDA_PREFIX` (with `Library/` on Windows). `root_env_var` only names the
|
|
73
|
+
caller's override in the error message.
|
|
74
|
+
"""
|
|
75
|
+
if root is not None:
|
|
76
|
+
library_dir, include_dir = root / "lib", root / "include"
|
|
77
|
+
elif package:
|
|
78
|
+
spec = find_spec(package)
|
|
79
|
+
if spec is None or not spec.submodule_search_locations:
|
|
80
|
+
raise ValueError(f"Artifact '{label}' package '{package}' is not installed in the build environment.")
|
|
81
|
+
prefix = Path(next(iter(spec.submodule_search_locations)))
|
|
82
|
+
library_dir, include_dir = prefix / "lib", prefix / "include"
|
|
83
|
+
elif pkg_config:
|
|
84
|
+
library_dir = pkg_config_variable(pkg_config, "libdir", label=label)
|
|
85
|
+
include_dir = pkg_config_variable(pkg_config, "includedir", label=label)
|
|
86
|
+
else:
|
|
87
|
+
conda_prefix = environ.get("PREFIX") or environ.get("CONDA_PREFIX")
|
|
88
|
+
if not conda_prefix:
|
|
89
|
+
raise ValueError(f"Artifact '{label}' is external but has no library-root, pkg-config, {root_env_var}, PREFIX, or CONDA_PREFIX.")
|
|
90
|
+
prefix = Path(conda_prefix) / "Library" if platform == "win32" else Path(conda_prefix)
|
|
91
|
+
library_dir, include_dir = prefix / "lib", prefix / "include"
|
|
92
|
+
|
|
93
|
+
shared_library = shared_library_name(name, platform=platform)
|
|
94
|
+
if platform == "win32":
|
|
95
|
+
candidates = [library_dir.parent / "bin" / shared_library, library_dir / shared_library]
|
|
96
|
+
link_name = name if (library_dir / f"{name}.lib").is_file() else f"{name}.dll"
|
|
97
|
+
elif platform == "darwin":
|
|
98
|
+
candidates = [library_dir / shared_library, *sorted(library_dir.glob(f"lib{name}.*.dylib"))]
|
|
99
|
+
link_name = name
|
|
100
|
+
else:
|
|
101
|
+
candidates = [library_dir / shared_library, *sorted(library_dir.glob(f"{shared_library}.*"))]
|
|
102
|
+
link_name = name
|
|
103
|
+
library = next((candidate for candidate in candidates if candidate.is_file()), None)
|
|
104
|
+
if library is None:
|
|
105
|
+
searched = ", ".join(str(candidate.parent) for candidate in candidates[:2])
|
|
106
|
+
raise FileNotFoundError(f"Artifact '{label}' external library '{shared_library}' was not found under {searched}.")
|
|
107
|
+
return ExternalLibrary(
|
|
108
|
+
name=name,
|
|
109
|
+
library=library,
|
|
110
|
+
library_dir=library_dir,
|
|
111
|
+
include_dir=include_dir if include_dir.is_dir() else None,
|
|
112
|
+
link_name=link_name,
|
|
113
|
+
package=package,
|
|
114
|
+
)
|
hatch_native/headers.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from re import DOTALL, MULTILINE, escape, findall, sub
|
|
5
|
+
|
|
6
|
+
__all__ = ("check_headers", "header_symbols", "prefixed_header_symbols")
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def header_symbols(text: str, prefix: str) -> list[str]:
|
|
10
|
+
"""Functions declared in a C header whose names start with `prefix`.
|
|
11
|
+
|
|
12
|
+
Comments, preprocessor lines, `static inline` definitions, and function
|
|
13
|
+
pointer declarators such as `prefix_status (*open)(...)` are skipped, since
|
|
14
|
+
none of them is exported by the library. Declarations are found with
|
|
15
|
+
regular expressions rather than a C parser, which works for a hand-written
|
|
16
|
+
or generated ABI header.
|
|
17
|
+
"""
|
|
18
|
+
text = sub(r"/\*.*?\*/", " ", text, flags=DOTALL)
|
|
19
|
+
text = sub(r"//[^\n]*", " ", text)
|
|
20
|
+
text = sub(r"^\s*#.*?(?<!\\)$", " ", text, flags=MULTILINE | DOTALL)
|
|
21
|
+
text = sub(r"\bstatic\s+inline\b[^;{]*\{", "static inline {", text)
|
|
22
|
+
declared = findall(rf"\b({escape(prefix)}\w*)\s*\((?!\s*\*)", text)
|
|
23
|
+
inline = set(findall(rf"\bstatic\s+(?:inline\s+)?[^;{{(]*?\b({escape(prefix)}\w*)\s*\((?!\s*\*)", text))
|
|
24
|
+
return sorted(set(declared) - inline)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def check_headers(headers: list[Path], abi_strings: list[str], *, base: Path, label: str) -> list[Path]:
|
|
28
|
+
"""Resolve expected headers against `base`, require each to be a file, and require every ABI string in one of them."""
|
|
29
|
+
resolved = []
|
|
30
|
+
for header in headers:
|
|
31
|
+
path = Path(header)
|
|
32
|
+
path = path.resolve() if path.is_absolute() else (base / path).resolve()
|
|
33
|
+
if not path.exists():
|
|
34
|
+
raise FileNotFoundError(f"Artifact '{label}' expected header does not exist: {header}")
|
|
35
|
+
if not path.is_file():
|
|
36
|
+
raise FileNotFoundError(f"Artifact '{label}' expected header is not a file: {header}")
|
|
37
|
+
resolved.append(path)
|
|
38
|
+
|
|
39
|
+
if abi_strings and not resolved:
|
|
40
|
+
raise ValueError(f"Artifact '{label}' must set expected-headers when using expected-abi-strings.")
|
|
41
|
+
|
|
42
|
+
for expected in abi_strings:
|
|
43
|
+
if not any(expected in header.read_text(errors="replace") for header in resolved):
|
|
44
|
+
raise RuntimeError(f"Artifact '{label}' expected ABI string was not found in headers: {expected}")
|
|
45
|
+
return resolved
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def prefixed_header_symbols(headers: list[Path], prefix: str | None, *, label: str) -> list[str]:
|
|
49
|
+
"""Functions starting with `prefix` across `headers`; an error if a prefix is set and none match."""
|
|
50
|
+
if prefix is None:
|
|
51
|
+
return []
|
|
52
|
+
symbols = sorted({symbol for header in headers for symbol in header_symbols(header.read_text(errors="replace"), prefix)})
|
|
53
|
+
if not symbols:
|
|
54
|
+
raise RuntimeError(f"Artifact '{label}' expected headers declare no functions starting with '{prefix}'.")
|
|
55
|
+
return symbols
|
hatch_native/manifest.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from json import dumps
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
__all__ = ("MANIFEST_VERSION", "write_artifact_manifest")
|
|
7
|
+
|
|
8
|
+
MANIFEST_VERSION = 1
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def write_artifact_manifest(destination: Path, *, module: str, records: list[dict[str, str]]) -> None:
|
|
12
|
+
"""Write the artifact manifest JSON shared by the hatch native plugins."""
|
|
13
|
+
destination.parent.mkdir(parents=True, exist_ok=True)
|
|
14
|
+
payload = {"version": MANIFEST_VERSION, "module": module, "artifacts": records}
|
|
15
|
+
destination.write_text(dumps(payload, indent=2, sort_keys=True) + "\n")
|
hatch_native/naming.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
__all__ = ("shared_library_name",)
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def shared_library_name(library: str, *, platform: str) -> str:
|
|
7
|
+
"""Render a platform-specific standalone shared-library filename."""
|
|
8
|
+
if platform == "win32":
|
|
9
|
+
return f"{library}.dll"
|
|
10
|
+
if platform == "darwin":
|
|
11
|
+
return f"lib{library}.dylib"
|
|
12
|
+
if platform == "linux":
|
|
13
|
+
return f"lib{library}.so"
|
|
14
|
+
if platform == "emscripten":
|
|
15
|
+
return f"{library}.wasm"
|
|
16
|
+
raise ValueError(f"Unsupported platform: {platform}")
|
hatch_native/symbols.py
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
"""Read exported symbol names from shared libraries without loading them.
|
|
2
|
+
|
|
3
|
+
Supports ELF, Mach-O (including fat binaries), PE, and WebAssembly so that
|
|
4
|
+
cross-compiled and Pyodide artifacts can be checked on any host.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from struct import Struct, unpack_from
|
|
11
|
+
|
|
12
|
+
__all__ = ("exported_symbols",)
|
|
13
|
+
|
|
14
|
+
_ELF_MAGIC = b"\x7fELF"
|
|
15
|
+
_PE_MAGIC = b"MZ"
|
|
16
|
+
_WASM_MAGIC = b"\x00asm"
|
|
17
|
+
_MACHO_MAGICS = {
|
|
18
|
+
b"\xcf\xfa\xed\xfe": ("<", 64),
|
|
19
|
+
b"\xfe\xed\xfa\xcf": (">", 64),
|
|
20
|
+
b"\xce\xfa\xed\xfe": ("<", 32),
|
|
21
|
+
b"\xfe\xed\xfa\xce": (">", 32),
|
|
22
|
+
}
|
|
23
|
+
_FAT_MAGICS = {b"\xca\xfe\xba\xbe": 32, b"\xca\xfe\xba\xbf": 64}
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def exported_symbols(path: Path | str) -> set[str]:
|
|
27
|
+
"""Return the names a shared library exports, as a C caller would spell them."""
|
|
28
|
+
data = Path(path).read_bytes()
|
|
29
|
+
if data[:4] == _ELF_MAGIC:
|
|
30
|
+
return _elf_exports(data)
|
|
31
|
+
if data[:4] in _MACHO_MAGICS:
|
|
32
|
+
return _macho_exports(data)
|
|
33
|
+
if data[:4] in _FAT_MAGICS:
|
|
34
|
+
return _fat_exports(data)
|
|
35
|
+
if data[:2] == _PE_MAGIC:
|
|
36
|
+
return _pe_exports(data)
|
|
37
|
+
if data[:4] == _WASM_MAGIC:
|
|
38
|
+
return _wasm_exports(data)
|
|
39
|
+
raise ValueError(f"Unrecognized shared library format: {path}")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _cstring(data: bytes, offset: int) -> str:
|
|
43
|
+
end = data.index(b"\x00", offset)
|
|
44
|
+
return data[offset:end].decode("utf-8", errors="replace")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _elf_exports(data: bytes) -> set[str]:
|
|
48
|
+
is_64 = data[4] == 2
|
|
49
|
+
endian = "<" if data[5] == 1 else ">"
|
|
50
|
+
if is_64:
|
|
51
|
+
shoff, shentsize, shnum = unpack_from(f"{endian}Q", data, 0x28)[0], *unpack_from(f"{endian}HH", data, 0x3A)
|
|
52
|
+
section_header = Struct(f"{endian}IIQQQQIIQQ")
|
|
53
|
+
symbol = Struct(f"{endian}IBBHQQ")
|
|
54
|
+
else:
|
|
55
|
+
shoff, shentsize, shnum = unpack_from(f"{endian}I", data, 0x20)[0], *unpack_from(f"{endian}HH", data, 0x2E)
|
|
56
|
+
section_header = Struct(f"{endian}IIIIIIIIII")
|
|
57
|
+
symbol = Struct(f"{endian}IIIBBH")
|
|
58
|
+
|
|
59
|
+
sections = [section_header.unpack_from(data, shoff + index * shentsize) for index in range(shnum)]
|
|
60
|
+
dynsym = next((section for section in sections if section[1] == 11), None)
|
|
61
|
+
if dynsym is None:
|
|
62
|
+
raise ValueError("ELF file has no dynamic symbol table")
|
|
63
|
+
_, _, _, _, sym_offset, sym_size, link, _, _, entsize = dynsym
|
|
64
|
+
str_offset = sections[link][4]
|
|
65
|
+
|
|
66
|
+
exported = set()
|
|
67
|
+
for index in range(sym_size // (entsize or symbol.size)):
|
|
68
|
+
fields = symbol.unpack_from(data, sym_offset + index * (entsize or symbol.size))
|
|
69
|
+
if is_64:
|
|
70
|
+
name, info, _, shndx = fields[0], fields[1], fields[2], fields[3]
|
|
71
|
+
else:
|
|
72
|
+
name, info, shndx = fields[0], fields[3], fields[5]
|
|
73
|
+
if shndx == 0 or info >> 4 not in (1, 2) or name == 0:
|
|
74
|
+
continue
|
|
75
|
+
exported.add(_cstring(data, str_offset + name))
|
|
76
|
+
return exported
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _macho_exports(data: bytes, base: int = 0) -> set[str]:
|
|
80
|
+
endian, bits = _MACHO_MAGICS[data[base : base + 4]]
|
|
81
|
+
header_size = 32 if bits == 64 else 28
|
|
82
|
+
ncmds = unpack_from(f"{endian}I", data, base + 16)[0]
|
|
83
|
+
nlist = Struct(f"{endian}IBBHQ") if bits == 64 else Struct(f"{endian}IBBhI")
|
|
84
|
+
|
|
85
|
+
offset = base + header_size
|
|
86
|
+
symtab = None
|
|
87
|
+
for _ in range(ncmds):
|
|
88
|
+
cmd, cmdsize = unpack_from(f"{endian}II", data, offset)
|
|
89
|
+
if cmd == 0x2:
|
|
90
|
+
symtab = unpack_from(f"{endian}IIII", data, offset + 8)
|
|
91
|
+
offset += cmdsize
|
|
92
|
+
if symtab is None:
|
|
93
|
+
raise ValueError("Mach-O file has no symbol table")
|
|
94
|
+
symoff, nsyms, stroff, _ = symtab
|
|
95
|
+
|
|
96
|
+
exported = set()
|
|
97
|
+
for index in range(nsyms):
|
|
98
|
+
strx, n_type, _, _, _ = nlist.unpack_from(data, base + symoff + index * nlist.size)
|
|
99
|
+
if n_type & 0xE0 or not n_type & 0x01 or n_type & 0x0E != 0x0E:
|
|
100
|
+
continue
|
|
101
|
+
name = _cstring(data, base + stroff + strx)
|
|
102
|
+
exported.add(name.removeprefix("_"))
|
|
103
|
+
return exported
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _fat_exports(data: bytes) -> set[str]:
|
|
107
|
+
bits = _FAT_MAGICS[data[:4]]
|
|
108
|
+
narch = unpack_from(">I", data, 4)[0]
|
|
109
|
+
arch = Struct(">IIQQII") if bits == 64 else Struct(">IIIII")
|
|
110
|
+
exported = set()
|
|
111
|
+
for index in range(narch):
|
|
112
|
+
fields = arch.unpack_from(data, 8 + index * arch.size)
|
|
113
|
+
exported |= _macho_exports(data, base=fields[2])
|
|
114
|
+
return exported
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _pe_exports(data: bytes) -> set[str]:
|
|
118
|
+
pe_offset = unpack_from("<I", data, 0x3C)[0]
|
|
119
|
+
if data[pe_offset : pe_offset + 4] != b"PE\x00\x00":
|
|
120
|
+
raise ValueError("PE file has no PE signature")
|
|
121
|
+
nsections, optional_size = unpack_from("<H", data, pe_offset + 6)[0], unpack_from("<H", data, pe_offset + 20)[0]
|
|
122
|
+
optional_offset = pe_offset + 24
|
|
123
|
+
magic = unpack_from("<H", data, optional_offset)[0]
|
|
124
|
+
directory_offset = optional_offset + (112 if magic == 0x20B else 96)
|
|
125
|
+
export_rva, export_size = unpack_from("<II", data, directory_offset)
|
|
126
|
+
if export_rva == 0 or export_size == 0:
|
|
127
|
+
return set()
|
|
128
|
+
|
|
129
|
+
section = Struct("<8sIIIIIIHHI")
|
|
130
|
+
sections_offset = optional_offset + optional_size
|
|
131
|
+
sections = [section.unpack_from(data, sections_offset + index * section.size) for index in range(nsections)]
|
|
132
|
+
|
|
133
|
+
def file_offset(rva: int) -> int:
|
|
134
|
+
for _, virtual_size, virtual_address, raw_size, raw_pointer, *_ in sections:
|
|
135
|
+
if virtual_address <= rva < virtual_address + max(virtual_size, raw_size):
|
|
136
|
+
return rva - virtual_address + raw_pointer
|
|
137
|
+
raise ValueError(f"PE RVA {rva:#x} is not inside any section")
|
|
138
|
+
|
|
139
|
+
export_offset = file_offset(export_rva)
|
|
140
|
+
nnames, _, names_rva = unpack_from("<III", data, export_offset + 24)
|
|
141
|
+
names_offset = file_offset(names_rva)
|
|
142
|
+
return {_cstring(data, file_offset(unpack_from("<I", data, names_offset + index * 4)[0])) for index in range(nnames)}
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _leb128(data: bytes, offset: int) -> tuple[int, int]:
|
|
146
|
+
result = shift = 0
|
|
147
|
+
while True:
|
|
148
|
+
byte = data[offset]
|
|
149
|
+
offset += 1
|
|
150
|
+
result |= (byte & 0x7F) << shift
|
|
151
|
+
shift += 7
|
|
152
|
+
if not byte & 0x80:
|
|
153
|
+
return result, offset
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _wasm_exports(data: bytes) -> set[str]:
|
|
157
|
+
offset = 8
|
|
158
|
+
while offset < len(data):
|
|
159
|
+
section_id = data[offset]
|
|
160
|
+
size, offset = _leb128(data, offset + 1)
|
|
161
|
+
if section_id != 7:
|
|
162
|
+
offset += size
|
|
163
|
+
continue
|
|
164
|
+
count, offset = _leb128(data, offset)
|
|
165
|
+
exported = set()
|
|
166
|
+
for _ in range(count):
|
|
167
|
+
length, offset = _leb128(data, offset)
|
|
168
|
+
exported.add(data[offset : offset + length].decode("utf-8", errors="replace"))
|
|
169
|
+
offset += length
|
|
170
|
+
_, offset = _leb128(data, offset + 1)
|
|
171
|
+
return exported
|
|
172
|
+
return set()
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
from json import loads
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
|
|
4
|
+
import pytest
|
|
5
|
+
from pydantic import ValidationError
|
|
6
|
+
|
|
7
|
+
from hatch_native import (
|
|
8
|
+
LibraryValidationConfig,
|
|
9
|
+
check_exports,
|
|
10
|
+
check_headers,
|
|
11
|
+
header_symbols,
|
|
12
|
+
prefixed_header_symbols,
|
|
13
|
+
resolve_external_library,
|
|
14
|
+
resolve_library_source,
|
|
15
|
+
shared_library_name,
|
|
16
|
+
write_artifact_manifest,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
HEADER = """
|
|
20
|
+
#define DEMO_ABI_VERSION 1
|
|
21
|
+
/* demo_commented(void); */
|
|
22
|
+
typedef int (*demo_callback)(int);
|
|
23
|
+
int demo_answer(void);
|
|
24
|
+
void demo_free(void *ptr);
|
|
25
|
+
static inline int demo_inline(void) { return 1; }
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def test_header_symbols_skip_comments_pointers_and_inline():
|
|
30
|
+
assert header_symbols(HEADER, "demo_") == ["demo_answer", "demo_free"]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def test_check_headers_resolves_and_finds_abi_string(tmp_path):
|
|
34
|
+
(tmp_path / "demo.h").write_text(HEADER)
|
|
35
|
+
assert check_headers([Path("demo.h")], ["DEMO_ABI_VERSION 1"], base=tmp_path, label="demo") == [(tmp_path / "demo.h").resolve()]
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def test_check_headers_errors(tmp_path):
|
|
39
|
+
with pytest.raises(FileNotFoundError, match="expected header does not exist"):
|
|
40
|
+
check_headers([Path("missing.h")], [], base=tmp_path, label="demo")
|
|
41
|
+
with pytest.raises(ValueError, match="must set expected-headers"):
|
|
42
|
+
check_headers([], ["DEMO_ABI_VERSION"], base=tmp_path, label="demo")
|
|
43
|
+
(tmp_path / "demo.h").write_text(HEADER)
|
|
44
|
+
with pytest.raises(RuntimeError, match="ABI string was not found"):
|
|
45
|
+
check_headers([Path("demo.h")], ["DEMO_ABI_VERSION 2"], base=tmp_path, label="demo")
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def test_prefixed_header_symbols(tmp_path):
|
|
49
|
+
header = tmp_path / "demo.h"
|
|
50
|
+
header.write_text(HEADER)
|
|
51
|
+
assert prefixed_header_symbols([header], None, label="demo") == []
|
|
52
|
+
assert prefixed_header_symbols([header], "demo_", label="demo") == ["demo_answer", "demo_free"]
|
|
53
|
+
with pytest.raises(RuntimeError, match="declare no functions starting with 'other_'"):
|
|
54
|
+
prefixed_header_symbols([header], "other_", label="demo")
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def test_check_exports_reports_missing(monkeypatch, tmp_path):
|
|
58
|
+
monkeypatch.setattr("hatch_native.validation.exported_symbols", lambda path: {"demo_answer"})
|
|
59
|
+
check_exports(tmp_path / "libdemo.so", expected=["demo_answer"], load=False, label="demo", display_path="lib/libdemo.so")
|
|
60
|
+
with pytest.raises(RuntimeError, match="expected symbol was not exported: demo_free"):
|
|
61
|
+
check_exports(tmp_path / "libdemo.so", expected=["demo_answer", "demo_free"], load=False, label="demo", display_path="lib/libdemo.so")
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@pytest.mark.parametrize(
|
|
65
|
+
"platform,filename",
|
|
66
|
+
[("linux", "libdemo.so"), ("darwin", "libdemo.dylib"), ("win32", "demo.dll"), ("emscripten", "demo.wasm")],
|
|
67
|
+
)
|
|
68
|
+
def test_shared_library_name(platform, filename):
|
|
69
|
+
assert shared_library_name("demo", platform=platform) == filename
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def test_resolve_library_source(monkeypatch):
|
|
73
|
+
monkeypatch.delenv("DEMO_LIBRARY_SOURCE", raising=False)
|
|
74
|
+
assert resolve_library_source("bundled", env_var="DEMO_LIBRARY_SOURCE") == "bundled"
|
|
75
|
+
monkeypatch.setenv("DEMO_LIBRARY_SOURCE", "external")
|
|
76
|
+
assert resolve_library_source("bundled", env_var="DEMO_LIBRARY_SOURCE") == "external"
|
|
77
|
+
monkeypatch.setenv("DEMO_LIBRARY_SOURCE", "vendored")
|
|
78
|
+
with pytest.raises(ValueError, match="Unsupported DEMO_LIBRARY_SOURCE: vendored"):
|
|
79
|
+
resolve_library_source("bundled", env_var="DEMO_LIBRARY_SOURCE")
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def test_resolve_external_library_from_root(tmp_path):
|
|
83
|
+
(tmp_path / "lib").mkdir()
|
|
84
|
+
(tmp_path / "include").mkdir()
|
|
85
|
+
(tmp_path / "lib" / "libdemo.so.1").write_bytes(b"")
|
|
86
|
+
external = resolve_external_library("demo", label="demo", platform="linux", root_env_var="DEMO_ROOT", root=tmp_path)
|
|
87
|
+
assert external.library == tmp_path / "lib" / "libdemo.so.1"
|
|
88
|
+
assert external.include_dir == tmp_path / "include"
|
|
89
|
+
assert external.link_name == "demo"
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def test_resolve_external_library_windows_prefers_bin_and_import_library(tmp_path):
|
|
93
|
+
(tmp_path / "lib").mkdir()
|
|
94
|
+
(tmp_path / "bin").mkdir()
|
|
95
|
+
(tmp_path / "bin" / "demo.dll").write_bytes(b"")
|
|
96
|
+
(tmp_path / "lib" / "demo.lib").write_bytes(b"")
|
|
97
|
+
external = resolve_external_library("demo", label="demo", platform="win32", root_env_var="DEMO_ROOT", root=tmp_path)
|
|
98
|
+
assert external.library == tmp_path / "bin" / "demo.dll"
|
|
99
|
+
assert external.link_name == "demo"
|
|
100
|
+
assert external.include_dir is None
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def test_resolve_external_library_errors(monkeypatch, tmp_path):
|
|
104
|
+
monkeypatch.delenv("PREFIX", raising=False)
|
|
105
|
+
monkeypatch.delenv("CONDA_PREFIX", raising=False)
|
|
106
|
+
with pytest.raises(ValueError, match="DEMO_ROOT, PREFIX, or CONDA_PREFIX"):
|
|
107
|
+
resolve_external_library("demo", label="demo", platform="linux", root_env_var="DEMO_ROOT")
|
|
108
|
+
with pytest.raises(FileNotFoundError, match="external library 'libdemo.so' was not found"):
|
|
109
|
+
resolve_external_library("demo", label="demo", platform="linux", root_env_var="DEMO_ROOT", root=tmp_path)
|
|
110
|
+
with pytest.raises(ValueError, match="package 'not_a_real_package' is not installed"):
|
|
111
|
+
resolve_external_library("demo", label="demo", platform="linux", root_env_var="DEMO_ROOT", package="not_a_real_package")
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def test_write_artifact_manifest(tmp_path):
|
|
115
|
+
destination = tmp_path / "demo" / "lib" / "artifacts.json"
|
|
116
|
+
write_artifact_manifest(destination, module="demo", records=[{"name": "demo", "role": "library"}])
|
|
117
|
+
assert loads(destination.read_text()) == {"version": 1, "module": "demo", "artifacts": [{"name": "demo", "role": "library"}]}
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def test_validation_config_accepts_both_spellings():
|
|
121
|
+
kebab = LibraryValidationConfig.model_validate({"expected-symbols": "demo_answer", "expected-headers": "demo.h", "validate": True})
|
|
122
|
+
snake = LibraryValidationConfig(expected_symbols=["demo_answer"], expected_headers=[Path("demo.h")], validate_artifact=True)
|
|
123
|
+
assert kebab == snake
|
|
124
|
+
assert LibraryValidationConfig.model_validate({"validation-commands": ["true"]}).validation_commands[0].command == ["true"]
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def test_validation_config_requires_headers_for_prefix():
|
|
128
|
+
with pytest.raises(ValidationError, match="must set expected-headers when using header-symbol-prefix"):
|
|
129
|
+
LibraryValidationConfig.model_validate({"header-symbol-prefix": "demo_"})
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import _ctypes
|
|
2
|
+
|
|
3
|
+
import pytest
|
|
4
|
+
|
|
5
|
+
from hatch_native.symbols import exported_symbols
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def test_host_extension_module_exports_init_symbol():
|
|
9
|
+
assert "PyInit__ctypes" in exported_symbols(_ctypes.__file__)
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def test_wasm_export_section(tmp_path):
|
|
13
|
+
# (module (func $f (export "demo_answer") (result i32) i32.const 42) (memory (export "memory") 1))
|
|
14
|
+
module = bytes.fromhex(
|
|
15
|
+
"0061736d01000000" # magic, version
|
|
16
|
+
"010501600001 7f" # type section: () -> i32
|
|
17
|
+
"03020100" # function section: one function of type 0
|
|
18
|
+
"0503010001" # memory section: min 1 page
|
|
19
|
+
"071802 0b64656d6f5f616e737765720000 066d656d6f72790200" # export section: demo_answer (func 0), memory (mem 0)
|
|
20
|
+
"0a06010400412a0b" # code section
|
|
21
|
+
)
|
|
22
|
+
wasm = tmp_path / "demo.wasm"
|
|
23
|
+
wasm.write_bytes(module)
|
|
24
|
+
assert exported_symbols(wasm) == {"demo_answer", "memory"}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def test_unknown_format_fails_clearly(tmp_path):
|
|
28
|
+
other = tmp_path / "other.so"
|
|
29
|
+
other.write_bytes(b"not a library")
|
|
30
|
+
with pytest.raises(ValueError, match="Unrecognized shared library format"):
|
|
31
|
+
exported_symbols(other)
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from ctypes import CDLL
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from shlex import join as shell_join
|
|
6
|
+
from subprocess import run
|
|
7
|
+
|
|
8
|
+
from .symbols import exported_symbols
|
|
9
|
+
|
|
10
|
+
__all__ = ("check_exports", "run_validation_command")
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def check_exports(library: Path, *, expected: list[str], load: bool, label: str, display_path: str) -> None:
|
|
14
|
+
"""Require `expected` symbols in the export table of `library`, then optionally load it with ctypes."""
|
|
15
|
+
if expected:
|
|
16
|
+
try:
|
|
17
|
+
exported = exported_symbols(library)
|
|
18
|
+
except (OSError, ValueError) as error:
|
|
19
|
+
raise RuntimeError(f"Artifact '{label}' could not read exported symbols from '{display_path}': {error}") from error
|
|
20
|
+
missing = [symbol for symbol in expected if symbol not in exported]
|
|
21
|
+
if missing:
|
|
22
|
+
raise RuntimeError(f"Artifact '{label}' expected symbol was not exported: {', '.join(missing)}")
|
|
23
|
+
|
|
24
|
+
if load:
|
|
25
|
+
try:
|
|
26
|
+
CDLL(str(library))
|
|
27
|
+
except OSError as error:
|
|
28
|
+
raise RuntimeError(f"Artifact '{label}' failed validation load check for '{display_path}': {error}") from error
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def run_validation_command(command: list[str], *, cwd: Path, env: dict[str, str], label: str) -> None:
|
|
32
|
+
"""Run one validation command argv, raising with the artifact label on a missing executable or non-zero exit."""
|
|
33
|
+
try:
|
|
34
|
+
completed = run(command, cwd=cwd, env=env, check=False)
|
|
35
|
+
except FileNotFoundError as error:
|
|
36
|
+
raise RuntimeError(f"Artifact '{label}' validation command was not found: {command[0]}") from error
|
|
37
|
+
if completed.returncode != 0:
|
|
38
|
+
raise RuntimeError(f"Artifact '{label}' validation command failed with exit code {completed.returncode}: {shell_join(command)}")
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: hatch-native
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Shared native-build helpers for hatch plugins
|
|
5
|
+
Project-URL: Repository, https://github.com/python-project-templates/hatch-native
|
|
6
|
+
Project-URL: Homepage, https://github.com/python-project-templates/hatch-native
|
|
7
|
+
Author-email: the hatch-native authors <t.paine154@gmail.com>
|
|
8
|
+
License: Apache-2.0
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Classifier: Development Status :: 3 - Alpha
|
|
11
|
+
Classifier: Programming Language :: Python
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
18
|
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
|
19
|
+
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
|
20
|
+
Requires-Python: >=3.10
|
|
21
|
+
Requires-Dist: pydantic
|
|
22
|
+
Provides-Extra: develop
|
|
23
|
+
Requires-Dist: build; extra == 'develop'
|
|
24
|
+
Requires-Dist: bump-my-version; extra == 'develop'
|
|
25
|
+
Requires-Dist: check-dist; extra == 'develop'
|
|
26
|
+
Requires-Dist: codespell; extra == 'develop'
|
|
27
|
+
Requires-Dist: hatchling; extra == 'develop'
|
|
28
|
+
Requires-Dist: mdformat; extra == 'develop'
|
|
29
|
+
Requires-Dist: mdformat-myst; extra == 'develop'
|
|
30
|
+
Requires-Dist: mdformat-tables>=1; extra == 'develop'
|
|
31
|
+
Requires-Dist: pytest; extra == 'develop'
|
|
32
|
+
Requires-Dist: pytest-cov; extra == 'develop'
|
|
33
|
+
Requires-Dist: ruff; extra == 'develop'
|
|
34
|
+
Requires-Dist: twine; extra == 'develop'
|
|
35
|
+
Requires-Dist: ty; extra == 'develop'
|
|
36
|
+
Requires-Dist: uv; extra == 'develop'
|
|
37
|
+
Requires-Dist: wheel; extra == 'develop'
|
|
38
|
+
Description-Content-Type: text/markdown
|
|
39
|
+
|
|
40
|
+
# hatch native
|
|
41
|
+
|
|
42
|
+
Shared native-build helpers for hatch plugins
|
|
43
|
+
|
|
44
|
+
[](https://github.com/python-project-templates/hatch-native/actions/workflows/build.yaml)
|
|
45
|
+
[](https://codecov.io/gh/python-project-templates/hatch-native)
|
|
46
|
+
[](https://github.com/python-project-templates/hatch-native)
|
|
47
|
+
[](https://pypi.python.org/pypi/hatch-native)
|
|
48
|
+
|
|
49
|
+
## Overview
|
|
50
|
+
|
|
51
|
+
Helpers shared by the hatch native build plugins ([hatch-rs](https://github.com/python-project-templates/hatch-rs), [hatch-cpp](https://github.com/python-project-templates/hatch-cpp)) for wheels that ship a C ABI library next to a Python extension. It is a library for plugin authors, not a hatch plugin, and has no configuration of its own.
|
|
52
|
+
|
|
53
|
+
| Module | Provides |
|
|
54
|
+
| ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
55
|
+
| `symbols` | `exported_symbols(path)`: the export table of an ELF, Mach-O (including fat), PE, or WebAssembly binary, read without loading it |
|
|
56
|
+
| `headers` | `header_symbols(text, prefix)`, `check_headers(...)` for expected headers and ABI strings, `prefixed_header_symbols(...)` |
|
|
57
|
+
| `validation` | `check_exports(...)` for expected symbols plus an optional `ctypes` load, `run_validation_command(...)` |
|
|
58
|
+
| `config` | pydantic models `LibraryValidationConfig`, `ExternalLibraryConfig`, `ValidationCommandConfig`, so every plugin uses the same field names |
|
|
59
|
+
| `external` | `resolve_library_source(...)` for `bundled`, `external`, `static`, `direct`; `resolve_external_library(...)` from a root, a Python package, pkg-config, or `$PREFIX`/`$CONDA_PREFIX` |
|
|
60
|
+
| `manifest` | `write_artifact_manifest(...)`: `{"version": 1, "module": ..., "artifacts": [...]}` |
|
|
61
|
+
| `naming` | `shared_library_name(name, platform=...)`: `libfoo.so`, `libfoo.dylib`, `foo.dll`, `foo.wasm` |
|
|
62
|
+
|
|
63
|
+
Plugins mix the config models into their own artifact models, so a project writes the same keys whichever plugin builds the library:
|
|
64
|
+
|
|
65
|
+
```toml
|
|
66
|
+
expected-headers = ["include/foo/foo.h"]
|
|
67
|
+
header-symbol-prefix = "foo_"
|
|
68
|
+
expected-abi-strings = ["FOO_ABI_VERSION 1"]
|
|
69
|
+
validate = false
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
Each key also accepts its snake_case spelling.
|
|
73
|
+
|
|
74
|
+
> [!NOTE]
|
|
75
|
+
> This library was generated using [copier](https://copier.readthedocs.io/en/stable/) from the [Base Python Project Template repository](https://github.com/python-project-templates/base).
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
hatch_native/__init__.py,sha256=vt5NxBl-bYTix-TYO8Mgf3nNqvBY1jJxUs2vGwV8lkU,536
|
|
2
|
+
hatch_native/config.py,sha256=_yc3kNOfcsH8Ua62sxYG0SVP9erfd5ZEK3aoSUQPte0,5684
|
|
3
|
+
hatch_native/external.py,sha256=zh6jqfZEMRVhO-1DP853qKVcD0dyq0YHaomJ1Yso68k,4636
|
|
4
|
+
hatch_native/headers.py,sha256=IaiQoCreYTarkdgKaToaRf1MvOS9CI0asy5BXLZv3CE,2729
|
|
5
|
+
hatch_native/manifest.py,sha256=l3aIOuPZsX_ufK2Ph-l6zu5SKgkpVAT10Ua5kAdEr0I,567
|
|
6
|
+
hatch_native/naming.py,sha256=MVsvTPPTOXIIEdnQAK8OKTNFDpAXr9isYgu1nK1xvto,522
|
|
7
|
+
hatch_native/symbols.py,sha256=M3b1tJj-yIZZ8qtBbyHBlDF3Zszus3t_L74rdIPFYm0,6566
|
|
8
|
+
hatch_native/validation.py,sha256=Z4HHcYCxh7hPNmL9jHFPFCAjinNc4CH4C0I5Q-f5Sc8,1749
|
|
9
|
+
hatch_native/tests/test_all.py,sha256=ptrNJHxn3_oqh6soGK0Ln62P330yuGLIhzFyAYbb2WQ,61
|
|
10
|
+
hatch_native/tests/test_shared.py,sha256=RjVcxiGiGCTXvrLnz3wXTA6EhBgVYY4fxdU98AYxEA8,6141
|
|
11
|
+
hatch_native/tests/test_symbols.py,sha256=_tS5RTphjX3KnKt6tnOL4gZSqDCkNkR4jVCcPSq2K1g,1121
|
|
12
|
+
hatch_native-0.1.0.dist-info/METADATA,sha256=sfh_YFD8mJX5FO70QKdADJleQJJdzNdQg5jisqfzOqo,5066
|
|
13
|
+
hatch_native-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
14
|
+
hatch_native-0.1.0.dist-info/licenses/LICENSE,sha256=RJv62sIjY-yDby6aGrpsXxXxN5lMUCxclVo4HZjsAno,11354
|
|
15
|
+
hatch_native-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2025 the hatch-native authors
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|