-
-
Notifications
You must be signed in to change notification settings - Fork 12
/
hatch_build.py
104 lines (81 loc) · 2.94 KB
/
hatch_build.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import os
import shutil
import sysconfig
from contextlib import suppress
from distutils.extension import Extension
from glob import glob
from pathlib import Path
from find_libpython import find_libpython
from hatchling.builders.hooks.plugin.interface import BuildHookInterface
from hatchling.plugin import hookimpl
from setuptools._distutils.ccompiler import new_compiler
ext_modules = [
Extension(
"_pointers",
include_dirs=["<header-file-directory>"],
sources=glob("src/_pointers/*"),
),
]
class CustomBuildHook(BuildHookInterface):
PLUGIN_NAME = "custom"
def initialize(self, version: str, data: dict):
self.clean()
compiler = new_compiler()
ext = os.path.join(self.root, "ext")
lib = os.path.join(ext, "./ext/lib")
# logic taken from distutils
if sysconfig.get_config_var('Py_ENABLE_SHARED'):
if not sysconfig.is_python_build():
compiler.add_library_dir(sysconfig.get_config_var('LIBDIR'))
else:
compiler.add_library_dir('.')
libpython_path = find_libpython()
if not libpython_path:
self.app.display_warning("failed to find libpython")
compiler.add_library_dir(str(Path(libpython_path).parent.absolute()))
compiler.add_include_dir(
os.path.join(sysconfig.get_path("platstdlib"), "lib")
)
compiler.add_include_dir(sysconfig.get_path("include"))
compiler.define_macro("PY_SSIZE_T_CLEAN")
self.app.display_waiting("compiling _pointers")
try:
compiler.compile(
glob("./src/mod.c"),
output_dir=ext,
extra_preargs=["-fPIC", "-v"] if os.name != "nt" else [],
)
except Exception:
self.app.abort("failed to compile _pointers")
self.app.display_success("successfully compiled _pointers")
self.app.display_waiting("linking _pointers")
files = []
for root, _, fls in os.walk(ext):
for i in fls:
if i.endswith(".o"):
files.append(os.path.join(root, i))
try:
compiler.link_shared_lib(
files,
"_pointers",
output_dir=lib,
debug=True
)
except Exception:
self.app.abort("failed to link _pointers")
self.app.display_success("successfully linked _pointers")
with suppress(KeyError):
data["force_include"][
os.path.join(lib, "lib_pointers.so")
] = "src/_pointers.so"
with suppress(KeyError):
data["infer_tag"] = True
with suppress(KeyError):
data["pure_python"] = False
def clean(self, *_):
path = os.path.join(self.root, "ext")
if os.path.exists(path):
shutil.rmtree(path)
@hookimpl
def hatch_register_build_hook():
return CustomBuildHook