Debian Codegraph @

src/build/_builder.py

raw
1 # SPDX-License-Identifier: MIT
2
3 from __future__ import annotations
4
5
6 __lazy_modules__ = [
7 'contextlib',
8 'difflib',
9 f'{__spec__.parent}._compat',
10 f'{__spec__.parent}._exceptions',
11 f'{__spec__.parent}._util',
12 'os',
13 'pyproject_hooks',
14 'subprocess',
15 'sys',
16 'warnings',
17 'zipfile',
18 ]
19
20 import contextlib
21 import difflib
22 import os
23 import subprocess
24 import sys
25 import warnings
26 import zipfile
27
28 import pyproject_hooks
29
30 from . import _ctx, env
31 from ._compat import tomllib
32 from ._exceptions import (
33 BuildBackendException,
34 BuildException,
35 BuildSystemTableValidationError,
36 TypoWarning,
37 )
38 from ._util import check_dependency
39
40
41 TYPE_CHECKING = False
42
43 if TYPE_CHECKING:
44 import datetime
45
46 from collections.abc import Iterable, Iterator, Mapping, Sequence
47 from typing import TypedDict
48
49 if sys.version_info < (3, 11):
50 from typing_extensions import NotRequired, Self
51 else:
52 from typing import NotRequired, Self
53
54 from ._types import ConfigSettings, Distribution, StrPath, SubprocessRunner
55
56 # A value as produced by ``tomllib`` when parsing ``pyproject.toml``. Uses the covariant
57 # ``Sequence``/``Mapping`` so concrete literals (e.g. ``dict[str, list[str]]``) are assignable.
58 TOMLValue = (
59 str
60 | int
61 | float
62 | bool
63 | datetime.datetime
64 | datetime.date
65 | datetime.time
66 | Sequence['TOMLValue']
67 | Mapping[str, 'TOMLValue']
68 )
69
70 # The validated ``[build-system]`` table.
71 BuildSystemTable = TypedDict(
72 'BuildSystemTable',
73 {'requires': list[str], 'build-backend': str, 'backend-path': NotRequired[list[str]]},
74 )
75
76
77 _DEFAULT_BACKEND: BuildSystemTable = {
78 'build-backend': 'setuptools.build_meta:__legacy__',
79 'requires': ['setuptools >= 40.8.0'],
80 }
81
82
83 def _find_typo(dictionary: Iterable[str], expected: str) -> None:
84 for obj in dictionary:
85 if difflib.SequenceMatcher(None, expected, obj).ratio() >= 0.8:
86 warnings.warn(
87 f"Found '{obj}' in pyproject.toml, did you mean '{expected}'?",
88 TypoWarning,
89 stacklevel=2,
90 )
91
92
93 def _validate_source_directory(source_dir: StrPath) -> None:
94 if not os.path.isdir(source_dir):
95 msg = f'Source {source_dir} is not a directory'
96 raise BuildException(msg)
97 pyproject_toml = os.path.join(source_dir, 'pyproject.toml')
98 setup_py = os.path.join(source_dir, 'setup.py')
99 if not os.path.exists(pyproject_toml) and not os.path.exists(setup_py):
100 msg = f'Source {source_dir} does not appear to be a Python project: no pyproject.toml or setup.py'
101 raise BuildException(msg)
102
103
104 def _read_pyproject_toml(path: StrPath) -> Mapping[str, TOMLValue]:
105 try:
106 with open(path, 'rb') as f:
107 return tomllib.load(f)
108 except FileNotFoundError:
109 return {}
110 except PermissionError as e: # pragma: win32 no cover
111 msg = f"{e.strerror}: '{e.filename}'"
112 raise BuildException(msg) from None
113 except tomllib.TOMLDecodeError as e:
114 msg = f'Failed to parse {path}: {e}'
115 raise BuildException(msg) from None
116
117
118 def _parse_build_system_table(pyproject_toml: Mapping[str, TOMLValue]) -> BuildSystemTable:
119 # If pyproject.toml is missing (per PEP 517) or [build-system] is missing
120 # (per PEP 518), use default values
121 if 'build-system' not in pyproject_toml:
122 _find_typo(pyproject_toml, 'build-system')
123 # Return a fresh copy so callers mutating the result (e.g. the ``requires``
124 # list) cannot corrupt the shared default for later builders.
125 return {**_DEFAULT_BACKEND, 'requires': list(_DEFAULT_BACKEND['requires'])}
126
127 build_system = pyproject_toml['build-system']
128 if not isinstance(build_system, dict):
129 msg = '`build-system` must be a table'
130 raise BuildSystemTableValidationError(msg)
131
132 # If [build-system] is present, it must have a ``requires`` field (per PEP 518)
133 if 'requires' not in build_system:
134 _find_typo(build_system, 'requires')
135 msg = '`requires` is a required property'
136 raise BuildSystemTableValidationError(msg)
137 requires = build_system['requires']
138 if not isinstance(requires, list) or not all(isinstance(i, str) for i in requires):
139 msg = '`requires` must be an array of strings'
140 raise BuildSystemTableValidationError(msg)
141
142 table: BuildSystemTable = {
143 'requires': requires,
144 'build-backend': _DEFAULT_BACKEND['build-backend'],
145 }
146
147 match build_system:
148 case {'build-backend': str() as backend}:
149 table['build-backend'] = backend
150 case {'build-backend': _}:
151 msg = '`build-backend` must be a string'
152 raise BuildSystemTableValidationError(msg)
153 case _:
154 # If ``build-backend`` is missing, inject the legacy setuptools backend
155 # but leave ``requires`` intact to emulate pip
156 _find_typo(build_system, 'build-backend')
157
158 match build_system:
159 case {'backend-path': list() as backend_path} if all(isinstance(i, str) for i in backend_path):
160 table['backend-path'] = backend_path
161 case {'backend-path': _}:
162 msg = '`backend-path` must be an array of strings'
163 raise BuildSystemTableValidationError(msg)
164
165 unknown_props = build_system.keys() - {'requires', 'build-backend', 'backend-path'}
166 if unknown_props:
167 msg = f'Unknown properties: {", ".join(unknown_props)}'
168 raise BuildSystemTableValidationError(msg)
169
170 return table
171
172
173 def _validate_backend_path(source_dir: str, backend_paths: Sequence[str]) -> None:
174 for path in backend_paths:
175 resolved = os.path.join(source_dir, path)
176 if not os.path.isdir(resolved):
177 msg = f'`backend-path` entry {path!r} does not exist or is not a directory'
178 raise BuildSystemTableValidationError(msg)
179
180
181 def _wrap_subprocess_runner(runner: SubprocessRunner, env: env.IsolatedEnv) -> SubprocessRunner:
182 def _invoke_wrapped_runner(
183 cmd: Sequence[str], cwd: str | None = None, extra_environ: Mapping[str, str] | None = None
184 ) -> None:
185 runner(cmd, cwd, {**(env.make_extra_environ() or {}), **(extra_environ or {})})
186
187 return _invoke_wrapped_runner
188
189
190 class ProjectBuilder:
191 """
192 The PEP 517 consumer API.
193 """
194
195 def __init__(
196 self,
197 source_dir: StrPath,
198 python_executable: str = sys.executable,
199 runner: SubprocessRunner = pyproject_hooks.default_subprocess_runner,
200 ) -> None:
201 """
202 :param source_dir: The source directory
203 :param python_executable: The python executable where the backend lives
204 :param runner: Runner for backend subprocesses
205
206 The ``runner``, if provided, must accept the following arguments:
207
208 - ``cmd``: a list of strings representing the command and arguments to
209 execute, as would be passed to e.g. 'subprocess.check_call'.
210 - ``cwd``: a string representing the working directory that must be
211 used for the subprocess. Corresponds to the provided source_dir.
212 - ``extra_environ``: a dict mapping environment variable names to values
213 which must be set for the subprocess execution.
214
215 The default runner simply calls the backend hooks in a subprocess, writing backend output
216 to stdout/stderr.
217 """
218 self._source_dir: str = os.path.abspath(source_dir)
219 _validate_source_directory(source_dir)
220
221 self._python_executable = python_executable
222 self._runner = runner
223
224 pyproject_toml_path = os.path.join(source_dir, 'pyproject.toml')
225 self._build_system = _parse_build_system_table(_read_pyproject_toml(pyproject_toml_path))
226
227 self._backend = self._build_system['build-backend']
228
229 if backend_paths := self._build_system.get('backend-path'):
230 _validate_backend_path(self._source_dir, backend_paths)
231
232 self._hook = pyproject_hooks.BuildBackendHookCaller(
233 self._source_dir,
234 self._backend,
235 backend_path=self._build_system.get('backend-path'),
236 python_executable=self._python_executable,
237 runner=self._runner,
238 )
239
240 @classmethod
241 def from_isolated_env(
242 cls,
243 env: env.IsolatedEnv,
244 source_dir: StrPath,
245 runner: SubprocessRunner = pyproject_hooks.default_subprocess_runner,
246 ) -> Self:
247 return cls(
248 source_dir=source_dir,
249 python_executable=env.python_executable,
250 runner=_wrap_subprocess_runner(runner, env),
251 )
252
253 @property
254 def source_dir(self) -> str:
255 """Project source directory."""
256 return self._source_dir
257
258 @property
259 def python_executable(self) -> str:
260 """
261 The Python executable used to invoke the backend.
262 """
263 return self._python_executable
264
265 @property
266 def build_system_requires(self) -> set[str]:
267 """
268 The dependencies defined in the ``pyproject.toml``'s
269 ``build-system.requires`` field or the default build dependencies
270 if ``pyproject.toml`` is missing or ``build-system`` is undefined.
271 """
272 return set(self._build_system['requires'])
273
274 def get_requires_for_build(
275 self,
276 distribution: Distribution,
277 config_settings: ConfigSettings | None = None,
278 ) -> set[str]:
279 """
280 Return the dependencies defined by the backend in addition to
281 :attr:`build_system_requires` for a given distribution.
282
283 :param distribution: Distribution to get the dependencies of
284 (``sdist`` or ``wheel``)
285 :param config_settings: Config settings for the build backend
286 """
287 _ctx.log(f'Getting build dependencies for {distribution}...', kind=('step',))
288 hook_name = f'get_requires_for_build_{distribution}'
289 get_requires = getattr(self._hook, hook_name)
290
291 with self._handle_backend(hook_name):
292 return set(get_requires(config_settings))
293
294 def check_dependencies(
295 self,
296 distribution: Distribution,
297 config_settings: ConfigSettings | None = None,
298 ) -> set[tuple[str, ...]]:
299 """
300 Return the dependencies which are not satisfied from the combined set of
301 :attr:`build_system_requires` and :meth:`get_requires_for_build` for a given
302 distribution.
303
304 :param distribution: Distribution to check (``sdist`` or ``wheel``)
305 :param config_settings: Config settings for the build backend
306 :returns: Set of variable-length unmet dependency tuples
307 """
308 dependencies = self.get_requires_for_build(distribution, config_settings).union(self.build_system_requires)
309 return {u for d in dependencies for u in check_dependency(d)}
310
311 def prepare(
312 self,
313 distribution: Distribution,
314 output_directory: StrPath,
315 config_settings: ConfigSettings | None = None,
316 ) -> str | None:
317 """
318 Prepare metadata for a distribution.
319
320 :param distribution: Distribution to build (must be ``wheel``)
321 :param output_directory: Directory to put the prepared metadata in
322 :param config_settings: Config settings for the build backend
323 :returns: The full path to the prepared metadata directory
324 """
325 _ctx.log(f'Getting metadata for {distribution}...', kind=('step',))
326 try:
327 return self._call_backend(
328 f'prepare_metadata_for_build_{distribution}',
329 output_directory,
330 config_settings,
331 _allow_fallback=False,
332 )
333 except BuildBackendException as exception:
334 if isinstance(exception.exception, pyproject_hooks.HookMissing):
335 return None
336 raise
337
338 def build(
339 self,
340 distribution: Distribution,
341 output_directory: StrPath,
342 config_settings: ConfigSettings | None = None,
343 metadata_directory: str | None = None,
344 ) -> str:
345 """
346 Build a distribution.
347
348 :param distribution: Distribution to build (``sdist`` or ``wheel``)
349 :param output_directory: Directory to put the built distribution in
350 :param config_settings: Config settings for the build backend
351 :param metadata_directory: If provided, should be the return value of a
352 previous ``prepare`` call on the same ``distribution`` kind
353 :returns: The full path to the built distribution
354 """
355 _ctx.log(f'Building {distribution}...', kind=('step',))
356
357 kwargs = {} if metadata_directory is None else {'metadata_directory': metadata_directory}
358 return self._call_backend(f'build_{distribution}', output_directory, config_settings, **kwargs)
359
360 def metadata_path(self, output_directory: StrPath) -> str:
361 """
362 Generate the metadata directory of a distribution and return its path.
363
364 If the backend does not support the ``prepare_metadata_for_build_wheel``
365 hook, a wheel will be built and the metadata will be extracted from it.
366
367 :param output_directory: Directory to put the metadata distribution in
368 :returns: The path of the metadata directory
369 """
370 # prepare_metadata hook
371 metadata = self.prepare('wheel', output_directory)
372 if metadata is not None:
373 return metadata
374
375 # fallback to build_wheel hook
376 wheel = self.build('wheel', output_directory)
377 try:
378 whl = zipfile.ZipFile(wheel)
379 except (OSError, zipfile.BadZipFile) as exception:
380 msg = 'Invalid wheel'
381 raise BuildException(msg) from exception
382
383 with whl:
384 names = whl.namelist()
385 # The dist-info directory name cannot be reliably derived from the wheel filename (e.g. a build
386 # tag makes the filename ambiguous), so find it by inspecting the wheel's contents instead.
387 metadata_names = [name for name in names if name.count('/') == 1 and name.endswith('.dist-info/METADATA')]
388 if len(metadata_names) != 1:
389 msg = 'Invalid wheel'
390 raise BuildException(msg)
391 distinfo = metadata_names[0].rsplit('/', 1)[0]
392 member_prefix = f'{distinfo}/'
393 whl.extractall(
394 output_directory,
395 (member for member in names if member.startswith(member_prefix)),
396 )
397 return os.path.join(output_directory, distinfo)
398
399 def _call_backend(
400 self, hook_name: str, outdir: StrPath, config_settings: ConfigSettings | None = None, **kwargs: str | bool
401 ) -> str:
402 outdir = os.path.abspath(outdir)
403
404 callback = getattr(self._hook, hook_name)
405
406 try:
407 os.makedirs(outdir, exist_ok=True)
408 except FileExistsError:
409 msg = f"Build path '{outdir}' exists and is not a directory"
410 raise BuildException(msg) from None
411 except (NotADirectoryError, FileNotFoundError):
412 msg = f"Build path '{outdir}' does not exist and cannot be a directory"
413 raise BuildException(msg) from None
414
415 with self._handle_backend(hook_name):
416 basename: str = callback(outdir, config_settings, **kwargs)
417
418 return os.path.join(outdir, basename)
419
420 @contextlib.contextmanager
421 def _handle_backend(self, hook: str) -> Iterator[None]:
422 try:
423 yield
424 except pyproject_hooks.BackendUnavailable as exception:
425 raise BuildBackendException(
426 exception,
427 f"Backend '{self._backend}' is not available.",
428 sys.exc_info(),
429 ) from None
430 except subprocess.CalledProcessError as exception:
431 raise BuildBackendException(exception, f'Backend subprocess exited when trying to invoke {hook}') from None
432 except Exception as exception:
433 raise BuildBackendException(exception, exc_info=sys.exc_info()) from None