Debian Codegraph @

build_ext.py

raw
1 """Build optional cython modules."""
2
3 import logging
4 import os
5 from distutils.command.build_ext import build_ext
6 from typing import Any
7
8 try:
9 from setuptools import Extension
10 except ImportError:
11 from distutils.core import Extension
12
13
14 _LOGGER = logging.getLogger(__name__)
15
16 TO_CYTHONIZE = [
17 "src/habluetooth/advertisement_tracker.py",
18 "src/habluetooth/auto_scheduler.py",
19 "src/habluetooth/base_scanner.py",
20 "src/habluetooth/manager.py",
21 "src/habluetooth/models.py",
22 "src/habluetooth/scanner_bleak.py",
23 "src/habluetooth/channels/bluez.py",
24 ]
25
26 EXTENSIONS = [
27 Extension(
28 ext.removeprefix("src/").removesuffix(".py").replace("/", "."),
29 [ext],
30 language="c",
31 extra_compile_args=["-O3", "-g0"],
32 )
33 for ext in TO_CYTHONIZE
34 ]
35
36
37 class BuildExt(build_ext):
38 """Build extension."""
39
40 def build_extensions(self) -> None:
41 """Build extensions."""
42 if self.parallel is None: # type: ignore[has-type, unused-ignore]
43 self.parallel = os.cpu_count() or 1
44 try:
45 super().build_extensions()
46 except Exception as ex: # nosec
47 # Cython is optional; any compile failure (missing C compiler,
48 # platform mismatch, etc.) should fall back to the pure-Python
49 # install rather than break the build.
50 _LOGGER.debug("Failed to build extensions: %s", ex, exc_info=True)
51
52
53 def build(setup_kwargs: Any) -> None:
54 """Build optional cython modules."""
55 if os.environ.get("SKIP_CYTHON"):
56 return
57 try:
58 # Cython is optional; defer the import so the SKIP_CYTHON
59 # branch above never has to find it on sys.path.
60 from Cython.Build import cythonize # noqa: PLC0415
61
62 setup_kwargs.update(
63 {
64 "ext_modules": cythonize(
65 EXTENSIONS,
66 compiler_directives={"language_level": "3"}, # Python 3
67 annotate=bool(os.environ.get("CYTHON_ANNOTATE")),
68 ),
69 "cmdclass": {"build_ext": BuildExt},
70 }
71 )
72 setup_kwargs["exclude_package_data"] = {
73 pkg: ["*.c"] for pkg in setup_kwargs["packages"]
74 }
75 except Exception:
76 if os.environ.get("REQUIRE_CYTHON"):
77 raise