| 1 |
# SPDX-License-Identifier: MIT |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
|
| 6 |
__lazy_modules__ = [ |
| 7 |
'argparse', |
| 8 |
'build._compat', |
| 9 |
'build._compat.tarfile', |
| 10 |
'build._exceptions', |
| 11 |
'build._util', |
| 12 |
'build.env', |
| 13 |
'functools', |
| 14 |
'hashlib', |
| 15 |
'json', |
| 16 |
'os', |
| 17 |
'packaging', |
| 18 |
'packaging.utils', |
| 19 |
'packaging.version', |
| 20 |
'platform', |
| 21 |
'pyproject_hooks', |
| 22 |
'shutil', |
| 23 |
'subprocess', |
| 24 |
'tarfile', |
| 25 |
'tempfile', |
| 26 |
'textwrap', |
| 27 |
'traceback', |
| 28 |
'warnings', |
| 29 |
'zipfile', |
| 30 |
] |
| 31 |
|
| 32 |
import argparse |
| 33 |
import contextlib |
| 34 |
import contextvars |
| 35 |
import hashlib |
| 36 |
import json |
| 37 |
import os |
| 38 |
import platform |
| 39 |
import shutil |
| 40 |
import subprocess |
| 41 |
import sys |
| 42 |
import tempfile |
| 43 |
import textwrap |
| 44 |
import traceback |
| 45 |
import warnings |
| 46 |
import zipfile |
| 47 |
|
| 48 |
from functools import partial |
| 49 |
from tarfile import TarError |
| 50 |
from tarfile import open as tar_open |
| 51 |
from typing import NoReturn, TextIO, TypedDict, cast |
| 52 |
|
| 53 |
import pyproject_hooks |
| 54 |
|
| 55 |
from packaging.utils import InvalidSdistFilename, parse_sdist_filename |
| 56 |
from packaging.version import InvalidVersion |
| 57 |
|
| 58 |
import build |
| 59 |
import build.env as _env |
| 60 |
|
| 61 |
from build import ProjectBuilder, _ctx |
| 62 |
from build._compat.tarfile import safe_extractall |
| 63 |
from build._exceptions import BuildBackendException, BuildException, FailedProcessError |
| 64 |
from build._util import format_unmet_dependencies |
| 65 |
from build.env import DefaultIsolatedEnv |
| 66 |
|
| 67 |
|
| 68 |
TYPE_CHECKING = False |
| 69 |
|
| 70 |
if TYPE_CHECKING: |
| 71 |
from collections.abc import Iterator, Mapping, Sequence |
| 72 |
|
| 73 |
from build._types import ConfigSettings, Distribution, StrPath, SubprocessRunner |
| 74 |
|
| 75 |
# A decoded JSON value, as produced by ``--config-json``. Uses the covariant ``Sequence``/``Mapping`` |
| 76 |
# so the ``str | list[str]`` settings from ``--config-setting`` are also assignable to it. |
| 77 |
JSONValue = str | int | float | bool | None | Sequence['JSONValue'] | Mapping[str, 'JSONValue'] |
| 78 |
|
| 79 |
class _Args(argparse.Namespace): |
| 80 |
"""The arguments :func:`main_parser` produces, typed for the rest of the module.""" |
| 81 |
|
| 82 |
srcdir: str |
| 83 |
verbosity: int |
| 84 |
outdir: str | None |
| 85 |
distributions: list[Distribution] | None |
| 86 |
metadata: bool |
| 87 |
config_settings: list[str] | None |
| 88 |
config_json: str | None |
| 89 |
installer: _env.Installer |
| 90 |
no_isolation: bool |
| 91 |
dependency_constraints_txt: str | None |
| 92 |
skip_dependency_check: bool |
| 93 |
sdist_extract_dir: str | None |
| 94 |
env_dir: str | None |
| 95 |
report: str | None |
| 96 |
|
| 97 |
|
| 98 |
_COLORS = { |
| 99 |
'red': '\33[91m', |
| 100 |
'green': '\33[92m', |
| 101 |
'yellow': '\33[93m', |
| 102 |
'bold': '\33[1m', |
| 103 |
'dim': '\33[2m', |
| 104 |
'underline': '\33[4m', |
| 105 |
'reset': '\33[0m', |
| 106 |
} |
| 107 |
_NO_COLORS = dict.fromkeys(_COLORS, '') |
| 108 |
|
| 109 |
|
| 110 |
_DEFAULT_STYLES = {'stdout': _COLORS, 'stderr': _COLORS} |
| 111 |
_styles = contextvars.ContextVar('_styles', default=_DEFAULT_STYLES) |
| 112 |
|
| 113 |
|
| 114 |
def _init_colors() -> None: |
| 115 |
match os.environ: |
| 116 |
case {'NO_COLOR': _, 'FORCE_COLOR': _}: |
| 117 |
warnings.warn('Both NO_COLOR and FORCE_COLOR environment variables are set, disabling color', stacklevel=2) |
| 118 |
_styles.set({'stdout': _NO_COLORS, 'stderr': _NO_COLORS}) |
| 119 |
case {'NO_COLOR': _}: |
| 120 |
_styles.set({'stdout': _NO_COLORS, 'stderr': _NO_COLORS}) |
| 121 |
case {'FORCE_COLOR': _}: |
| 122 |
_styles.set({'stdout': _COLORS, 'stderr': _COLORS}) |
| 123 |
case _: |
| 124 |
_styles.set( |
| 125 |
{ |
| 126 |
'stdout': _COLORS if sys.stdout.isatty() else _NO_COLORS, |
| 127 |
'stderr': _COLORS if sys.stderr.isatty() else _NO_COLORS, |
| 128 |
} |
| 129 |
) |
| 130 |
|
| 131 |
|
| 132 |
def _cprint(fmt: str = '', msg: str = '', file: TextIO | None = None) -> None: |
| 133 |
stream = file or sys.stdout |
| 134 |
key = 'stderr' if stream is sys.stderr else 'stdout' |
| 135 |
print(fmt.format(msg, **_styles.get()[key]), file=file, flush=True) |
| 136 |
|
| 137 |
|
| 138 |
def _showwarning( |
| 139 |
message: Warning | str, |
| 140 |
category: type[Warning], # noqa: ARG001 |
| 141 |
filename: str, # noqa: ARG001 |
| 142 |
lineno: int, # noqa: ARG001 |
| 143 |
file: TextIO | None = None, |
| 144 |
line: str | None = None, # noqa: ARG001 |
| 145 |
) -> None: |
| 146 |
_cprint('{yellow}WARNING{reset} {}', str(message), file if file is not None else sys.stderr) |
| 147 |
|
| 148 |
|
| 149 |
def _make_logger() -> _ctx.Logger: |
| 150 |
max_terminal_width = shutil.get_terminal_size().columns - 2 |
| 151 |
if max_terminal_width <= 0: # pragma: no cover |
| 152 |
max_terminal_width = 78 |
| 153 |
|
| 154 |
fill = partial(textwrap.fill, subsequent_indent=' ', width=max_terminal_width) |
| 155 |
|
| 156 |
def emit(message: str, *, indent: str, style: str = '{}') -> None: |
| 157 |
for line in message.splitlines(): |
| 158 |
_cprint(style, fill(line, initial_indent=indent), file=sys.stderr) |
| 159 |
|
| 160 |
# Nested so it cannot be called directly, bypassing the logger setup above. |
| 161 |
def log(message: str, *, kind: tuple[str, ...] | None = None) -> None: |
| 162 |
if _ctx.verbosity < -1: |
| 163 |
return |
| 164 |
match kind: |
| 165 |
case ('step', *_): |
| 166 |
first, _, rest = message.partition('\n') |
| 167 |
_cprint('{bold}{}{reset}', fill(first, initial_indent='* '), file=sys.stderr) |
| 168 |
emit(rest, indent=' ') |
| 169 |
case ('subprocess', 'cmd'): |
| 170 |
emit(message, indent='> ', style='{dim}{}{reset}') |
| 171 |
case ('subprocess', 'stdout' | 'stderr'): |
| 172 |
emit(message, indent='< ', style='{dim}{}{reset}') |
| 173 |
case _: |
| 174 |
emit(message, indent=' ') |
| 175 |
|
| 176 |
return log |
| 177 |
|
| 178 |
|
| 179 |
def _setup_cli(*, verbosity: int) -> None: |
| 180 |
warnings.showwarning = _showwarning |
| 181 |
|
| 182 |
if platform.system() == 'Windows': |
| 183 |
try: |
| 184 |
import colorama |
| 185 |
|
| 186 |
colorama.init() |
| 187 |
except ModuleNotFoundError: |
| 188 |
pass |
| 189 |
|
| 190 |
_init_colors() |
| 191 |
|
| 192 |
_ctx.LOGGER.set(_make_logger()) |
| 193 |
_ctx.VERBOSITY.set(verbosity) |
| 194 |
|
| 195 |
|
| 196 |
def _error(msg: str, code: int = 1) -> NoReturn: # pragma: no cover |
| 197 |
""" |
| 198 |
Print an error message and exit. Will color the output when writing to a TTY. |
| 199 |
|
| 200 |
:param msg: Error message |
| 201 |
:param code: Error code |
| 202 |
""" |
| 203 |
_cprint('{red}ERROR{reset} {}', msg, file=sys.stderr) |
| 204 |
raise SystemExit(code) |
| 205 |
|
| 206 |
|
| 207 |
@contextlib.contextmanager |
| 208 |
def _bootstrap_build_env( |
| 209 |
isolation: bool, |
| 210 |
srcdir: StrPath, |
| 211 |
distribution: Distribution, |
| 212 |
config_settings: ConfigSettings | None, |
| 213 |
skip_dependency_check: bool, |
| 214 |
dependency_constraints_txt: os.PathLike[str] | None, |
| 215 |
installer: _env.Installer, |
| 216 |
env_dir: str | None = None, |
| 217 |
runner: SubprocessRunner | None = None, |
| 218 |
) -> Iterator[ProjectBuilder]: |
| 219 |
runner = runner or pyproject_hooks.default_subprocess_runner |
| 220 |
if isolation: |
| 221 |
with DefaultIsolatedEnv(installer=installer, path=env_dir) as env: |
| 222 |
builder = ProjectBuilder.from_isolated_env(env, srcdir, runner=runner) |
| 223 |
|
| 224 |
install = env.install |
| 225 |
if dependency_constraints_txt: |
| 226 |
with open(dependency_constraints_txt, encoding='utf-8') as dependency_constraints_file: |
| 227 |
install = partial(install, constraints=set(map(str.strip, dependency_constraints_file))) |
| 228 |
|
| 229 |
# first install the build dependencies |
| 230 |
install(builder.build_system_requires, _fresh=True) |
| 231 |
# then get the extra required dependencies from the backend (which was installed in the call above :P) |
| 232 |
extra_requires = builder.get_requires_for_build(distribution, config_settings) |
| 233 |
install(extra_requires) |
| 234 |
|
| 235 |
_log_dependency_versions(env, builder.build_system_requires | extra_requires) |
| 236 |
|
| 237 |
yield builder |
| 238 |
|
| 239 |
else: |
| 240 |
builder = ProjectBuilder(srcdir, runner=runner) |
| 241 |
|
| 242 |
if not skip_dependency_check and (missing := builder.check_dependencies(distribution, config_settings)): |
| 243 |
_cprint() |
| 244 |
_error(format_unmet_dependencies(missing)) |
| 245 |
|
| 246 |
yield builder |
| 247 |
|
| 248 |
|
| 249 |
def _log_dependency_versions(env: DefaultIsolatedEnv, requirements: set[str]) -> None: |
| 250 |
if versions := env.installed_versions(requirements): |
| 251 |
_ctx.log( |
| 252 |
'Installed build dependency versions:\n' |
| 253 |
+ '\n'.join(f'- {name}=={version}' for name, version in sorted(versions.items())), |
| 254 |
kind=('step',), |
| 255 |
) |
| 256 |
|
| 257 |
|
| 258 |
def _build( |
| 259 |
isolation: bool, |
| 260 |
srcdir: StrPath, |
| 261 |
outdir: StrPath, |
| 262 |
distribution: Distribution, |
| 263 |
config_settings: ConfigSettings | None, |
| 264 |
skip_dependency_check: bool, |
| 265 |
dependency_constraints_txt: os.PathLike[str] | None, |
| 266 |
installer: _env.Installer, |
| 267 |
env_dir: str | None = None, |
| 268 |
) -> str: |
| 269 |
with _bootstrap_build_env( |
| 270 |
isolation, |
| 271 |
srcdir, |
| 272 |
distribution, |
| 273 |
config_settings, |
| 274 |
skip_dependency_check, |
| 275 |
dependency_constraints_txt, |
| 276 |
installer, |
| 277 |
env_dir, |
| 278 |
pyproject_hooks.quiet_subprocess_runner if _ctx.verbosity < 0 else None, |
| 279 |
) as builder: |
| 280 |
return builder.build(distribution, outdir, config_settings) |
| 281 |
|
| 282 |
|
| 283 |
@contextlib.contextmanager |
| 284 |
def _handle_build_error(*, env_dir: str | None, sdist_extract_dir: StrPath | None) -> Iterator[None]: |
| 285 |
try: |
| 286 |
yield |
| 287 |
except (BuildException, FailedProcessError) as e: |
| 288 |
_error(str(e)) |
| 289 |
except BuildBackendException as e: |
| 290 |
hint = _build_failure_hint(env_dir, sdist_extract_dir) |
| 291 |
if isinstance(e.exception, subprocess.CalledProcessError): |
| 292 |
_cprint() |
| 293 |
_cprint('{yellow}TIP{reset} {}', hint, file=sys.stderr) |
| 294 |
_error(str(e)) |
| 295 |
|
| 296 |
if e.exc_info[0] is not None: |
| 297 |
tb_lines = traceback.format_exception(e.exc_info[0], e.exc_info[1], e.exc_info[2], limit=-1) |
| 298 |
tb = ''.join(tb_lines) |
| 299 |
else: # pragma: no cover |
| 300 |
tb = traceback.format_exc(limit=-1) |
| 301 |
_cprint('\n{dim}{}{reset}\n', tb.strip('\n')) |
| 302 |
_cprint('{yellow}TIP{reset} {}', hint, file=sys.stderr) |
| 303 |
_error(str(e)) |
| 304 |
except Exception as e: # pragma: no cover |
| 305 |
tb = traceback.format_exc().strip('\n') |
| 306 |
_cprint('\n{dim}{}{reset}\n', tb) |
| 307 |
_error(str(e)) |
| 308 |
|
| 309 |
|
| 310 |
def _build_failure_hint(env_dir: str | None, sdist_extract_dir: StrPath | None) -> str: |
| 311 |
kept = [ |
| 312 |
f'{label} at {os.fspath(path)}' |
| 313 |
for path, label in ((env_dir, 'the build environment'), (sdist_extract_dir, 'the extracted sources')) |
| 314 |
if path is not None |
| 315 |
] |
| 316 |
if kept: |
| 317 |
action = f'inspect {" and ".join(kept)}' |
| 318 |
else: |
| 319 |
action = 'pass --env-dir and --sdist-extract-dir to keep the build environment and sources' |
| 320 |
docs = 'https://build.pypa.io/en/stable/how-to/troubleshooting.html#debug-a-failed-build' |
| 321 |
return f'{action}, then see {docs} for help debugging a failed build' |
| 322 |
|
| 323 |
|
| 324 |
def _natural_language_list(elements: Sequence[str]) -> str: |
| 325 |
if len(elements) == 0: |
| 326 |
msg = 'no elements' |
| 327 |
raise IndexError(msg) |
| 328 |
if len(elements) == 1: |
| 329 |
return elements[0] |
| 330 |
return '{} and {}'.format( |
| 331 |
', '.join(elements[:-1]), |
| 332 |
elements[-1], |
| 333 |
) |
| 334 |
|
| 335 |
|
| 336 |
def build_package( |
| 337 |
srcdir: StrPath, |
| 338 |
outdir: StrPath, |
| 339 |
distributions: Sequence[Distribution], |
| 340 |
config_settings: ConfigSettings | None = None, |
| 341 |
isolation: bool = True, |
| 342 |
skip_dependency_check: bool = False, |
| 343 |
dependency_constraints_txt: os.PathLike[str] | None = None, |
| 344 |
installer: _env.Installer = 'pip', |
| 345 |
env_dir: str | None = None, |
| 346 |
) -> list[str]: |
| 347 |
""" |
| 348 |
Run the build process. |
| 349 |
|
| 350 |
:param srcdir: Source directory |
| 351 |
:param outdir: Output directory |
| 352 |
:param distribution: Distribution to build (sdist or wheel) |
| 353 |
:param config_settings: Configuration settings to be passed to the backend |
| 354 |
:param isolation: Isolate the build in a separate environment |
| 355 |
:param skip_dependency_check: Do not perform the dependency check |
| 356 |
:param env_dir: Location of the isolated build environment (a temporary directory is used when not set) |
| 357 |
""" |
| 358 |
built: list[str] = [] |
| 359 |
for distribution in distributions: |
| 360 |
out = _build( |
| 361 |
isolation, |
| 362 |
srcdir, |
| 363 |
outdir, |
| 364 |
distribution, |
| 365 |
config_settings, |
| 366 |
skip_dependency_check, |
| 367 |
dependency_constraints_txt, |
| 368 |
installer, |
| 369 |
env_dir, |
| 370 |
) |
| 371 |
built.append(os.path.basename(out)) |
| 372 |
return built |
| 373 |
|
| 374 |
|
| 375 |
def build_package_via_sdist( |
| 376 |
srcdir: StrPath, |
| 377 |
outdir: StrPath, |
| 378 |
distributions: Sequence[Distribution], |
| 379 |
config_settings: ConfigSettings | None = None, |
| 380 |
isolation: bool = True, |
| 381 |
skip_dependency_check: bool = False, |
| 382 |
dependency_constraints_txt: os.PathLike[str] | None = None, |
| 383 |
installer: _env.Installer = 'pip', |
| 384 |
sdist_extract_dir: StrPath | None = None, |
| 385 |
env_dir: str | None = None, |
| 386 |
) -> list[str]: |
| 387 |
""" |
| 388 |
Build a sdist and then the specified distributions from it. |
| 389 |
|
| 390 |
:param srcdir: Source directory |
| 391 |
:param outdir: Output directory |
| 392 |
:param distribution: Distribution to build (only wheel) |
| 393 |
:param config_settings: Configuration settings to be passed to the backend |
| 394 |
:param isolation: Isolate the build in a separate environment |
| 395 |
:param skip_dependency_check: Do not perform the dependency check |
| 396 |
:param sdist_extract_dir: Directory to extract the intermediate sdist into; a temporary directory is used and |
| 397 |
removed afterwards when ``None`` |
| 398 |
:param env_dir: Location of the isolated build environment (a temporary directory is used when not set) |
| 399 |
""" |
| 400 |
if 'sdist' in distributions: |
| 401 |
msg = 'Only binary distributions are allowed but sdist was specified' |
| 402 |
raise ValueError(msg) |
| 403 |
|
| 404 |
sdist = _build( |
| 405 |
isolation, |
| 406 |
srcdir, |
| 407 |
outdir, |
| 408 |
'sdist', |
| 409 |
config_settings, |
| 410 |
skip_dependency_check, |
| 411 |
dependency_constraints_txt, |
| 412 |
installer, |
| 413 |
env_dir, |
| 414 |
) |
| 415 |
|
| 416 |
sdist_name = os.path.basename(sdist) |
| 417 |
built: list[str] = [] |
| 418 |
if distributions: |
| 419 |
top_level = _validate_sdist_archive(sdist) |
| 420 |
with _extract_sdist(sdist, top_level, extract_dir=sdist_extract_dir) as extracted_srcdir: |
| 421 |
_ctx.log(f'Building {_natural_language_list(distributions)} from sdist', kind=('step',)) |
| 422 |
for distribution in distributions: |
| 423 |
out = _build( |
| 424 |
isolation, |
| 425 |
extracted_srcdir, |
| 426 |
outdir, |
| 427 |
distribution, |
| 428 |
config_settings, |
| 429 |
skip_dependency_check, |
| 430 |
dependency_constraints_txt, |
| 431 |
installer, |
| 432 |
env_dir, |
| 433 |
) |
| 434 |
built.append(os.path.basename(out)) |
| 435 |
return [sdist_name, *built] |
| 436 |
|
| 437 |
|
| 438 |
def _build_metadata( |
| 439 |
srcdir: StrPath, |
| 440 |
outdir: StrPath, # noqa: ARG001 |
| 441 |
distributions: Sequence[Distribution], # noqa: ARG001 |
| 442 |
config_settings: ConfigSettings | None = None, |
| 443 |
isolation: bool = True, |
| 444 |
skip_dependency_check: bool = False, |
| 445 |
dependency_constraints_txt: os.PathLike[str] | None = None, |
| 446 |
installer: _env.Installer = 'pip', |
| 447 |
env_dir: str | None = None, |
| 448 |
) -> list[str]: |
| 449 |
if os.path.isfile(srcdir) and os.fspath(srcdir).lower().endswith('.whl'): |
| 450 |
_print_metadata(_wheel_metadata(srcdir)) |
| 451 |
return [] |
| 452 |
|
| 453 |
def run_subprocess(cmd: Sequence[StrPath], cwd: str | None = None, extra_environ: Mapping[str, str] | None = None) -> None: |
| 454 |
env = os.environ.copy() |
| 455 |
if extra_environ: |
| 456 |
env.update(extra_environ) |
| 457 |
_ctx.run_subprocess(cmd, cwd, env) |
| 458 |
|
| 459 |
with ( |
| 460 |
_bootstrap_build_env( |
| 461 |
isolation, |
| 462 |
srcdir, |
| 463 |
'wheel', |
| 464 |
config_settings, |
| 465 |
skip_dependency_check, |
| 466 |
dependency_constraints_txt, |
| 467 |
installer, |
| 468 |
env_dir, |
| 469 |
runner=run_subprocess, |
| 470 |
) as builder, |
| 471 |
tempfile.TemporaryDirectory() as tempdir, |
| 472 |
open( |
| 473 |
os.path.join(builder.metadata_path(tempdir), 'METADATA'), |
| 474 |
'rb', |
| 475 |
) as metadata_file, |
| 476 |
): |
| 477 |
_print_metadata(metadata_file.read()) |
| 478 |
|
| 479 |
return [] |
| 480 |
|
| 481 |
|
| 482 |
def _wheel_metadata(wheel: StrPath) -> bytes: |
| 483 |
with zipfile.ZipFile(wheel) as archive: |
| 484 |
names = [name for name in archive.namelist() if name.count('/') == 1 and name.endswith('.dist-info/METADATA')] |
| 485 |
if len(names) != 1: |
| 486 |
msg = f'{os.fspath(wheel)!r} is not a valid wheel: expected one .dist-info/METADATA, found {len(names)}' |
| 487 |
raise BuildException(msg) |
| 488 |
return archive.read(names[0]) |
| 489 |
|
| 490 |
|
| 491 |
def _print_metadata(raw_metadata: bytes) -> None: |
| 492 |
import packaging.metadata |
| 493 |
|
| 494 |
valid_metadata, _ = packaging.metadata.parse_email(raw_metadata) |
| 495 |
print( # noqa: T201 |
| 496 |
json.dumps(valid_metadata, ensure_ascii=False, indent=2), |
| 497 |
) |
| 498 |
|
| 499 |
|
| 500 |
def main_parser() -> argparse.ArgumentParser: |
| 501 |
""" |
| 502 |
Construct the main parser. |
| 503 |
""" |
| 504 |
|
| 505 |
class NegativeCountAction(argparse.Action): |
| 506 |
def __init__( |
| 507 |
self, |
| 508 |
option_strings: Sequence[str], |
| 509 |
dest: str, |
| 510 |
default: int | None = None, |
| 511 |
help: str | None = None, |
| 512 |
) -> None: |
| 513 |
super().__init__( |
| 514 |
option_strings=option_strings, |
| 515 |
dest=dest, |
| 516 |
nargs=0, |
| 517 |
default=default, |
| 518 |
help=help, |
| 519 |
) |
| 520 |
|
| 521 |
def __call__( |
| 522 |
self, |
| 523 |
parser: argparse.ArgumentParser, # noqa: ARG002 |
| 524 |
namespace: argparse.Namespace, |
| 525 |
values: str | Sequence[str] | None, # noqa: ARG002 |
| 526 |
option_string: str | None = None, # noqa: ARG002 |
| 527 |
) -> None: |
| 528 |
setattr(namespace, self.dest, getattr(namespace, self.dest, 0) - 1) |
| 529 |
|
| 530 |
make_parser = partial( |
| 531 |
argparse.ArgumentParser, |
| 532 |
add_help=False, |
| 533 |
description="""\ |
| 534 |
A simple, correct Python build frontend. |
| 535 |
|
| 536 |
By default, a source distribution (sdist) is built from the project root |
| 537 |
and a binary distribution (wheel) is built from the sdist. |
| 538 |
If this is undesirable, you can pass `--sdist` and/or `--wheel` |
| 539 |
to build distributions independently of each other. |
| 540 |
""".rstrip(), |
| 541 |
# Prevent argparse from taking up the entire width of the terminal window |
| 542 |
# which impedes readability. Also keep the description formatted. |
| 543 |
formatter_class=argparse.RawDescriptionHelpFormatter, |
| 544 |
) |
| 545 |
if sys.version_info >= (3, 14): # pragma: no branch |
| 546 |
make_parser = partial(make_parser, suggest_on_error=True) # pragma: no cover |
| 547 |
|
| 548 |
parser = make_parser() |
| 549 |
parser.add_argument( |
| 550 |
'srcdir', |
| 551 |
type=str, |
| 552 |
nargs='?', |
| 553 |
default=os.getcwd(), |
| 554 |
help='source directory, .tar.gz source distribution, or (with --metadata) a .whl to read metadata from ' |
| 555 |
'(defaults to the current working directory)', |
| 556 |
) |
| 557 |
|
| 558 |
global_group = parser.add_argument_group('global options') |
| 559 |
global_group.add_argument( |
| 560 |
'-h', |
| 561 |
'--help', |
| 562 |
action='help', |
| 563 |
default=argparse.SUPPRESS, |
| 564 |
help='show this help message and exit', |
| 565 |
) |
| 566 |
global_group.add_argument( |
| 567 |
'--version', |
| 568 |
'-V', |
| 569 |
action='version', |
| 570 |
version=f'build {build.__version__} ({",".join(build.__path__)})', |
| 571 |
) |
| 572 |
verbosity_exclusive_group = global_group.add_mutually_exclusive_group() |
| 573 |
verbosity_exclusive_group.add_argument( |
| 574 |
'--quiet', |
| 575 |
'-q', |
| 576 |
dest='verbosity', |
| 577 |
action=NegativeCountAction, |
| 578 |
default=0, |
| 579 |
help='reduce verbosity', |
| 580 |
) |
| 581 |
verbosity_exclusive_group.add_argument( |
| 582 |
'--verbose', |
| 583 |
'-v', |
| 584 |
dest='verbosity', |
| 585 |
action='count', |
| 586 |
default=0, |
| 587 |
help='increase verbosity', |
| 588 |
) |
| 589 |
|
| 590 |
build_group = parser.add_argument_group('build options') |
| 591 |
build_group.add_argument( |
| 592 |
'--outdir', |
| 593 |
'-o', |
| 594 |
help=f'output directory (defaults to {{srcdir}}{os.sep}dist). Cannot be used together with ``--metadata``', |
| 595 |
metavar='PATH', |
| 596 |
) |
| 597 |
build_group.add_argument( |
| 598 |
'--sdist-extract-dir', |
| 599 |
help='extract the intermediate sdist to PATH (created if missing and kept afterwards) instead of a random ' |
| 600 |
'temporary directory; reusing it across rebuilds gives compiler caches such as ccache/sccache a stable ' |
| 601 |
'source path. Only affects the default (via-sdist) build and building a wheel from an sdist', |
| 602 |
metavar='PATH', |
| 603 |
) |
| 604 |
build_group.add_argument( |
| 605 |
'--sdist', |
| 606 |
'-s', |
| 607 |
dest='distributions', |
| 608 |
action='append_const', |
| 609 |
const='sdist', |
| 610 |
help='build a source distribution (disables the default behavior)', |
| 611 |
) |
| 612 |
build_group.add_argument( |
| 613 |
'--wheel', |
| 614 |
'-w', |
| 615 |
dest='distributions', |
| 616 |
action='append_const', |
| 617 |
const='wheel', |
| 618 |
help='build a wheel (disables the default behavior)', |
| 619 |
) |
| 620 |
build_group.add_argument( |
| 621 |
'--metadata', |
| 622 |
action='store_true', |
| 623 |
help="print out a wheel's metadata in JSON format, building it first unless the source argument is already a " |
| 624 |
'.whl. Cannot be used in conjunction with ``--sdist`` or ``--wheel``', |
| 625 |
) |
| 626 |
build_group.add_argument( |
| 627 |
'--report', |
| 628 |
help='write a machine-readable JSON report of the built artifacts (name, path, kind, size and SHA-256 hash) ' |
| 629 |
'to this path. Cannot be used together with ``--metadata``', |
| 630 |
metavar='PATH', |
| 631 |
) |
| 632 |
config_exclusive_group = build_group.add_mutually_exclusive_group() |
| 633 |
config_exclusive_group.add_argument( |
| 634 |
'--config-setting', |
| 635 |
'-C', |
| 636 |
dest='config_settings', |
| 637 |
action='append', |
| 638 |
help='settings to pass to the backend. Multiple settings can be provided. ' |
| 639 |
'Settings beginning with a hyphen will erroneously be interpreted as options to build if separated ' |
| 640 |
'by a space; use ``--config-setting=--my-setting -C--my-other-setting`` instead. ' |
| 641 |
'A setting passed without ``=VALUE`` is given an empty value, but this form is not supported by pip; ' |
| 642 |
'write ``KEY=`` instead for compatibility', |
| 643 |
metavar='KEY=[VALUE]', |
| 644 |
) |
| 645 |
config_exclusive_group.add_argument( |
| 646 |
'--config-json', |
| 647 |
help='settings to pass to the backend as a JSON object. ' |
| 648 |
'This is an alternative to ``--config-setting`` that allows complex nested structures. ' |
| 649 |
'Cannot be used together with ``--config-setting``', |
| 650 |
metavar='JSON_STRING', |
| 651 |
) |
| 652 |
|
| 653 |
install_group = parser.add_argument_group('installation options') |
| 654 |
env_exclusive_group = install_group.add_mutually_exclusive_group() |
| 655 |
env_exclusive_group.add_argument( |
| 656 |
'--installer', |
| 657 |
choices=_env.INSTALLERS, |
| 658 |
default='pip', |
| 659 |
help='Python package installer to use (defaults to pip)', |
| 660 |
) |
| 661 |
env_exclusive_group.add_argument( |
| 662 |
'--no-isolation', |
| 663 |
'-n', |
| 664 |
action='store_true', |
| 665 |
help='disable building the project in an isolated virtual environment. ' |
| 666 |
'Build dependencies must be installed separately when this option is used', |
| 667 |
) |
| 668 |
install_group.add_argument( |
| 669 |
'--env-dir', |
| 670 |
help='create the isolated build environment at this location instead of a temporary directory. The location ' |
| 671 |
'must be empty; it is removed on success and kept on failure so it can be inspected', |
| 672 |
metavar='PATH', |
| 673 |
) |
| 674 |
install_group.add_argument( |
| 675 |
'--dependency-constraints-txt', |
| 676 |
help='constrain build dependencies using a constraints.txt when installing dependencies', |
| 677 |
metavar='PATH', |
| 678 |
) |
| 679 |
install_group.add_argument( |
| 680 |
'--skip-dependency-check', |
| 681 |
'-x', |
| 682 |
action='store_true', |
| 683 |
help='do not check that build dependencies are installed', |
| 684 |
) |
| 685 |
|
| 686 |
return parser |
| 687 |
|
| 688 |
|
| 689 |
def _parse_config_settings(raw_config_settings: list[str]) -> dict[str, str | list[str]]: |
| 690 |
config_settings = dict[str, str | list[str]]() |
| 691 |
|
| 692 |
for arg in raw_config_settings: |
| 693 |
setting, sep, value = arg.partition('=') |
| 694 |
if not sep: |
| 695 |
warnings.warn( |
| 696 |
f'Config setting {setting!r} was passed without a value; this form is not supported by pip. ' |
| 697 |
f'Write {setting}= instead to be compatible with both tools', |
| 698 |
stacklevel=2, |
| 699 |
) |
| 700 |
existing = config_settings.get(setting) |
| 701 |
if existing is None: |
| 702 |
config_settings[setting] = value |
| 703 |
elif isinstance(existing, list): |
| 704 |
existing.append(value) |
| 705 |
else: |
| 706 |
config_settings[setting] = [existing, value] |
| 707 |
|
| 708 |
return config_settings |
| 709 |
|
| 710 |
|
| 711 |
def main(cli_args: Sequence[str], prog: str | None = None) -> None: |
| 712 |
""" |
| 713 |
Parse the CLI arguments and invoke the build process. |
| 714 |
|
| 715 |
:param cli_args: CLI arguments |
| 716 |
:param prog: Program name to show in help text |
| 717 |
""" |
| 718 |
parser = main_parser() |
| 719 |
if prog: |
| 720 |
parser.prog = prog |
| 721 |
args = cast('_Args', parser.parse_args(cli_args)) |
| 722 |
|
| 723 |
if args.env_dir is not None and args.no_isolation: |
| 724 |
parser.error('--env-dir: not allowed with --no-isolation') |
| 725 |
|
| 726 |
_setup_cli(verbosity=args.verbosity) |
| 727 |
|
| 728 |
is_file = os.path.isfile(args.srcdir) |
| 729 |
sdist_input = is_file and os.fspath(args.srcdir).lower().endswith('.tar.gz') |
| 730 |
wheel_input = is_file and os.fspath(args.srcdir).lower().endswith('.whl') |
| 731 |
run_build = partial( |
| 732 |
_select_build(parser, args, sdist_input=sdist_input, wheel_input=wheel_input), |
| 733 |
config_settings=_resolve_config_settings(args), |
| 734 |
isolation=not args.no_isolation, |
| 735 |
skip_dependency_check=args.skip_dependency_check, |
| 736 |
dependency_constraints_txt=args.dependency_constraints_txt, |
| 737 |
installer=args.installer, |
| 738 |
env_dir=args.env_dir, |
| 739 |
) |
| 740 |
|
| 741 |
if args.outdir is not None: |
| 742 |
outdir = args.outdir |
| 743 |
elif sdist_input or wheel_input: |
| 744 |
outdir = os.path.dirname(os.path.abspath(args.srcdir)) |
| 745 |
else: |
| 746 |
outdir = os.path.join(args.srcdir, 'dist') |
| 747 |
|
| 748 |
with _handle_build_error(env_dir=args.env_dir, sdist_extract_dir=args.sdist_extract_dir): |
| 749 |
if sdist_input: |
| 750 |
top_level = _validate_sdist_archive(args.srcdir) |
| 751 |
with _extract_sdist(args.srcdir, top_level, extract_dir=args.sdist_extract_dir) as extracted_srcdir: |
| 752 |
built = run_build(extracted_srcdir, outdir) |
| 753 |
else: |
| 754 |
built = run_build(args.srcdir, outdir) |
| 755 |
if args.report is not None: |
| 756 |
_write_report(args.report, outdir, built) |
| 757 |
if _ctx.verbosity >= -1 and built: |
| 758 |
artifact_list = _natural_language_list( |
| 759 |
['{underline}{}{reset}{bold}{green}'.format(artifact, **_styles.get()['stdout']) for artifact in built] |
| 760 |
) |
| 761 |
_cprint('{bold}{green}Successfully built {}{reset}', artifact_list) |
| 762 |
|
| 763 |
|
| 764 |
class _ArtifactReport(TypedDict): |
| 765 |
name: str |
| 766 |
path: str |
| 767 |
kind: str |
| 768 |
size: int |
| 769 |
hashes: dict[str, str] |
| 770 |
|
| 771 |
|
| 772 |
class _BuildReport(TypedDict): |
| 773 |
version: str |
| 774 |
artifacts: list[_ArtifactReport] |
| 775 |
|
| 776 |
|
| 777 |
def _write_report(path: StrPath, outdir: StrPath, artifacts: Sequence[str]) -> None: |
| 778 |
report: _BuildReport = { |
| 779 |
'version': '1.0', |
| 780 |
'artifacts': [_describe_artifact(os.path.join(outdir, name), name) for name in artifacts], |
| 781 |
} |
| 782 |
data = json.dumps(report, indent=2) + '\n' |
| 783 |
|
| 784 |
fd, tmp = tempfile.mkstemp(dir=os.path.dirname(os.path.abspath(path)), suffix='.tmp') |
| 785 |
try: |
| 786 |
with os.fdopen(fd, 'w', encoding='utf-8') as report_file: |
| 787 |
report_file.write(data) |
| 788 |
os.replace(tmp, path) |
| 789 |
except BaseException: |
| 790 |
with contextlib.suppress(OSError): |
| 791 |
os.unlink(tmp) |
| 792 |
raise |
| 793 |
|
| 794 |
|
| 795 |
def _describe_artifact(path: str, name: str) -> _ArtifactReport: |
| 796 |
digest = hashlib.sha256() |
| 797 |
size = 0 |
| 798 |
with open(path, 'rb') as artifact: |
| 799 |
while chunk := artifact.read(65536): |
| 800 |
size += len(chunk) |
| 801 |
digest.update(chunk) |
| 802 |
return { |
| 803 |
'name': name, |
| 804 |
'path': path, |
| 805 |
'kind': 'sdist' if name.endswith('.tar.gz') else 'wheel', |
| 806 |
'size': size, |
| 807 |
'hashes': {'sha256': digest.hexdigest()}, |
| 808 |
} |
| 809 |
|
| 810 |
|
| 811 |
def _resolve_config_settings(args: _Args) -> Mapping[str, JSONValue]: |
| 812 |
if args.config_json: |
| 813 |
try: |
| 814 |
config_settings = json.loads(args.config_json) |
| 815 |
except json.JSONDecodeError as e: |
| 816 |
_error(f'Invalid JSON in --config-json: {e}') |
| 817 |
if not isinstance(config_settings, dict): |
| 818 |
_error('--config-json must contain a JSON object (dict), not a list or primitive value') |
| 819 |
return config_settings |
| 820 |
if args.config_settings: |
| 821 |
return _parse_config_settings(args.config_settings) |
| 822 |
return {} |
| 823 |
|
| 824 |
|
| 825 |
def _select_build(parser: argparse.ArgumentParser, args: _Args, *, sdist_input: bool, wheel_input: bool) -> partial[list[str]]: |
| 826 |
if args.report is not None and args.metadata: |
| 827 |
parser.error('--report: not allowed with --metadata') |
| 828 |
if wheel_input and not args.metadata: |
| 829 |
parser.error('a wheel can only be used with --metadata, to read its metadata; it cannot be built from') |
| 830 |
if args.metadata and args.distributions: |
| 831 |
parser.error('--metadata: not allowed with --sdist or --wheel') |
| 832 |
if sdist_input and args.distributions and 'sdist' in args.distributions: |
| 833 |
parser.error( |
| 834 |
'cannot build a source distribution from a source distribution; ' |
| 835 |
'pass --wheel to build a wheel from the sdist (see https://github.com/pypa/build/issues/311)' |
| 836 |
) |
| 837 |
if args.metadata: |
| 838 |
return partial(_build_metadata, distributions=['wheel']) |
| 839 |
if sdist_input: |
| 840 |
distributions: list[Distribution] = args.distributions or ['wheel'] |
| 841 |
return partial(build_package, distributions=distributions) |
| 842 |
if args.distributions: |
| 843 |
return partial(build_package, distributions=args.distributions) |
| 844 |
return partial(build_package_via_sdist, distributions=['wheel'], sdist_extract_dir=args.sdist_extract_dir) |
| 845 |
|
| 846 |
|
| 847 |
def _validate_sdist_archive(archive: StrPath) -> str: |
| 848 |
"""Validate that ``archive`` is a PEP 625 source distribution and return its top-level directory name.""" |
| 849 |
name = os.path.basename(os.fspath(archive)) |
| 850 |
try: |
| 851 |
parse_sdist_filename(name) |
| 852 |
except (InvalidSdistFilename, InvalidVersion) as exc: |
| 853 |
msg = f'{name!r} does not look like a source distribution: {exc}' |
| 854 |
raise BuildException(msg) from exc |
| 855 |
|
| 856 |
try: |
| 857 |
with tar_open(archive) as tar: |
| 858 |
members = tar.getmembers() |
| 859 |
except (OSError, TarError) as exc: |
| 860 |
msg = f'failed to read source distribution {archive}: {exc}' |
| 861 |
raise BuildException(msg) from exc |
| 862 |
|
| 863 |
top_levels = {m.name.split('/', 1)[0] for m in members if m.name} |
| 864 |
top_levels.discard('') |
| 865 |
if len(top_levels) != 1: |
| 866 |
msg = f'source distribution {archive} must contain a single top-level directory, got: {sorted(top_levels)}' |
| 867 |
raise BuildException(msg) |
| 868 |
|
| 869 |
top = next(iter(top_levels)) |
| 870 |
if not any(m.name == f'{top}/PKG-INFO' and m.isfile() for m in members): |
| 871 |
msg = ( |
| 872 |
f'source distribution {archive} does not contain {top}/PKG-INFO; ' |
| 873 |
'this does not appear to be a valid source distribution' |
| 874 |
) |
| 875 |
raise BuildException(msg) |
| 876 |
return top |
| 877 |
|
| 878 |
|
| 879 |
@contextlib.contextmanager |
| 880 |
def _extract_sdist(archive: StrPath, top_level: str, *, extract_dir: StrPath | None = None) -> Iterator[str]: |
| 881 |
if extract_dir is None: |
| 882 |
tmp_dir = tempfile.mkdtemp(prefix='build-via-sdist-') |
| 883 |
try: |
| 884 |
with tar_open(archive) as tar: |
| 885 |
safe_extractall(tar, tmp_dir) |
| 886 |
yield os.path.join(tmp_dir, top_level) |
| 887 |
finally: |
| 888 |
shutil.rmtree(tmp_dir, ignore_errors=True) |
| 889 |
else: |
| 890 |
root = os.fspath(extract_dir) |
| 891 |
os.makedirs(root, exist_ok=True) |
| 892 |
target = os.path.join(root, top_level) |
| 893 |
shutil.rmtree(target, ignore_errors=True) |
| 894 |
with tar_open(archive) as tar: |
| 895 |
safe_extractall(tar, root) |
| 896 |
yield target |
| 897 |
|
| 898 |
|
| 899 |
def entrypoint() -> None: |
| 900 |
main(sys.argv[1:]) |
| 901 |
|
| 902 |
|
| 903 |
if __name__ == '__main__': # pragma: no cover |
| 904 |
main(sys.argv[1:], 'python -m build') |
| 905 |
|
| 906 |
|
| 907 |
__all__ = [ |
| 908 |
'main', |
| 909 |
'main_parser', |
| 910 |
] |