Debian Codegraph @

packaging/pep517_backend/_backend.py

raw
1 # fmt: off
2 """PEP 517 build backend wrapper for pre-building Cython for wheel."""
3
4 from __future__ import annotations
5
6 import os
7 from contextlib import contextmanager, nullcontext, suppress
8 from functools import partial
9 from pathlib import Path
10 from shutil import copytree
11 from sys import implementation as _system_implementation
12 from sys import stderr as _standard_error_stream
13 from tempfile import TemporaryDirectory
14 from typing import Dict, Iterator, List, Union
15 from warnings import warn as _warn_that
16
17 from setuptools.build_meta import build_sdist as _setuptools_build_sdist
18 from setuptools.build_meta import build_wheel as _setuptools_build_wheel
19 from setuptools.build_meta import (
20 get_requires_for_build_wheel as _setuptools_get_requires_for_build_wheel,
21 )
22 from setuptools.build_meta import (
23 prepare_metadata_for_build_wheel as _setuptools_prepare_metadata_for_build_wheel,
24 )
25
26 try:
27 from setuptools.build_meta import build_editable as _setuptools_build_editable
28 except ImportError:
29 _setuptools_build_editable = None # type: ignore[assignment]
30
31
32 # isort: split
33 from distutils.command.install import install as _distutils_install_cmd
34 from distutils.core import Distribution as _DistutilsDistribution
35 from distutils.dist import DistributionMetadata as _DistutilsDistributionMetadata
36
37 with suppress(ImportError):
38 # NOTE: Only available for wheel builds that bundle C-extensions. Declared
39 # NOTE: by `get_requires_for_build_wheel()` and
40 # NOTE: `get_requires_for_build_editable()`, when `pure-python`
41 # NOTE: is not passed.
42 from Cython.Build.Cythonize import main as _cythonize_cli_cmd
43
44 from ._compat import chdir_cm
45 from ._cython_configuration import get_local_cython_config as _get_local_cython_config
46 from ._cython_configuration import (
47 make_cythonize_cli_args_from_config as _make_cythonize_cli_args_from_config,
48 )
49 from ._cython_configuration import patched_env as _patched_cython_env
50 from ._transformers import sanitize_rst_roles
51
52 __all__ = ( # noqa: WPS410
53 'build_sdist',
54 'build_wheel',
55 'get_requires_for_build_wheel',
56 'prepare_metadata_for_build_wheel',
57 *(
58 () if _setuptools_build_editable is None # type: ignore[redundant-expr]
59 else (
60 'build_editable',
61 'get_requires_for_build_editable',
62 'prepare_metadata_for_build_editable',
63 )
64 ),
65 )
66
67 _ConfigDict = Dict[str, Union[str, List[str], None]]
68
69
70 CYTHON_TRACING_CONFIG_SETTING = 'with-cython-tracing'
71 """Config setting name toggle to include line tracing to C-exts."""
72
73 CYTHON_TRACING_ENV_VAR = 'FROZENLIST_CYTHON_TRACING'
74 """Environment variable name toggle used to opt out of making C-exts."""
75
76 PURE_PYTHON_CONFIG_SETTING = 'pure-python'
77 """Config setting name toggle that is used to opt out of making C-exts."""
78
79 PURE_PYTHON_ENV_VAR = 'FROZENLIST_NO_EXTENSIONS'
80 """Environment variable name toggle used to opt out of making C-exts."""
81
82 IS_CPYTHON = _system_implementation.name == "cpython"
83 """A flag meaning that the current interpreter implementation is CPython."""
84
85 PURE_PYTHON_MODE_CLI_FALLBACK = not IS_CPYTHON
86 """A fallback for ``pure-python`` is not set."""
87
88
89 def _is_truthy_setting_value(setting_value: str) -> bool:
90 truthy_values = {'', None, 'true', '1', 'on'}
91 return setting_value.lower() in truthy_values
92
93
94 def _get_setting_value(
95 config_settings: _ConfigDict | None = None,
96 config_setting_name: str | None = None,
97 env_var_name: str | None = None,
98 *,
99 default: bool = False,
100 ) -> bool:
101 user_provided_setting_sources = (
102 (config_settings, config_setting_name, (KeyError, TypeError)),
103 (os.environ, env_var_name, KeyError),
104 )
105 for src_mapping, src_key, lookup_errors in user_provided_setting_sources:
106 if src_key is None:
107 continue
108
109 with suppress(lookup_errors): # type: ignore[arg-type]
110 return _is_truthy_setting_value(src_mapping[src_key]) # type: ignore[arg-type,index]
111
112 return default
113
114
115 def _make_pure_python(config_settings: _ConfigDict | None = None) -> bool:
116 return _get_setting_value(
117 config_settings,
118 PURE_PYTHON_CONFIG_SETTING,
119 PURE_PYTHON_ENV_VAR,
120 default=PURE_PYTHON_MODE_CLI_FALLBACK,
121 )
122
123
124 def _include_cython_line_tracing(
125 config_settings: _ConfigDict | None = None,
126 *,
127 default: bool = False,
128 ) -> bool:
129 return _get_setting_value(
130 config_settings,
131 CYTHON_TRACING_CONFIG_SETTING,
132 CYTHON_TRACING_ENV_VAR,
133 default=default,
134 )
135
136
137 @contextmanager
138 def patched_distutils_cmd_install() -> Iterator[None]:
139 """Make `install_lib` of `install` cmd always use `platlib`.
140
141 :yields: None
142 """
143 # Without this, build_lib puts stuff under `*.data/purelib/` folder
144 orig_finalize = _distutils_install_cmd.finalize_options
145
146 def new_finalize_options(self: _distutils_install_cmd) -> None: # noqa: WPS430
147 self.install_lib = self.install_platlib
148 orig_finalize(self)
149
150 _distutils_install_cmd.finalize_options = new_finalize_options # type: ignore[method-assign]
151 try:
152 yield
153 finally:
154 _distutils_install_cmd.finalize_options = orig_finalize # type: ignore[method-assign]
155
156
157 @contextmanager
158 def patched_dist_has_ext_modules() -> Iterator[None]:
159 """Make `has_ext_modules` of `Distribution` always return `True`.
160
161 :yields: None
162 """
163 # Without this, build_lib puts stuff under `*.data/platlib/` folder
164 orig_func = _DistutilsDistribution.has_ext_modules
165
166 _DistutilsDistribution.has_ext_modules = lambda *args, **kwargs: True # type: ignore[method-assign]
167 try:
168 yield
169 finally:
170 _DistutilsDistribution.has_ext_modules = orig_func # type: ignore[method-assign]
171
172
173 @contextmanager
174 def patched_dist_get_long_description() -> Iterator[None]:
175 """Make `has_ext_modules` of `Distribution` always return `True`.
176
177 :yields: None
178 """
179 # Without this, build_lib puts stuff under `*.data/platlib/` folder
180 _orig_func = _DistutilsDistributionMetadata.get_long_description
181
182 def _get_sanitized_long_description(self: _DistutilsDistributionMetadata) -> str:
183 assert self.long_description is not None
184 return sanitize_rst_roles(self.long_description)
185
186 _DistutilsDistributionMetadata.get_long_description = ( # type: ignore[method-assign]
187 _get_sanitized_long_description
188 )
189 try:
190 yield
191 finally:
192 _DistutilsDistributionMetadata.get_long_description = _orig_func # type: ignore[method-assign]
193
194
195 def _exclude_dir_path(
196 excluded_dir_path: Path,
197 visited_directory: str,
198 _visited_dir_contents: list[str],
199 ) -> list[str]:
200 """Prevent recursive directory traversal."""
201 # This stops the temporary directory from being copied
202 # into self recursively forever.
203 # Ref: https://github.com/aio-libs/yarl/issues/992
204 visited_directory_subdirs_to_ignore = [
205 subdir
206 for subdir in _visited_dir_contents
207 if excluded_dir_path == Path(visited_directory) / subdir
208 ]
209 if visited_directory_subdirs_to_ignore:
210 print(
211 f'Preventing `{excluded_dir_path !s}` from being '
212 'copied into itself recursively...',
213 file=_standard_error_stream,
214 )
215 return visited_directory_subdirs_to_ignore
216
217
218 @contextmanager
219 def _in_temporary_directory(src_dir: Path) -> Iterator[None]:
220 with TemporaryDirectory(prefix='.tmp-frozenlist-pep517-') as tmp_dir:
221 tmp_dir_path = Path(tmp_dir)
222 root_tmp_dir_path = tmp_dir_path.parent
223 _exclude_tmpdir_parent = partial(_exclude_dir_path, root_tmp_dir_path)
224
225 with chdir_cm(tmp_dir):
226 tmp_src_dir = tmp_dir_path / 'src'
227 copytree(
228 src_dir,
229 tmp_src_dir,
230 ignore=_exclude_tmpdir_parent,
231 symlinks=True,
232 )
233 os.chdir(tmp_src_dir)
234 yield
235
236
237 @contextmanager
238 def maybe_prebuild_c_extensions(
239 line_trace_cython_when_unset: bool = False,
240 build_inplace: bool = False,
241 config_settings: _ConfigDict | None = None,
242 ) -> Iterator[None]:
243 """Pre-build C-extensions in a temporary directory, when needed.
244
245 This context manager also patches metadata, setuptools and distutils.
246
247 :param build_inplace: Whether to copy and chdir to a temporary location.
248 :param config_settings: :pep:`517` config settings mapping.
249
250 """
251 cython_line_tracing_requested = _include_cython_line_tracing(
252 config_settings,
253 default=line_trace_cython_when_unset,
254 )
255 is_pure_python_build = _make_pure_python(config_settings)
256
257 if is_pure_python_build:
258 print("*********************", file=_standard_error_stream)
259 print("* Pure Python build *", file=_standard_error_stream)
260 print("*********************", file=_standard_error_stream)
261
262 if cython_line_tracing_requested:
263 _warn_that(
264 f'The `{CYTHON_TRACING_CONFIG_SETTING !s}` setting requesting '
265 'Cython line tracing is set, but building C-extensions is not. '
266 'This option will not have any effect for in the pure-python '
267 'build mode.',
268 RuntimeWarning,
269 stacklevel=999,
270 )
271
272 yield
273 return
274
275 print("**********************", file=_standard_error_stream)
276 print("* Accelerated build *", file=_standard_error_stream)
277 print("**********************", file=_standard_error_stream)
278 if not IS_CPYTHON:
279 _warn_that(
280 'Building C-extensions under the runtimes other than CPython is '
281 'unsupported and will likely fail. Consider passing the '
282 f'`{PURE_PYTHON_CONFIG_SETTING !s}` PEP 517 config setting.',
283 RuntimeWarning,
284 stacklevel=999,
285 )
286
287 build_dir_ctx = (
288 nullcontext() if build_inplace
289 else _in_temporary_directory(src_dir=Path.cwd().resolve())
290 )
291 with build_dir_ctx:
292 config = _get_local_cython_config()
293
294 cythonize_args = _make_cythonize_cli_args_from_config(config, cython_line_tracing_requested)
295 with _patched_cython_env(config['env'], cython_line_tracing_requested):
296 _cythonize_cli_cmd(cythonize_args)
297 with patched_distutils_cmd_install():
298 with patched_dist_has_ext_modules():
299 yield
300
301
302 @patched_dist_get_long_description()
303 def build_wheel(
304 wheel_directory: str,
305 config_settings: _ConfigDict | None = None,
306 metadata_directory: str | None = None,
307 ) -> str:
308 """Produce a built wheel.
309
310 This wraps the corresponding ``setuptools``' build backend hook.
311
312 :param wheel_directory: Directory to put the resulting wheel in.
313 :param config_settings: :pep:`517` config settings mapping.
314 :param metadata_directory: :file:`.dist-info` directory path.
315
316 """
317 with maybe_prebuild_c_extensions(
318 line_trace_cython_when_unset=False,
319 build_inplace=False,
320 config_settings=config_settings,
321 ):
322 return _setuptools_build_wheel(
323 wheel_directory=wheel_directory,
324 config_settings=config_settings,
325 metadata_directory=metadata_directory,
326 )
327
328
329 @patched_dist_get_long_description()
330 def build_editable(
331 wheel_directory: str,
332 config_settings: _ConfigDict | None = None,
333 metadata_directory: str | None = None,
334 ) -> str:
335 """Produce a built wheel for editable installs.
336
337 This wraps the corresponding ``setuptools``' build backend hook.
338
339 :param wheel_directory: Directory to put the resulting wheel in.
340 :param config_settings: :pep:`517` config settings mapping.
341 :param metadata_directory: :file:`.dist-info` directory path.
342
343 """
344 with maybe_prebuild_c_extensions(
345 line_trace_cython_when_unset=True,
346 build_inplace=True,
347 config_settings=config_settings,
348 ):
349 return _setuptools_build_editable(
350 wheel_directory=wheel_directory,
351 config_settings=config_settings,
352 metadata_directory=metadata_directory,
353 )
354
355
356 def get_requires_for_build_wheel(
357 config_settings: _ConfigDict | None = None,
358 ) -> list[str]:
359 """Determine additional requirements for building wheels.
360
361 :param config_settings: :pep:`517` config settings mapping.
362
363 """
364 is_pure_python_build = _make_pure_python(config_settings)
365
366 if not is_pure_python_build and not IS_CPYTHON:
367 _warn_that(
368 'Building C-extensions under the runtimes other than CPython is '
369 'unsupported and will likely fail. Consider passing the '
370 f'`{PURE_PYTHON_CONFIG_SETTING !s}` PEP 517 config setting.',
371 RuntimeWarning,
372 stacklevel=999,
373 )
374
375 if is_pure_python_build:
376 c_ext_build_deps = []
377 else:
378 c_ext_build_deps = ['Cython >= 3.1.1']
379
380 return _setuptools_get_requires_for_build_wheel(
381 config_settings=config_settings,
382 ) + c_ext_build_deps
383
384
385 build_sdist = patched_dist_get_long_description()(_setuptools_build_sdist)
386 get_requires_for_build_editable = get_requires_for_build_wheel
387 prepare_metadata_for_build_wheel = patched_dist_get_long_description()(
388 _setuptools_prepare_metadata_for_build_wheel,
389 )
390 prepare_metadata_for_build_editable = prepare_metadata_for_build_wheel