diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index a95eb943e4a4e7c..41147bb9cc1c493 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -88,7 +88,6 @@ Modules/Setup* @erlend-aasland @AA-Turner @emmatyping @itamaro Tools/build/regen-configure.sh @AA-Turner @itamaro # generate-build-details -Tools/build/generate-build-details.py @FFY00 Lib/test/test_build_details.py @FFY00 diff --git a/.github/workflows/mypy.yml b/.github/workflows/mypy.yml index 6109870724ea59c..cafc6df42980a0a 100644 --- a/.github/workflows/mypy.yml +++ b/.github/workflows/mypy.yml @@ -18,7 +18,6 @@ on: - "Tools/build/compute-changes.py" - "Tools/build/consts_getter.py" - "Tools/build/deepfreeze.py" - - "Tools/build/generate-build-details.py" - "Tools/build/generate_levenshtein_examples.py" - "Tools/build/generate_sbom.py" - "Tools/build/generate_stdlib_module_names.py" diff --git a/Lib/sysconfig/_build_details.py b/Lib/sysconfig/_build_details.py new file mode 100644 index 000000000000000..d49279ddd9fedca --- /dev/null +++ b/Lib/sysconfig/_build_details.py @@ -0,0 +1,573 @@ +"""Helper module to generate and manipulate build-details.json data (see PEP 739).""" + +from __future__ import annotations + +import argparse +import dataclasses +import importlib.machinery +import json +import os +import pathlib +import sys +import sysconfig +import typing +import types + +from typing import Any, Callable, ClassVar, Literal, NoDefault, Self, Type + + +_RELEASE_LEVELS = {0xA: 'alpha', 0xB: 'beta', 0xC: 'candidate', 0xF: 'final'} + + +# Types + + +class _NamespaceType(typing.Protocol): + __dict__: dict[str, Any] + + +_PathType = str | os.PathLike[str] + + +# Helpers + + +class _FieldTransform[GetT, SetT]: + """Descriptor that transforms values into the desired type. + + The dataclasses API does not provide a way to accept a different types in + the constructor, and convert them to the field type. This is a very common + functionality — eg. accepting str or os.PathLike in pathlib.Path fields. + Such scenarios require us to disable the automatic __init__ generation, + which is not ergonomic, requiring us to write a large amount of boilerplate. + Alternatively, we can disable init inclusion for such fields, and define + extra "init-only" fields to receive the value, allowing us to set the + transformed field value in __post_init__. However, this requires the + __init__ arguments to have a different name than the actual field. + + This descriptor provides a more ergonomic way to achieve this functionality. + It allows defining a custom setter function, which can receive different + types. It's similar to the functionality provided by "property". + + For better ergonomics when dealing with optional types, the transform + function is not called when setting the value to None. + """ + + # XXX: Repurpose typing.NoDefault as our sentinel here. + def __init__(self, fn: Callable[[SetT], GetT], default: GetT | NoDefault = NoDefault) -> None: + self._fn = fn + self._default_value = default + self._value: dict[int, GetT] = {} + + def __set_name__(self, cls: Type[object], name: str) -> None: + self.__name__ = name + + def __get__(self, obj: object | None, cls: Type[object]) -> GetT: + if obj and id(obj) in self._value: + return self._value[id(obj)] + if self._default_value is not NoDefault: + return self._default_value + assert self.__name__, 'missing __set_name__' + raise AttributeError(f'{cls.__name__!r} has no attribute {self.__name__!r}') from None + + def __set__(self, obj: object, value: SetT) -> None: + self._value[id(obj)] = self._fn(value) if value else None + + +# Common data types. + + +class VersionInfo(typing.NamedTuple): + major: int + minor: int + micro: int + releaselevel: Literal['alpha', 'beta', 'candidate', 'final'] + serial: int + + @classmethod + def from_object(cls, obj: object) -> VersionInfo: + return cls(obj.major, obj.minor, obj.micro, obj.releaselevel, obj.serial) + + @classmethod + def _from_patchlevel(cls, path: _PathType) -> VersionInfo: + import re + + with open(path) as f: + patchlevel = f.read() + + defines = dict(re.findall(r'^#define\s+(PY_\w+)\s+(\S+)', patchlevel, re.M)) + # PY_RELEASE_LEVEL is defined as another macro, e.g. PY_RELEASE_LEVEL_ALPHA. + level = int(defines[defines['PY_RELEASE_LEVEL']], 16) + return cls( + int(defines['PY_MAJOR_VERSION']), + int(defines['PY_MINOR_VERSION']), + int(defines['PY_MICRO_VERSION']), + _RELEASE_LEVELS[level], + int(defines['PY_RELEASE_SERIAL']), + ) + + +@dataclasses.dataclass(kw_only=True) +class Implementation: + name: str + version: _FieldTransform[VersionInfo, object] = _FieldTransform(VersionInfo.from_object) + hexversion: int + cache_tag: str + + @classmethod + def from_object(cls, obj: _NamespaceType) -> Implementation: + """Creates a Implementation instance from a sys.implementation namespace object. + + The namespace object must define __dict__ (eg. SimpleNamespace instances). + + If the namespace object defines extra fields, a new dataclass type is + created on-the-fly. This type subclasses Implementation, and defines the + extra fields. + """ + try: + fields_dict = vars(obj) + except TypeError: + raise TypeError('object must define __dict__') from None + + obj_fields = set(fields_dict) + cls_fields = {field.name for field in dataclasses.fields(cls)} + + if missing := (cls_fields - obj_fields): + missing_list_repr = ', '.join(sorted(missing, key=cls._fields.index)) + raise ValueError(f'{obj} is missing the following fields: {missing_list_repr}') + + if obj_fields == cls_fields: + return cls(**fields_dict) + + new_cls = dataclasses.make_dataclass( + cls_name=f'Implementation{id(obj)}', + fields=sorted(obj_fields - cls_fields, key=list(obj_fields).index), + bases=(cls,), + ) + return new_cls(**fields_dict) + + +# Base schema data structure definitions. + + +class SchemaVersion(typing.NamedTuple): + major: int + minor: int + + def __str__(self) -> str: + return f'{self.major}.{self.minor}' + + def __repr__(self) -> str: + return f'SchemaVersion({self.major}.{self.minor})' + + +@dataclasses.dataclass(kw_only=True) +class SchemaBase: + """Base type for versioned data structures.""" + + schema_version: ClassVar[SchemaVersion] + + def __init_subclass__(cls, schema: SchemaVersion): + cls.schema_version = SchemaVersion(*schema) + + def _validate(self) -> Exception: + # Check that all versioned objects in the dataclass fields are compatible + for field in dataclasses.fields(self): + value = getattr(self, field.name) + if not isinstance(value, SchemaBase): + continue + if value.schema_version != self.schema_version: + yield ValueError( + f'{self}.{key}: {value} has an incompatible schema version ' + f'{str(value.schema_version)!r} (expected {str(self.schema_version)!r})' + ) + + def __post_init__(self) -> None: + if validation_excs := list(self._validate()): + raise ExceptionGroup('Compatibility validation failed', validation_excs) + + +# Schema definitions - V1 + + +@dataclasses.dataclass(kw_only=True) +class LanguageV1(SchemaBase, schema=(1, 0)): + """PEP 739 — "language" field (https://peps.python.org/pep-0739/#language)""" + version: str + version_info: VersionInfo | None = None + + +@dataclasses.dataclass(kw_only=True) +class ABIV1(SchemaBase, schema=(1, 0)): + """PEP 739 — "abi" field (https://peps.python.org/pep-0739/#abi)""" + flags: tuple[str, ...] + extension_suffix: str | None = None + stable_abi_suffix: str | None = None + + +@dataclasses.dataclass(kw_only=True) +class SuffixesV1(SchemaBase, schema=(1, 0)): + """PEP 739 — "suffixes" field (https://peps.python.org/pep-0739/#suffixes)""" + source: tuple[str, ...] | None = None + bytecode: tuple[str, ...] | None = None + optimized_bytecode: tuple[str, ...] | None = None + debug_bytecode: tuple[str, ...] | None = None + extensions: tuple[str, ...] | None = None + + @classmethod + def from_interpreter(cls) -> SuffixesV1: + return cls( + source=importlib.machinery.SOURCE_SUFFIXES, + bytecode=importlib.machinery.BYTECODE_SUFFIXES, + #optimized_bytecode=importlib.machinery.OPTIMIZED_BYTECODE_SUFFIXES, + #debug_bytecode=importlib.machinery.DEBUG_BYTECODE_SUFFIXES, + # TODO: Add dedicated from_sysconfig_vars(?) constructor, instead of + # relying on from_interpreter to honor patched sysconfig vars. + extensions=cls._calculate_extension_suffixes(sysconfig.get_config_vars()), + #extensions=importlib.machinery.EXTENSION_SUFFIXES, + ) + + @classmethod + def _calculate_extension_suffixes(cls, sysconfig_vars: dict[str, str]) -> list[str] | None: + """Return the extension module suffixes of the target interpreter. + + importlib.machinery.EXTENSION_SUFFIXES describes the running interpreter, + which is not the target under --with-build-python. On POSIX, rebuild the + list from the target configuration instead, following + _PyImport_DynLoadFiletab in Python/dynload_*.c. The two are kept in sync + by test_build_details.BuildDetailsTargetTests.test_native_extension_suffixes. + """ + if os.name != 'posix': + return importlib.machinery.EXTENSION_SUFFIXES + + dynloadfile = sysconfig_vars['DYNLOADFILE'] + if dynloadfile == 'dynload_stub.o': + return None # Not supported + if dynloadfile == 'dynload_hpux.o': + return [sysconfig_vars['EXT_SUFFIX'], '.sl'] + if dynloadfile != 'dynload_shlib.o': + raise ValueError(f'Unsupported DYNLOADFILE: {dynloadfile!r}') + + soabi = sysconfig_vars['SOABI'] + if sysconfig_vars['MACHDEP'] == 'cygwin': + return [f'.{soabi}.dll', '.dll'] + + suffixes = [f'.{soabi}.so'] + alt_soabi = sysconfig_vars['ALT_SOABI'] + if alt_soabi: + suffixes.append(f'.{alt_soabi}.so') + platform = sysconfig_vars['SOABI_PLATFORM'] + if not sysconfig_vars['Py_GIL_DISABLED']: + if platform: + suffixes.append(f'.abi3-{platform}.so') + suffixes.append('.abi3.so') + if platform: + suffixes.append(f'.abi3t-{platform}.so') + suffixes.append('.abi3t.so') + suffixes.append('.so') + return suffixes + + +@dataclasses.dataclass(kw_only=True) +class LibpythonV1(SchemaBase, schema=(1, 0)): + """PEP 739 — "libpython" field (https://peps.python.org/pep-0739/#libpython)""" + dynamic: _FieldTransform[pathlib.Path | None, _PathType] = _FieldTransform(pathlib.Path, default=None) + dynamic_stableabi: _FieldTransform[pathlib.Path | None, _PathType] = _FieldTransform(pathlib.Path, default=None) + static: _FieldTransform[pathlib.Path | None, _PathType] = _FieldTransform(pathlib.Path, default=None) + link_extensions: bool | None = None + + +@dataclasses.dataclass(kw_only=True) +class CAPIV1(SchemaBase, schema=(1, 0)): + """PEP 739 — "capi" field (https://peps.python.org/pep-0739/#capi)""" + headers: _FieldTransform[pathlib.Path, _PathType] = _FieldTransform(pathlib.Path) + pkgconfig_path: _FieldTransform[pathlib.Path | None, _PathType] = _FieldTransform(pathlib.Path, default=None) + + +@dataclasses.dataclass(kw_only=True) +class BuildDetailsV1(SchemaBase, schema=(1, 0)): + """PEP 739 — root object (https://peps.python.org/pep-0739/#format)""" + schema_version: SchemaVersion + + base_prefix: _FieldTransform[pathlib.Path, _PathType] = _FieldTransform(pathlib.Path) + base_interpreter: _FieldTransform[pathlib.Path | None, _PathType] = _FieldTransform(pathlib.Path, default=None) + platform: str + + language: LanguageV1 + implementation: Implementation + abi: ABIV1 | None = None + suffixes: SuffixesV1 | None = None + libpython: LibpythonV1 | None = None + c_api: CAPIV1 | None = None + + arbitrary_data: SchemaBase | None = None + + def _relocate(self, obj: SchemaBase, origin: pathlib.Path) -> None: + changes = {} + for field in dataclasses.fields(obj): + if not field.init or field.name == 'base_prefix': + continue + value = getattr(obj, field.name) + if isinstance(value, pathlib.Path): + changes[field.name] = pathlib.Path(os.path.relpath(value, origin)) + elif isinstance(value, SchemaBase): + changes[field.name] = self._relocate(value, origin) + return dataclasses.replace(obj, **changes) + + def as_relocatable(self) -> Self: + """Returns a copy of the object where all the paths are relative to base_prefix.""" + return self._relocate(self, origin=self.base_prefix) + + def _dataclass_asdict(self, items: list[tuple[str, Any]]) -> dict[str, Any]: + data = dict(items) + for key, value in items: + # Filter out empty sections. + if value is None: + data.pop(key, None) + # Convert schema_version to string. + elif isinstance(value, SchemaVersion): + data[key] = str(value) + # Convert VersionInfo namedtuple to dict. + elif isinstance(value, VersionInfo): + data[key] = value._asdict() + # Convert paths to string. + elif isinstance(value, pathlib.Path): + data[key] = os.fspath(value) + # Join '.' so that the it is formated as './path' instead of 'path'. + if not value.is_absolute(): + data[key] = os.path.join('.', data[key]) + return data + + def as_json(self) -> str: + """Serialize data as JSON.""" + data = dataclasses.asdict(self, dict_factory=self._dataclass_asdict) + return json.dumps(data, indent=2) + + @classmethod + def from_interpreter(cls) -> BuildDetailsV1: + """Generate the build-details.json data for the running interpreter.""" + # TODO: Abstract data sources, in order to be able to re-use this code for other environments. + default_scheme_paths = types.SimpleNamespace({ + key: pathlib.Path(value) + for key, value in sysconfig.get_paths().items() + }) + + def make_path(value: str | None): + return pathlib.Path(value) if value else None + + LDLIBRARY = sysconfig.get_config_var('LDLIBRARY') + LIBRARY = sysconfig.get_config_var('LIBRARY') + PY3LIBRARY = sysconfig.get_config_var('PY3LIBRARY') + LIBPYTHON = sysconfig.get_config_var('LIBPYTHON') + STATIC_LIBPYTHON = sysconfig.get_config_var('STATIC_LIBPYTHON') + PYTHONFRAMEWORK = sysconfig.get_config_var('PYTHONFRAMEWORK') + + LIBDIR = make_path(sysconfig.get_config_var('LIBDIR')) + INCLUDEPY = make_path(sysconfig.get_config_var('INCLUDEPY')) + PYTHONFRAMEWORKPREFIX = make_path(sysconfig.get_config_var('PYTHONFRAMEWORKPREFIX')) + LIBPC = make_path(sysconfig.get_config_var('LIBPC')) + LIBPL = make_path(sysconfig.get_config_var('LIBPL')) + + interpreter_name = 'python' + if LDVERSION := sysconfig.get_config_var('LDVERSION'): + interpreter_name += LDVERSION + interpreter_name += sysconfig.get_config_var('EXE') + + # XXX: Workaround for cross compilation. Ideally we should always use + # VersionInfo.from_object here, and VersionInfo._from_patchlevel in + # a separate API (eg. from_data). + try: + version_info = VersionInfo._from_patchlevel(default_scheme_paths.include / 'patchlevel.h') + except FileNotFoundError: + version_info = VersionInfo.from_object(sys.version_info) + + data = types.SimpleNamespace() + + data.base_prefix = sysconfig.get_config_var('installed_base') + data.base_interpreter = default_scheme_paths.scripts / interpreter_name + data.platform = sysconfig.get_platform() + data.language = LanguageV1( + version=sysconfig.get_python_version(), + # XXX: Workaround for cross compilation — build version_info from + # patchlevel.h. Ideally this should be split into a separate + # API (eg. from_data). + version_info=version_info, + #version_info=VersionInfo.from_object(sys.version_info), + ) + data.implementation = Implementation.from_object(sys.implementation) + data.abi = ABIV1( + # XXX: Workaround for cross compilation. Ideally this should be + # split into a separate API (eg. from_data). + flags=tuple(sysconfig.get_config_var('ABIFLAGS')), + #flags=tuple(sys.abiflags), + ) + data.libpython = LibpythonV1() + data.suffixes = SuffixesV1.from_interpreter() + data.c_api = CAPIV1( + headers=INCLUDEPY, + ) + + # XXX: Workaround for cross compilation — override values based on + # sysconfig.get_config_var(s). Ideally, this should be provided by + # a different API instead (eg. from_data). + if '_multiarch' in vars(data.implementation): + data.implementation._multiarch = sysconfig.get_config_var('MULTIARCH') + if 'supports_isolated_interpreters' in vars(data.implementation): + # Mirrors Python/sysmodule.c. + data.implementation.supports_isolated_interpreters = ( + sysconfig.get_config_var('MACHDEP') not in ('wasi', 'emscripten') + ) + # XXX: Workaround for cross compilation — override hexversion with the + # values from the version_info computed above, as it might not + # match sys.version_info. + level = {name: value for value, name in _RELEASE_LEVELS.items()} + data.implementation.hexversion = int( + data.language.version_info.major << 24 + | data.language.version_info.minor << 16 + | data.language.version_info.micro << 8 + | level[data.language.version_info.releaselevel] << 4 + | data.language.version_info.serial + ) + + if os.name == 'posix': + # On POSIX, LIBRARY is always the static library, while LDLIBRARY is the + # dynamic library if enabled, otherwise it's the static library. + # If LIBRARY != LDLIBRARY, support for the dynamic library is enabled. + has_dynamic_library = LDLIBRARY != LIBRARY + # macOS framework builds don't install the static library (see libainstall). + has_static_library = STATIC_LIBPYTHON and not PYTHONFRAMEWORK + # The static library is only installed into LIBDIR when it is also + # LDLIBRARY; otherwise it is only installed into LIBPL. + static_library_dir = LIBPL if has_dynamic_library else LIBDIR + # In framework builds, LDLIBRARY is the path of the framework library + # relative to PYTHONFRAMEWORKPREFIX (e.g. + # Python.framework/Versions/3.X/Python), not a file in LIBDIR. + dynamic_library_dir = PYTHONFRAMEWORKPREFIX if PYTHONFRAMEWORK else LIBDIR + elif os.name == 'nt': + # Windows can only use a dynamic library or a static library. + # If it's using a dynamic library, sys.dllhandle will be set. + # Static builds on Windows are not really well supported, though. + # More context: https://github.com/python/cpython/issues/110234 + has_dynamic_library = hasattr(sys, 'dllhandle') + has_static_library = not has_dynamic_library + static_library_dir = LIBDIR + dynamic_library_dir = LIBDIR + else: + raise NotADirectoryError(f'Unknown platform: {os.name}') + + # On POSIX, EXT_SUFFIX is set regardless if extension modules are supported + # or not, and on Windows older versions of CPython only set EXT_SUFFIX when + # extension modules are supported, but newer versions of CPython set it + # regardless. + # + # We only want to set abi.extension_suffix and stable_abi_suffix if + # extension modules are supported. + if data.suffixes.extensions: + data.abi.extension_suffix = sysconfig.get_config_var('EXT_SUFFIX') + + # EXTENSION_SUFFIXES has been constant for a long time, and currently we + # don't have a better information source to find the stable ABI suffix. + for suffix in data.suffixes.extensions: + if suffix.startswith('.abi'): + data.abi.stable_abi_suffix = suffix + break + + if has_dynamic_library: + data.libpython.dynamic = dynamic_library_dir / LDLIBRARY + # FIXME: Not sure if windows has a different dll for the stable ABI, and + # even if it does, currently we don't have a way to get its name. + if PY3LIBRARY: + data.libpython.dynamic_stableabi = dynamic_library_dir / PY3LIBRARY + + # Os POSIX, this is defined by the LIBPYTHON Makefile variable not being + # empty. On Windows, don't link extensions — LIBPYTHON won't be defined, + data.libpython.link_extensions = bool(LIBPYTHON) + + if has_static_library: + data.libpython.static = static_library_dir / LIBRARY + + if LIBPC: + data.c_api.pkgconfig_path = LIBPC + + return BuildDetailsV1(**vars(data)) + + +# Default alias. + + +class _BuildDetailsProtocol(typing.Protocol): + def as_relocatable(self) -> Self: + """Returns a copy of the object where all the paths are relative to base_prefix.""" + return self._relocate(self, origin=self.base_prefix) + + def as_json(self) -> str: + return json.dumps(self, indent=2, object_hook=self._json_object_serializer) + + @classmethod + def from_interpreter(cls) -> SchemaBase: ... + + +BuildDetails: _BuildDetailsProtocol = BuildDetailsV1 + + +# Generation/CLI helpers. + + +def generate( + output_path: _PathType, + install_path: _PathType | None = None, + relative_paths=False, +) -> None: + """Generates build-details.json for the current interpreter. + + **install_path** allows overwriting the intended installation path. The file + will still be written to **output_path**, but `base_prefix` will be relative + to **install_path**. This is helpful when separting the build and install + steps. If **install_path** is not specified, it will default to + **output_path**. + """ + data = BuildDetails.from_interpreter() + + if not install_path: + install_path = output_path + + if relative_paths: + data = data.as_relocatable() + # If relative_paths is enabled, we also make base_prefix relative. + install_dir = pathlib.Path(install_path).parent + data.base_prefix = pathlib.Path(os.path.relpath(data.base_prefix, install_dir)) + + with open(output_path, 'w', encoding='utf-8') as f: + f.write(data.as_json() + '\n') + + +def main() -> None: + parser = argparse.ArgumentParser(exit_on_error=False) + parser.add_argument('output_path') + parser.add_argument( + '--relative-paths', + action='store_true', + help='Whether to specify paths as absolute, or as relative paths to ``base_prefix``.', + ) + install_path_group = parser.add_mutually_exclusive_group() + install_path_group.add_argument( + '--install-path', + nargs=1, + help='Overwrite the intended instalation path. Used when calculating a relative value for ``base_prefix``.', + ) + install_path_group.add_argument( + '--calculate-system-install-path', + action='store_true', + help='Calculate the install path for the system build-details.json file, and use that value.', + ) + + args = parser.parse_args() + + if args.calculate_system_install_path: + args.install_path = os.path.join(sysconfig.get_path('stdlib'), 'build-details.json') + + generate(args.output_path, args.install_path, args.relative_paths) + + +if __name__ == '__main__': + main() diff --git a/Lib/test/test_build_details.py b/Lib/test/test_build_details.py index a3f0937bdfc949a..519f149a7c03078 100644 --- a/Lib/test/test_build_details.py +++ b/Lib/test/test_build_details.py @@ -1,4 +1,4 @@ -import importlib +import importlib.machinery import json import os import os.path @@ -7,31 +7,12 @@ import string import textwrap import unittest -from pathlib import Path -from unittest import mock +import unittest.mock +import sysconfig._build_details as build_details +import tempfile from test.support import is_android, is_apple_mobile, is_wasm32, os_helper -BASE_PATH = Path( - __file__, # Lib/test/test_build_details.py - '..', # Lib/test - '..', # Lib - '..', # -).resolve() -MODULE_PATH = BASE_PATH / 'Tools' / 'build' / 'generate-build-details.py' - -try: - # Import "generate-build-details.py" as "generate_build_details" - spec = importlib.util.spec_from_file_location( - "generate_build_details", MODULE_PATH - ) - generate_build_details = importlib.util.module_from_spec(spec) - sys.modules["generate_build_details"] = generate_build_details - spec.loader.exec_module(generate_build_details) -except (FileNotFoundError, ImportError): - generate_build_details = None - - class FormatTestsBase: @property def contents(self): @@ -234,23 +215,19 @@ def test_libpython_dynamic(self): self.assertTrue(os.path.isfile(self.resolve(value['dynamic']))) -@unittest.skipIf( - generate_build_details is None, - "Failed to import generate-build-details" -) +@unittest.skipIf('_PYTHON_SYSCONFIGDATA_NAME' in os.environ, 'Cross-compiling') @unittest.skipIf(os.name != 'posix', 'Feature only implemented on POSIX right now') @unittest.skipIf(is_wasm32, 'Feature not available on WebAssembly builds') class BuildDetailsRelativePathsTests(unittest.TestCase): @property def build_details_absolute_paths(self): - data = generate_build_details.generate_data(schema_version='1.0') - return json.loads(json.dumps(data)) + json_data = build_details.BuildDetails.from_interpreter().as_json() + return json.loads(json_data) @property def build_details_relative_paths(self): - data = self.build_details_absolute_paths - generate_build_details.make_paths_relative(data, config_path=None) - return data + json_data = build_details.BuildDetails.from_interpreter().as_relocatable().as_json() + return json.loads(json_data) def test_round_trip(self): data_abs_path = self.build_details_absolute_paths @@ -265,14 +242,20 @@ def test_round_trip_with_config_file_path(self): data_abs_path = self.build_details_absolute_paths base_prefix = data_abs_path['base_prefix'] config_dir = os.path.join(base_prefix, 'lib', 'python3.X') - data_rel_path = self.build_details_absolute_paths - generate_build_details.make_paths_relative( - data_rel_path, - config_path=os.path.join(config_dir, 'build-details.json'), - ) + + with tempfile.TemporaryDirectory() as temp_dir: + out_file = os.path.join(temp_dir, 'build-details.json') + build_details.generate( + output_path=out_file, + install_path=os.path.join(config_dir, 'build-details.json'), + relative_paths=True + ) + + with open(out_file) as f: + data_rel_path = json.loads(f.read()) # base_prefix is relative to the config file's directory... - self.assertEqual(data_rel_path['base_prefix'], os.path.join('..', '..')) + self.assertEqual(data_rel_path['base_prefix'], os.path.join('.', '..', '..')) # ...while the other paths are still relative to base_prefix. self.check_relative_paths(data_abs_path, data_rel_path) @@ -314,26 +297,35 @@ def check_relative_paths(self, data_abs_path, data_rel_path): def generate_data(**config_vars): """Generate build-details data with overridden config vars.""" get_config_var = sysconfig.get_config_var + get_config_vars = sysconfig.get_config_vars + def patched_get_config_var(name): if name in config_vars: return config_vars[name] return get_config_var(name) - with mock.patch('sysconfig.get_config_var', patched_get_config_var): - data = generate_build_details.generate_data(schema_version='1.0') - return json.loads(json.dumps(data)) + + def patched_get_config_vars(*args): + if args: + raise NotImplementedError("Mock get_config_vars doesn't support named lookups.") + return get_config_vars() | config_vars + + with ( + unittest.mock.patch('sysconfig.get_config_var', patched_get_config_var), + unittest.mock.patch('sysconfig.get_config_vars', patched_get_config_vars), + ): + data = build_details.BuildDetails.from_interpreter().as_json() + return json.loads(data) -@unittest.skipIf( - generate_build_details is None, - "Failed to import generate-build-details" -) @unittest.skipIf(os.name != 'posix', 'Feature only implemented on POSIX') class BuildDetailsTargetTests(unittest.TestCase): """Values that must come from the target configuration (gh-136267).""" def test_native_extension_suffixes(self): - self.assertEqual(generate_build_details.get_extension_suffixes(), - importlib.machinery.EXTENSION_SUFFIXES) + self.assertEqual( + build_details.BuildDetails.from_interpreter().suffixes.extensions, + importlib.machinery.EXTENSION_SUFFIXES, + ) def test_free_threaded_debug(self): # A GIL-enabled release build Python generating for this target @@ -360,25 +352,20 @@ def test_free_threaded_debug(self): def test_no_dynamic_loading(self): data = generate_data(MACHDEP='wasi', DYNLOADFILE='dynload_stub.o') - self.assertEqual(data['suffixes']['extensions'], []) + self.assertNotIn('extensions', data['suffixes']) self.assertNotIn('extension_suffix', data['abi']) self.assertNotIn('stable_abi_suffix', data['abi']) - self.assertFalse( - data['implementation']['supports_isolated_interpreters']) + self.assertFalse(data['implementation']['supports_isolated_interpreters']) -@unittest.skipIf( - generate_build_details is None, - "Failed to import generate-build-details" -) class BuildDetailsVersionTests(unittest.TestCase): def test_native(self): - version_info = generate_build_details.get_version_info() - self.assertEqual(version_info, - generate_build_details.version_info_to_dict( - sys.version_info)) - self.assertEqual(generate_build_details.hexversion(version_info), - sys.hexversion) + data = build_details.BuildDetails.from_interpreter() + self.assertEqual( + data.language.version_info, + build_details.VersionInfo.from_object(sys.version_info), + ) + self.assertEqual(data.implementation.hexversion, sys.hexversion) def test_patchlevel(self): patchlevel_h = os.path.join(os_helper.TESTFN, 'patchlevel.h') @@ -394,21 +381,24 @@ def test_patchlevel(self): #define PY_RELEASE_SERIAL 2 #define PY_VERSION "3.99.7rc2" ''')) - with mock.patch.object(generate_build_details, 'PATCHLEVEL_H', - patchlevel_h): - version_info = generate_build_details.get_version_info() - self.assertEqual(version_info, { - 'major': 3, 'minor': 99, 'micro': 7, - 'releaselevel': 'candidate', 'serial': 2, - }) - self.assertEqual(generate_build_details.hexversion(version_info), - 0x036307c2) - - -@unittest.skipIf( - generate_build_details is None, - "Failed to import generate-build-details" -) + + version_info_from_patchlevel = build_details.VersionInfo._from_patchlevel + + def patched_version_info_from_patchlevel(path): + return version_info_from_patchlevel(patchlevel_h) + + with unittest.mock.patch( + 'sysconfig._build_details.VersionInfo._from_patchlevel', + patched_version_info_from_patchlevel, + ): + data = build_details.BuildDetails.from_interpreter() + + self.assertEqual(data.language.version_info, build_details.VersionInfo( + major=3, minor=99, micro=7, releaselevel='candidate', serial=2, + )) + self.assertEqual(data.implementation.hexversion, 0x036307c2) + + @unittest.skipIf(os.name != 'posix', 'Feature only implemented on POSIX') @unittest.skipIf(is_wasm32, 'Feature not available on WebAssembly builds') class BuildDetailsLibpythonTests(unittest.TestCase): diff --git a/Makefile.pre.in b/Makefile.pre.in index 035e8bd3c29ce2d..fd7e126b8b0d56f 100644 --- a/Makefile.pre.in +++ b/Makefile.pre.in @@ -1035,8 +1035,9 @@ pybuilddir.txt: $(PYTHON_FOR_BUILD_DEPS) fi $(BUILD_DETAILS): pybuilddir.txt - $(RUNSHARED_FOR_BUILD) $(PYTHON_FOR_BUILD) $(srcdir)/Tools/build/generate-build-details.py \ - --relative-paths --installed-location \ + $(RUNSHARED_FOR_BUILD) $(PYTHON_FOR_BUILD) -m sysconfig._build_details \ + --relative-paths \ + --calculate-system-install-path \ `cat pybuilddir.txt`/$(BUILD_DETAILS) # Build static library diff --git a/Tools/build/generate-build-details.py b/Tools/build/generate-build-details.py deleted file mode 100644 index bf216fb0385d5b1..000000000000000 --- a/Tools/build/generate-build-details.py +++ /dev/null @@ -1,332 +0,0 @@ -"""Generate build-details.json (see PEP 739).""" - -# Script initially imported from: -# https://github.com/FFY00/python-instrospection/blob/main/python_introspection/scripts/generate-build-details.py - -from __future__ import annotations - -import argparse -import collections -import importlib.machinery -import json -import os -import re -import sys -import sysconfig - -TYPE_CHECKING = False -if TYPE_CHECKING: - from typing import Any - - -PATCHLEVEL_H = os.path.join( - os.path.dirname(__file__), '..', '..', 'Include', 'patchlevel.h', -) -RELEASE_LEVELS = {0xA: 'alpha', 0xB: 'beta', 0xC: 'candidate', 0xF: 'final'} - - -def version_info_to_dict(obj: sys._version_info) -> dict[str, Any]: - field_names = ('major', 'minor', 'micro', 'releaselevel', 'serial') - return {field: getattr(obj, field) for field in field_names} - - -def get_version_info() -> dict[str, Any]: - """Return the target's version as a version_info dict. - - sys.version_info describes the running interpreter, which under - --with-build-python can differ from the target in micro version and - release level. Read Include/patchlevel.h instead when it is available. - """ - try: - with open(PATCHLEVEL_H, encoding='utf-8') as f: - patchlevel = f.read() - except FileNotFoundError: - return version_info_to_dict(sys.version_info) - defines = dict(re.findall(r'^#define\s+(PY_\w+)\s+(\S+)', patchlevel, re.M)) - # PY_RELEASE_LEVEL is defined as another macro, e.g. PY_RELEASE_LEVEL_ALPHA. - level = int(defines[defines['PY_RELEASE_LEVEL']], 16) - return { - 'major': int(defines['PY_MAJOR_VERSION']), - 'minor': int(defines['PY_MINOR_VERSION']), - 'micro': int(defines['PY_MICRO_VERSION']), - 'releaselevel': RELEASE_LEVELS[level], - 'serial': int(defines['PY_RELEASE_SERIAL']), - } - - -def hexversion(version_info: dict[str, Any]) -> int: - level = {name: value for value, name in RELEASE_LEVELS.items()} - return int( - version_info['major'] << 24 - | version_info['minor'] << 16 - | version_info['micro'] << 8 - | level[version_info['releaselevel']] << 4 - | version_info['serial'] - ) - - -def get_dict_key(container: dict[str, Any], key: str) -> dict[str, Any]: - for part in key.split('.'): - container = container[part] - return container - - -def get_extension_suffixes() -> list[str]: - """Return the extension module suffixes of the target interpreter. - - importlib.machinery.EXTENSION_SUFFIXES describes the running interpreter, - which is not the target under --with-build-python. On POSIX, rebuild the - list from the target configuration instead, following - _PyImport_DynLoadFiletab in Python/dynload_*.c. The two are kept in sync - by test_build_details.BuildDetailsTargetTests.test_native_extension_suffixes. - """ - if os.name != 'posix': - return importlib.machinery.EXTENSION_SUFFIXES - - dynloadfile = sysconfig.get_config_var('DYNLOADFILE') - if dynloadfile == 'dynload_stub.o': - return [] - if dynloadfile == 'dynload_hpux.o': - return [sysconfig.get_config_var('EXT_SUFFIX'), '.sl'] - if dynloadfile != 'dynload_shlib.o': - raise ValueError(f'Unsupported DYNLOADFILE: {dynloadfile!r}') - - soabi = sysconfig.get_config_var('SOABI') - if sysconfig.get_config_var('MACHDEP') == 'cygwin': - return [f'.{soabi}.dll', '.dll'] - - suffixes = [f'.{soabi}.so'] - alt_soabi = sysconfig.get_config_var('ALT_SOABI') - if alt_soabi: - suffixes.append(f'.{alt_soabi}.so') - platform = sysconfig.get_config_var('SOABI_PLATFORM') - if not sysconfig.get_config_var('Py_GIL_DISABLED'): - if platform: - suffixes.append(f'.abi3-{platform}.so') - suffixes.append('.abi3.so') - if platform: - suffixes.append(f'.abi3t-{platform}.so') - suffixes.append('.abi3t.so') - suffixes.append('.so') - return suffixes - - -def generate_data(schema_version: str) -> collections.defaultdict[str, Any]: - """Generate the build-details.json data (PEP 739). - - :param schema_version: The schema version of the data we want to generate. - """ - - if schema_version != '1.0': - raise ValueError(f'Unsupported schema_version: {schema_version}') - - data: collections.defaultdict[str, Any] = collections.defaultdict( - lambda: collections.defaultdict(dict), - ) - - data['schema_version'] = schema_version - - data['base_prefix'] = sysconfig.get_config_var('installed_base') - #data['base_interpreter'] = sys._base_executable - data['base_interpreter'] = os.path.join( - sysconfig.get_path('scripts'), - "python" - + sysconfig.get_config_var('LDVERSION') - + sysconfig.get_config_var('EXE'), - ) - data['platform'] = sysconfig.get_platform() - - version_info = get_version_info() - data['language']['version'] = sysconfig.get_python_version() - data['language']['version_info'] = version_info - - data['implementation'] = vars(sys.implementation).copy() - data['implementation']['version'] = version_info - data['implementation']['hexversion'] = hexversion(version_info) - # Fix cross-compilation - if '_multiarch' in data['implementation']: - data['implementation']['_multiarch'] = sysconfig.get_config_var('MULTIARCH') - if 'supports_isolated_interpreters' in data['implementation']: - # Mirrors Python/sysmodule.c. - data['implementation']['supports_isolated_interpreters'] = ( - sysconfig.get_config_var('MACHDEP') not in ('wasi', 'emscripten') - ) - - data['abi']['flags'] = list(sysconfig.get_config_var('ABIFLAGS')) - - data['suffixes']['source'] = importlib.machinery.SOURCE_SUFFIXES - data['suffixes']['bytecode'] = importlib.machinery.BYTECODE_SUFFIXES - #data['suffixes']['optimized_bytecode'] = importlib.machinery.OPTIMIZED_BYTECODE_SUFFIXES - #data['suffixes']['debug_bytecode'] = importlib.machinery.DEBUG_BYTECODE_SUFFIXES - extension_suffixes = get_extension_suffixes() - data['suffixes']['extensions'] = extension_suffixes - - LIBDIR = sysconfig.get_config_var('LIBDIR') - LIBPL = sysconfig.get_config_var('LIBPL') - LDLIBRARY = sysconfig.get_config_var('LDLIBRARY') - LIBRARY = sysconfig.get_config_var('LIBRARY') - PY3LIBRARY = sysconfig.get_config_var('PY3LIBRARY') - LIBPYTHON = sysconfig.get_config_var('LIBPYTHON') - LIBPC = sysconfig.get_config_var('LIBPC') - INCLUDEPY = sysconfig.get_config_var('INCLUDEPY') - - if os.name == 'posix': - # On POSIX, LIBRARY is always the static library, while LDLIBRARY is the - # dynamic library if enabled, otherwise it's the static library. - # If LIBRARY != LDLIBRARY, support for the dynamic library is enabled. - has_dynamic_library = LDLIBRARY != LIBRARY - # Framework builds don't install the static library (see libainstall). - has_static_library = ( - sysconfig.get_config_var('STATIC_LIBPYTHON') - and not sysconfig.get_config_var('PYTHONFRAMEWORK') - ) - # The static library is only installed into LIBDIR when it is also - # LDLIBRARY; otherwise it is only installed into LIBPL. - static_library_dir = LIBPL if has_dynamic_library else LIBDIR - # In framework builds, LDLIBRARY is the path of the framework library - # relative to PYTHONFRAMEWORKPREFIX (e.g. - # Python.framework/Versions/3.X/Python), not a file in LIBDIR. - if sysconfig.get_config_var('PYTHONFRAMEWORK'): - dynamic_library_dir = sysconfig.get_config_var('PYTHONFRAMEWORKPREFIX') - else: - dynamic_library_dir = LIBDIR - elif os.name == 'nt': - # Windows can only use a dynamic library or a static library. - # If it's using a dynamic library, sys.dllhandle will be set. - # Static builds on Windows are not really well supported, though. - # More context: https://github.com/python/cpython/issues/110234 - has_dynamic_library = hasattr(sys, 'dllhandle') - has_static_library = not has_dynamic_library - static_library_dir = LIBDIR - dynamic_library_dir = LIBDIR - else: - raise NotADirectoryError(f'Unknown platform: {os.name}') - - # On POSIX, EXT_SUFFIX is set regardless if extension modules are supported - # or not, and on Windows older versions of CPython only set EXT_SUFFIX when - # extension modules are supported, but newer versions of CPython set it - # regardless. - # - # We only want to set abi.extension_suffix and stable_abi_suffix if - # extension modules are supported, regardless of how libpython is built. - if extension_suffixes: - data['abi']['extension_suffix'] = sysconfig.get_config_var('EXT_SUFFIX') - - for suffix in extension_suffixes: - if suffix.startswith('.abi'): - data['abi']['stable_abi_suffix'] = suffix - break - - if has_dynamic_library: - data['libpython']['dynamic'] = os.path.join(dynamic_library_dir, LDLIBRARY) - # FIXME: Not sure if windows has a different dll for the stable ABI, and - # even if it does, currently we don't have a way to get its name. - if PY3LIBRARY: - data['libpython']['dynamic_stableabi'] = os.path.join(LIBDIR, PY3LIBRARY) - - # Os POSIX, this is defined by the LIBPYTHON Makefile variable not being - # empty. On Windows, don't link extensions — LIBPYTHON won't be defined, - data['libpython']['link_extensions'] = bool(LIBPYTHON) - - if has_static_library: - data['libpython']['static'] = os.path.join(static_library_dir, LIBRARY) - - data['c_api']['headers'] = INCLUDEPY - if LIBPC: - data['c_api']['pkgconfig_path'] = LIBPC - - return data - - -def make_paths_relative(data: dict[str, Any], config_path: str | None = None) -> None: - base_prefix = data['base_prefix'] - # Make base_prefix relative to the config_path directory. The other paths - # are still made relative to the absolute base_prefix below. - if config_path: - data['base_prefix'] = relative_path(base_prefix, - os.path.dirname(config_path)) - - # Update path values to make them relative to base_prefix - PATH_KEYS = ( - 'base_interpreter', - 'libpython.dynamic', - 'libpython.dynamic_stableabi', - 'libpython.static', - 'c_api.headers', - 'c_api.pkgconfig_path', - ) - for entry in PATH_KEYS: - *parents, child = entry.split('.') - # Get the key container object - try: - container = data - for part in parents: - container = container[part] - if child not in container: - raise KeyError(child) - current_path = container[child] - except KeyError: - continue - # Get the relative path - new_path = relative_path(current_path, base_prefix) - # Join '.' so that the path is formated as './path' instead of 'path' - new_path = os.path.join('.', new_path) - container[child] = new_path - - -def relative_path(path: str, base: str) -> str: - if os.name != 'nt': - return os.path.relpath(path, base) - - # There are no relative paths between drives on Windows. - path_drv, _ = os.path.splitdrive(path) - base_drv, _ = os.path.splitdrive(base) - if path_drv.lower() == base_drv.lower(): - return os.path.relpath(path, base) - - return path - - -def main() -> None: - parser = argparse.ArgumentParser(exit_on_error=False) - parser.add_argument('location') - parser.add_argument( - '--schema-version', - default='1.0', - help='Schema version of the build-details.json file to generate.', - ) - parser.add_argument( - '--relative-paths', - action='store_true', - help='Whether to specify paths as absolute, or as relative paths to ``base_prefix``.', - ) - parser.add_argument( - '--config-file-path', - default=None, - help='If specified, ``base_prefix`` will be set as a relative path to the given config file path.', - ) - parser.add_argument( - '--installed-location', - action='store_true', - help='Use the path the file is installed to as ``--config-file-path``.', - ) - - args = parser.parse_args() - - data = generate_data(args.schema_version) - if args.installed_location: - # Not taken from the Makefile: `make install prefix=...` changes - # LIBDEST, but not the prefix that sysconfig reports. - args.config_file_path = os.path.join( - sysconfig.get_path('stdlib'), 'build-details.json') - if args.relative_paths: - make_paths_relative(data, args.config_file_path) - - json_output = json.dumps(data, indent=2) - with open(args.location, 'w', encoding='utf-8') as f: - f.write(json_output) - f.write('\n') - - -if __name__ == '__main__': - main() diff --git a/Tools/build/mypy.ini b/Tools/build/mypy.ini index 485c9314cf70015..68ab2bfff20cd82 100644 --- a/Tools/build/mypy.ini +++ b/Tools/build/mypy.ini @@ -8,7 +8,6 @@ files = Tools/build/compute-changes.py, Tools/build/consts_getter.py, Tools/build/deepfreeze.py, - Tools/build/generate-build-details.py, Tools/build/generate_levenshtein_examples.py, Tools/build/generate_sbom.py, Tools/build/generate_stdlib_module_names.py,