Debian Codegraph @

Tools/build/generate-build-details.py

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 """Generate build-details.json (see PEP 739)."""
2
3 # Script initially imported from:
4 # https://github.com/FFY00/python-instrospection/blob/main/python_introspection/scripts/generate-build-details.py
5
6 from __future__ import annotations
7
8 import argparse
9 import collections
10 import importlib.machinery
11 import json
12 import os
13 import sys
14 import sysconfig
15
16 TYPE_CHECKING = False
17 if TYPE_CHECKING:
18 from typing import Any
19
20
21 def version_info_to_dict(obj: sys._version_info) -> dict[str, Any]:
22 field_names = ('major', 'minor', 'micro', 'releaselevel', 'serial')
23 return {field: getattr(obj, field) for field in field_names}
24
25
26 def get_dict_key(container: dict[str, Any], key: str) -> dict[str, Any]:
27 for part in key.split('.'):
28 container = container[part]
29 return container
30
31
32 def generate_data(schema_version: str) -> collections.defaultdict[str, Any]:
33 """Generate the build-details.json data (PEP 739).
34
35 :param schema_version: The schema version of the data we want to generate.
36 """
37
38 if schema_version != '1.0':
39 raise ValueError(f'Unsupported schema_version: {schema_version}')
40
41 data: collections.defaultdict[str, Any] = collections.defaultdict(
42 lambda: collections.defaultdict(dict),
43 )
44
45 data['schema_version'] = schema_version
46
47 data['base_prefix'] = sysconfig.get_config_var('installed_base')
48 #data['base_interpreter'] = sys._base_executable
49 data['base_interpreter'] = os.path.join(
50 sysconfig.get_path('scripts'),
51 'python' + sysconfig.get_config_var('VERSION'),
52 )
53 data['platform'] = sysconfig.get_platform()
54
55 data['language']['version'] = sysconfig.get_python_version()
56 data['language']['version_info'] = version_info_to_dict(sys.version_info)
57
58 data['implementation'] = vars(sys.implementation).copy()
59 data['implementation']['version'] = version_info_to_dict(sys.implementation.version)
60 # Fix cross-compilation
61 if '_multiarch' in data['implementation']:
62 data['implementation']['_multiarch'] = sysconfig.get_config_var('MULTIARCH')
63
64 data['abi']['flags'] = list(sys.abiflags)
65
66 data['suffixes']['source'] = importlib.machinery.SOURCE_SUFFIXES
67 data['suffixes']['bytecode'] = importlib.machinery.BYTECODE_SUFFIXES
68 #data['suffixes']['optimized_bytecode'] = importlib.machinery.OPTIMIZED_BYTECODE_SUFFIXES
69 #data['suffixes']['debug_bytecode'] = importlib.machinery.DEBUG_BYTECODE_SUFFIXES
70 data['suffixes']['extensions'] = importlib.machinery.EXTENSION_SUFFIXES
71
72 LIBDIR = sysconfig.get_config_var('LIBDIR')
73 LDLIBRARY = sysconfig.get_config_var('LDLIBRARY')
74 LIBRARY = sysconfig.get_config_var('LIBRARY')
75 PY3LIBRARY = sysconfig.get_config_var('PY3LIBRARY')
76 LIBPYTHON = sysconfig.get_config_var('LIBPYTHON')
77 LIBPC = sysconfig.get_config_var('LIBPC')
78 INCLUDEPY = sysconfig.get_config_var('INCLUDEPY')
79
80 if os.name == 'posix':
81 # On POSIX, LIBRARY is always the static library, while LDLIBRARY is the
82 # dynamic library if enabled, otherwise it's the static library.
83 # If LIBRARY != LDLIBRARY, support for the dynamic library is enabled.
84 has_dynamic_library = LDLIBRARY != LIBRARY
85 has_static_library = sysconfig.get_config_var('STATIC_LIBPYTHON')
86 elif os.name == 'nt':
87 # Windows can only use a dynamic library or a static library.
88 # If it's using a dynamic library, sys.dllhandle will be set.
89 # Static builds on Windows are not really well supported, though.
90 # More context: https://github.com/python/cpython/issues/110234
91 has_dynamic_library = hasattr(sys, 'dllhandle')
92 has_static_library = not has_dynamic_library
93 else:
94 raise NotADirectoryError(f'Unknown platform: {os.name}')
95
96 # On POSIX, EXT_SUFFIX is set regardless if extension modules are supported
97 # or not, and on Windows older versions of CPython only set EXT_SUFFIX when
98 # extension modules are supported, but newer versions of CPython set it
99 # regardless.
100 #
101 # We only want to set abi.extension_suffix and stable_abi_suffix if
102 # extension modules are supported.
103 if has_dynamic_library:
104 data['abi']['extension_suffix'] = sysconfig.get_config_var('EXT_SUFFIX')
105
106 # EXTENSION_SUFFIXES has been constant for a long time, and currently we
107 # don't have a better information source to find the stable ABI suffix.
108 for suffix in importlib.machinery.EXTENSION_SUFFIXES:
109 if suffix.startswith('.abi'):
110 data['abi']['stable_abi_suffix'] = suffix
111 break
112
113 data['libpython']['dynamic'] = os.path.join(LIBDIR, LDLIBRARY)
114 # FIXME: Not sure if windows has a different dll for the stable ABI, and
115 # even if it does, currently we don't have a way to get its name.
116 if PY3LIBRARY:
117 data['libpython']['dynamic_stableabi'] = os.path.join(LIBDIR, PY3LIBRARY)
118
119 # Os POSIX, this is defined by the LIBPYTHON Makefile variable not being
120 # empty. On Windows, don't link extensions — LIBPYTHON won't be defined,
121 data['libpython']['link_extensions'] = bool(LIBPYTHON)
122
123 if has_static_library:
124 data['libpython']['static'] = os.path.join(LIBDIR, LIBRARY)
125
126 data['c_api']['headers'] = INCLUDEPY
127 if LIBPC:
128 data['c_api']['pkgconfig_path'] = LIBPC
129
130 return data
131
132
133 def make_paths_relative(data: dict[str, Any], config_path: str | None = None) -> None:
134 # Make base_prefix relative to the config_path directory
135 if config_path:
136 data['base_prefix'] = relative_path(data['base_prefix'],
137 os.path.dirname(config_path))
138 base_prefix = data['base_prefix']
139
140 # Update path values to make them relative to base_prefix
141 PATH_KEYS = (
142 'base_interpreter',
143 'libpython.dynamic',
144 'libpython.dynamic_stableabi',
145 'libpython.static',
146 'c_api.headers',
147 'c_api.pkgconfig_path',
148 )
149 for entry in PATH_KEYS:
150 *parents, child = entry.split('.')
151 # Get the key container object
152 try:
153 container = data
154 for part in parents:
155 container = container[part]
156 if child not in container:
157 raise KeyError(child)
158 current_path = container[child]
159 except KeyError:
160 continue
161 # Get the relative path
162 new_path = relative_path(current_path, base_prefix)
163 # Join '.' so that the path is formated as './path' instead of 'path'
164 new_path = os.path.join('.', new_path)
165 container[child] = new_path
166
167
168 def relative_path(path: str, base: str) -> str:
169 if os.name != 'nt':
170 return os.path.relpath(path, base)
171
172 # There are no relative paths between drives on Windows.
173 path_drv, _ = os.path.splitdrive(path)
174 base_drv, _ = os.path.splitdrive(base)
175 if path_drv.lower() == base_drv.lower():
176 return os.path.relpath(path, base)
177
178 return path
179
180
181 def main() -> None:
182 parser = argparse.ArgumentParser(exit_on_error=False)
183 parser.add_argument('location')
184 parser.add_argument(
185 '--schema-version',
186 default='1.0',
187 help='Schema version of the build-details.json file to generate.',
188 )
189 parser.add_argument(
190 '--relative-paths',
191 action='store_true',
192 help='Whether to specify paths as absolute, or as relative paths to ``base_prefix``.',
193 )
194 parser.add_argument(
195 '--config-file-path',
196 default=None,
197 help='If specified, ``base_prefix`` will be set as a relative path to the given config file path.',
198 )
199
200 args = parser.parse_args()
201
202 data = generate_data(args.schema_version)
203 if args.relative_paths:
204 make_paths_relative(data, args.config_file_path)
205
206 json_output = json.dumps(data, indent=2)
207 with open(args.location, 'w', encoding='utf-8') as f:
208 f.write(json_output)
209 f.write('\n')
210
211
212 if __name__ == '__main__':
213 main()