Debian Codegraph @

mesonbuild/modules/python.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2018 The Meson development team
3
4 from __future__ import annotations
5
6 import copy, json, os, shutil, re
7 import typing as T
8
9 from . import ExtensionModule, ModuleInfo
10 from .. import mesonlib
11 from .. import mlog
12 from ..build import CustomTarget, CustomTargetIndex, BuildTarget, GeneratedList, StructuredSources, ExtractedObjects, SharedModule
13 from ..dependencies import NotFoundDependency
14 from ..dependencies.detect import get_dep_identifier, find_external_dependency
15 from ..dependencies.python import BasicPythonExternalProgram, python_factory, _PythonDependencyBase
16 from ..interpreter import extract_required_kwarg, primitives as P_OBJ
17 from ..interpreter.interpreterobjects import ProgramHolder
18 from ..interpreter.type_checking import NoneType, DEPENDENCY_KWS, PRESERVE_PATH_KW, REQUIRED_KW, SHARED_MOD_KWS
19 from ..interpreterbase import (
20 noPosargs, noKwargs, ContainerTypeInfo,
21 InvalidArguments, typed_pos_args, typed_kwargs, KwargInfo,
22 FeatureNew, disablerIfNotFound, InterpreterObject
23 )
24 from ..mesonlib import MachineChoice
25 from ..options import OptionKey
26 from ..programs import ExternalProgram, NonExistingExternalProgram
27
28 _T = T.TypeVar('_T')
29
30 if T.TYPE_CHECKING:
31 from typing_extensions import TypedDict, NotRequired
32
33 from . import ModuleState
34 from ..build import Build, Data
35 from ..dependencies.base import Dependency, DependencyObjectKWs
36 from ..interpreter import Interpreter
37 from ..interpreter.interpreter import BuildTargetSource
38 from ..interpreter.kwargs import ExtractRequired, SharedModule as SharedModuleKw, FuncDependency
39 from ..interpreter.type_checking import SourcesVarargsType
40 from ..interpreterbase.baseobjects import TYPE_var, TYPE_kwargs
41
42 class PyInstallKw(TypedDict):
43
44 pure: T.Optional[bool]
45 subdir: str
46 install_tag: T.Optional[str]
47 preserve_path: bool
48
49 class FindInstallationKw(ExtractRequired):
50
51 disabler: bool
52 modules: T.List[str]
53 pure: T.Optional[bool]
54
55 class ExtensionModuleKw(SharedModuleKw):
56
57 # Yes, these are different between SharedModule and ExtensionModule
58 install_dir: T.Union[str, bool, None] # type: ignore[misc]
59 limited_api: str
60 subdir: NotRequired[T.Optional[str]]
61
62 MaybePythonProg = T.Union[NonExistingExternalProgram, 'PythonExternalProgram']
63
64
65 _MOD_KWARGS = [k for k in SHARED_MOD_KWS if
66 k.name not in {'name_prefix', 'name_suffix', 'install_dir'}]
67
68
69 class PythonExternalProgram(BasicPythonExternalProgram):
70
71 # This is a ClassVar instead of an instance bool, because although an
72 # installation is cached, we actually copy it, modify attributes such as pure,
73 # and return a temporary one rather than the cached object.
74 run_bytecompile: T.ClassVar[T.Dict[str, bool]] = {}
75
76 def sanity(self, state: T.Optional['ModuleState'] = None) -> bool:
77 ret = super().sanity()
78 if ret:
79 self.platlib = self._get_path(state, 'platlib')
80 self.purelib = self._get_path(state, 'purelib')
81 self.run_bytecompile.setdefault(self.info['version'], False)
82 return ret
83
84 def _get_path(self, state: T.Optional['ModuleState'], key: str) -> str:
85 rel_path = self.info['install_paths'][key][1:]
86 if not state:
87 # This happens only from run_project_tests.py
88 return rel_path
89 value = T.cast('str', state.get_option(f'python.{key}dir'))
90 if value:
91 if state.is_user_defined_option('python.install_env'):
92 raise mesonlib.MesonException(f'python.{key}dir and python.install_env are mutually exclusive')
93 return value
94
95 install_env = state.get_option('python.install_env')
96 if install_env == 'auto':
97 install_env = 'venv' if self.info['is_venv'] else 'system'
98
99 if install_env == 'system':
100 rel_path = os.path.join(self.info['variables']['prefix'], rel_path)
101 elif install_env == 'venv':
102 if not self.info['is_venv']:
103 raise mesonlib.MesonException('python.install_env cannot be set to "venv" unless you are in a venv!')
104 # inside a venv, deb_system is *never* active hence info['paths'] may be wrong
105 rel_path = self.info['sysconfig_paths'][key]
106
107 return rel_path
108
109
110 _PURE_KW = KwargInfo('pure', (bool, NoneType))
111 _SUBDIR_KW = KwargInfo('subdir', str, default='')
112 _LIMITED_API_KW = KwargInfo('limited_api', str, default='', since='1.3.0')
113 _DEFAULTABLE_SUBDIR_KW = KwargInfo('subdir', (str, NoneType))
114
115 class PythonInstallation(ProgramHolder['PythonExternalProgram']):
116 def __init__(self, python: 'PythonExternalProgram', interpreter: 'Interpreter'):
117 ProgramHolder.__init__(self, python, interpreter)
118 info = python.info
119 prefix = self.interpreter.environment.coredata.optstore.get_value_for(OptionKey('prefix'))
120 assert isinstance(prefix, str), 'for mypy'
121
122 if python.build_config:
123 def as_(obj: object, type_: T.Type[_T]) -> _T:
124 assert isinstance(obj, type_), 'for mypy'
125 return obj
126
127 self.version = as_(python.build_config['language']['version'], str)
128 self.platform = as_(python.build_config['platform'], str)
129 self.suffix = as_(python.build_config['abi']['extension_suffix'], str)
130 self.limited_api_suffix = as_(python.build_config['abi']['stable_abi_suffix'], str)
131 self.link_libpython = as_(python.build_config['libpython']['link_extensions'], bool)
132 self.is_pypy = as_(python.build_config['implementation']['name'], str) == 'pypy'
133 else:
134 self.version = info['version']
135 self.platform = info['platform']
136 self.suffix = info['suffix']
137 self.limited_api_suffix = info['limited_api_suffix']
138 self.link_libpython = info['link_libpython']
139 self.is_pypy = info['is_pypy']
140
141 self.variables = info['variables']
142 self.paths = info['paths']
143 self.pure = python.pure
144 self.platlib_install_path = os.path.join(prefix, python.platlib)
145 self.purelib_install_path = os.path.join(prefix, python.purelib)
146
147 @typed_pos_args('python.extension_module', str, varargs=(str, mesonlib.File, CustomTarget, CustomTargetIndex, GeneratedList, StructuredSources, ExtractedObjects, BuildTarget))
148 @typed_kwargs(
149 'python.extension_module',
150 *_MOD_KWARGS,
151 _DEFAULTABLE_SUBDIR_KW,
152 _LIMITED_API_KW,
153 KwargInfo('install_dir', (str, bool, NoneType)),
154 )
155 @InterpreterObject.method('extension_module')
156 def extension_module_method(self, args: T.Tuple[str, T.List[BuildTargetSource]], kwargs: ExtensionModuleKw) -> 'SharedModule':
157 target_kwargs = T.cast('SharedModuleKw', {k: v for k, v in kwargs.items() if k not in {'install_dir', 'subdir', 'limited_api'}})
158 if kwargs['rust_abi'] is None and kwargs['rust_crate_type'] is None:
159 target_kwargs['rust_abi'] = 'c'
160
161 if kwargs['install_dir'] is not None:
162 if kwargs['subdir'] is not None:
163 raise InvalidArguments('"subdir" and "install_dir" are mutually exclusive')
164 # the build_target() method now expects this to be correct.
165 target_kwargs['install_dir'] = [kwargs['install_dir']]
166 else:
167 # We want to remove 'subdir', but it may be None and we want to replace it with ''
168 # It must be done this way since we don't allow both `install_dir`
169 # and `subdir` to be set at the same time
170 subdir = kwargs.get('subdir') or ''
171
172 target_kwargs['install_dir'] = [self._get_install_dir_impl(False, subdir)]
173
174 target_suffix = self.suffix
175
176 new_deps = kwargs['dependencies'].copy()
177 pydep = next((dep for dep in new_deps if isinstance(dep, _PythonDependencyBase)), None)
178 if pydep is None:
179 pydep = self._dependency_method_impl({'native': kwargs['native']})
180 if not pydep.found():
181 raise mesonlib.MesonException('Python dependency not found')
182 new_deps.append(pydep)
183 FeatureNew.single_use('python_installation.extension_module with implicit dependency on python',
184 '0.63.0', self.subproject, 'use python_installation.dependency()',
185 self.current_node)
186
187 limited_api_version = kwargs.get('limited_api')
188 allow_limited_api = self.interpreter.environment.coredata.optstore.get_value_for(OptionKey('python.allow_limited_api'))
189 if limited_api_version != '' and allow_limited_api:
190
191 target_suffix = self.limited_api_suffix
192
193 limited_api_version_hex = self._convert_api_version_to_py_version_hex(limited_api_version, pydep.version)
194 limited_api_definition = f'-DPy_LIMITED_API={limited_api_version_hex}'
195
196 new_c_args = kwargs['c_args'].copy()
197 new_c_args.append(limited_api_definition)
198 target_kwargs['c_args'] = new_c_args
199
200 new_cpp_args = kwargs['cpp_args'].copy()
201 new_cpp_args.append(limited_api_definition)
202 target_kwargs['cpp_args'] = new_cpp_args
203
204 # On Windows, the limited API DLL is python3.dll, not python3X.dll.
205 # FIXME: pydep.for_machine is nicer, but InternalDependency does not have the attribute
206 for_machine = self.interpreter.build.machine_map[kwargs['native']]
207 if self.interpreter.environment.machines[for_machine].is_windows():
208 pydep_copy = copy.copy(pydep)
209 if isinstance(pydep_copy, _PythonDependencyBase):
210 pydep_copy.find_libpy_windows(self.env, limited_api=True)
211 if not pydep_copy.found():
212 raise mesonlib.MesonException('Python dependency supporting limited API not found')
213
214 new_deps.remove(pydep)
215 new_deps.append(pydep_copy)
216
217 # When compiled under MSVC, Python's PC/pyconfig.h forcibly inserts pythonMAJOR.MINOR.lib
218 # into the linker path when not running in debug mode via a series #pragma comment(lib, "")
219 # directives. We manually override these here as this interferes with the intended
220 # use of the 'limited_api' kwarg
221 compilers = self.interpreter.environment.coredata.compilers[for_machine]
222 if any(compiler.get_id() == 'msvc' for compiler in compilers.values()):
223 pyver = pydep.version.replace('.', '')
224 python_windows_debug_link_exception = f'/NODEFAULTLIB:python{pyver}_d.lib'
225 python_windows_release_link_exception = f'/NODEFAULTLIB:python{pyver}.lib'
226
227 new_link_args = kwargs['link_args'].copy()
228
229 is_debug = self.interpreter.environment.coredata.optstore.get_value_for('debug')
230 if is_debug:
231 new_link_args.append(python_windows_debug_link_exception)
232 else:
233 new_link_args.append(python_windows_release_link_exception)
234
235 target_kwargs['link_args'] = new_link_args
236
237 target_kwargs['dependencies'] = new_deps
238
239 # msys2's python3 has "-cpython-36m.dll", we have to be clever
240 # FIXME: explain what the specific cleverness is here
241 split, target_suffix = target_suffix.rsplit('.', 1)
242 args = (args[0] + split, args[1])
243
244 target_kwargs['name_prefix'] = ''
245 target_kwargs['name_suffix'] = target_suffix
246
247 if kwargs['gnu_symbol_visibility'] == '' and \
248 (self.is_pypy or mesonlib.version_compare(self.version, '>=3.9')):
249 target_kwargs['gnu_symbol_visibility'] = 'inlineshidden'
250
251 return self.interpreter.build_target(
252 self.current_node, T.cast('T.Tuple[str, SourcesVarargsType]', args),
253 target_kwargs, SharedModule)
254
255 def _convert_api_version_to_py_version_hex(self, api_version: str, detected_version: str) -> str:
256 python_api_version_format = re.compile(r'[0-9]\.[0-9]{1,2}')
257 decimal_match = python_api_version_format.fullmatch(api_version)
258 if not decimal_match:
259 raise InvalidArguments(f'Python API version invalid: "{api_version}".')
260 if mesonlib.version_compare(api_version, '<3.2'):
261 raise InvalidArguments(f'Python Limited API version invalid: {api_version} (must be greater than 3.2)')
262 if mesonlib.version_compare(api_version, '>' + detected_version):
263 raise InvalidArguments(f'Python Limited API version too high: {api_version} (detected {detected_version})')
264
265 version_components = api_version.split('.')
266 major = int(version_components[0])
267 minor = int(version_components[1])
268
269 return '0x{:02x}{:02x}0000'.format(major, minor)
270
271 def _dependency_method_impl(self, kwargs: DependencyObjectKWs) -> Dependency:
272 for_machine = self.interpreter.build.machine_map[kwargs['native']]
273 kwargs['native'] = for_machine
274
275 identifier = get_dep_identifier(self._full_path(), kwargs)
276
277 dep = self.interpreter.coredata.deps[for_machine].get(identifier)
278 if dep is not None:
279 return dep
280
281 build_config = self.interpreter.environment.coredata.optstore.get_value_for(OptionKey('python.build_config'))
282 assert isinstance(build_config, str), 'for mypy'
283
284 new_kwargs = kwargs.copy()
285 new_kwargs['required'] = False
286 if build_config:
287 new_kwargs['build_config'] = build_config
288 candidates = python_factory(self.interpreter.environment, new_kwargs, self.held_object)
289 dep = find_external_dependency('python', self.interpreter.environment, new_kwargs, candidates)
290
291 self.interpreter.coredata.deps[for_machine].put(identifier, dep)
292 return dep
293
294 @noPosargs
295 @typed_kwargs(
296 'python_installation.dependency',
297 *DEPENDENCY_KWS,
298 KwargInfo('embed', bool, default=False, since='0.53.0'),
299 )
300 @disablerIfNotFound
301 @InterpreterObject.method('dependency')
302 def dependency_method(self, args: T.List['TYPE_var'], kwargs: FuncDependency) -> 'Dependency':
303 disabled, required, feature = extract_required_kwarg(kwargs, self.subproject)
304 nkwargs = T.cast('DependencyObjectKWs', kwargs.copy())
305 nkwargs['required'] = required
306 if disabled:
307 mlog.log('Dependency', mlog.bold('python'), 'skipped: feature', mlog.bold(feature), 'disabled')
308 return NotFoundDependency('python', self.interpreter.environment)
309 else:
310 dep = self._dependency_method_impl(nkwargs)
311 if required and not dep.found():
312 raise mesonlib.MesonException('Python dependency not found')
313 return dep
314
315 @typed_pos_args('install_data', varargs=(str, mesonlib.File))
316 @typed_kwargs(
317 'python_installation.install_sources',
318 _PURE_KW,
319 _SUBDIR_KW,
320 PRESERVE_PATH_KW,
321 KwargInfo('install_tag', (str, NoneType), since='0.60.0')
322 )
323 @InterpreterObject.method('install_sources')
324 def install_sources_method(self, args: T.Tuple[T.List[T.Union[str, mesonlib.File]]],
325 kwargs: 'PyInstallKw') -> list[Data]:
326 self.held_object.run_bytecompile[self.version] = True
327 tag = kwargs['install_tag'] or 'python-runtime'
328 pure = kwargs['pure'] if kwargs['pure'] is not None else self.pure
329 install_dir = self._get_install_dir_impl(pure, kwargs['subdir'])
330 return self.interpreter.install_data_impl(
331 self.interpreter.source_strings_to_files(args[0]),
332 install_dir,
333 mesonlib.FileMode(), rename=None, tag=tag, install_data_type='python',
334 preserve_path=kwargs['preserve_path'])
335
336 @noPosargs
337 @typed_kwargs('python_installation.install_dir', _PURE_KW, _SUBDIR_KW)
338 @InterpreterObject.method('get_install_dir')
339 def get_install_dir_method(self, args: T.List['TYPE_var'], kwargs: 'PyInstallKw') -> str:
340 self.held_object.run_bytecompile[self.version] = True
341 pure = kwargs['pure'] if kwargs['pure'] is not None else self.pure
342 return self._get_install_dir_impl(pure, kwargs['subdir'])
343
344 def _get_install_dir_impl(self, pure: bool, subdir: str) -> P_OBJ.OptionString:
345 if pure:
346 base = self.purelib_install_path
347 name = '{py_purelib}'
348 else:
349 base = self.platlib_install_path
350 name = '{py_platlib}'
351
352 return P_OBJ.OptionString(os.path.join(base, subdir), os.path.join(name, subdir))
353
354 @noPosargs
355 @noKwargs
356 @InterpreterObject.method('language_version')
357 def language_version_method(self, args: T.List['TYPE_var'], kwargs: 'TYPE_kwargs') -> str:
358 return self.version
359
360 @typed_pos_args('python_installation.has_path', str)
361 @noKwargs
362 @InterpreterObject.method('has_path')
363 def has_path_method(self, args: T.Tuple[str], kwargs: 'TYPE_kwargs') -> bool:
364 return args[0] in self.paths
365
366 @typed_pos_args('python_installation.get_path', str, optargs=[object])
367 @noKwargs
368 @InterpreterObject.method('get_path')
369 def get_path_method(self, args: T.Tuple[str, T.Optional['TYPE_var']], kwargs: 'TYPE_kwargs') -> 'TYPE_var':
370 path_name, fallback = args
371 try:
372 return self.paths[path_name]
373 except KeyError:
374 if fallback is not None:
375 return fallback
376 raise InvalidArguments(f'{path_name} is not a valid path name')
377
378 @typed_pos_args('python_installation.has_variable', str)
379 @noKwargs
380 @InterpreterObject.method('has_variable')
381 def has_variable_method(self, args: T.Tuple[str], kwargs: 'TYPE_kwargs') -> bool:
382 return args[0] in self.variables
383
384 @typed_pos_args('python_installation.get_variable', str, optargs=[object])
385 @noKwargs
386 @InterpreterObject.method('get_variable')
387 def get_variable_method(self, args: T.Tuple[str, T.Optional['TYPE_var']], kwargs: 'TYPE_kwargs') -> 'TYPE_var':
388 var_name, fallback = args
389 try:
390 return self.variables[var_name]
391 except KeyError:
392 if fallback is not None:
393 return fallback
394 raise InvalidArguments(f'{var_name} is not a valid variable name')
395
396 @noPosargs
397 @noKwargs
398 @FeatureNew('Python module path method', '0.50.0')
399 @InterpreterObject.method('path')
400 def path_method(self, args: T.List['TYPE_var'], kwargs: 'TYPE_kwargs') -> str:
401 return super().path_method(args, kwargs)
402
403
404 class PythonModule(ExtensionModule):
405
406 INFO = ModuleInfo('python', '0.46.0')
407
408 def __init__(self, interpreter: 'Interpreter') -> None:
409 super().__init__(interpreter)
410 self.installations: T.Dict[str, MaybePythonProg] = {}
411 self.methods.update({
412 'find_installation': self.find_installation,
413 })
414
415 def _get_install_scripts(self) -> T.List[mesonlib.ExecutableSerialisation]:
416 backend = self.interpreter.backend
417 ret: T.List[mesonlib.ExecutableSerialisation] = []
418 optlevel = self.interpreter.environment.coredata.optstore.get_value_for(OptionKey('python.bytecompile'))
419 if optlevel == -1:
420 return ret
421 if not any(PythonExternalProgram.run_bytecompile.values()):
422 return ret
423
424 installdata = backend.create_install_data()
425 py_files = []
426
427 def should_append(f: str, isdir: bool = False) -> bool:
428 # This uses the install_plan decorated names to see if the original source was propagated via
429 # install_sources() or get_install_dir().
430 return f.startswith(('{py_platlib}', '{py_purelib}')) and (f.endswith('.py') or isdir)
431
432 for t in installdata.targets:
433 if should_append(t.out_name):
434 py_files.append((t.out_name, os.path.join(installdata.prefix, t.outdir, os.path.basename(t.fname))))
435 for d in installdata.data:
436 if should_append(d.install_path_name):
437 py_files.append((d.install_path_name, os.path.join(installdata.prefix, d.install_path)))
438 for d in installdata.install_subdirs:
439 if should_append(d.install_path_name, True):
440 py_files.append((d.install_path_name, os.path.join(installdata.prefix, d.install_path)))
441
442 import importlib.resources
443 pycompile = os.path.join(self.interpreter.environment.get_scratch_dir(), 'pycompile.py')
444 with open(pycompile, 'wb') as f:
445 f.write(importlib.resources.read_binary('mesonbuild.scripts', 'pycompile.py'))
446
447 for i in self.installations.values():
448 if isinstance(i, PythonExternalProgram) and i.run_bytecompile[i.info['version']]:
449 manifest = f'python-{i.info["version"]}-installed.json'
450 manifest_json = []
451 for name, f in py_files:
452 if f.startswith((os.path.join(installdata.prefix, i.platlib), os.path.join(installdata.prefix, i.purelib))):
453 manifest_json.append(name)
454 with open(os.path.join(self.interpreter.environment.get_scratch_dir(), manifest), 'w', encoding='utf-8') as f:
455 json.dump(manifest_json, f)
456 cmd = i.command + [pycompile, manifest, str(optlevel)]
457
458 script = backend.get_executable_serialisation(cmd, verbose=True, tag='python-runtime',
459 installdir_map={'py_purelib': i.purelib, 'py_platlib': i.platlib})
460 ret.append(script)
461 return ret
462
463 def postconf_hook(self, b: Build) -> None:
464 b.install_scripts.extend(self._get_install_scripts())
465
466 # https://www.python.org/dev/peps/pep-0397/
467 @staticmethod
468 def _get_win_pythonpath(name_or_path: str) -> T.Optional[str]:
469 if not name_or_path.startswith(('python2', 'python3')):
470 return None
471 if not shutil.which('py'):
472 # program not installed, return without an exception
473 return None
474 ver = f'-{name_or_path[6:]}'
475 cmd = ['py', ver, '-c', "import sysconfig; print(sysconfig.get_config_var('BINDIR'))"]
476 _, stdout, _ = mesonlib.Popen_safe(cmd)
477 directory = stdout.strip()
478 if os.path.exists(directory):
479 return os.path.join(directory, 'python')
480 else:
481 return None
482
483 def _find_installation_impl(self, state: 'ModuleState', display_name: str, name_or_path: str, required: bool) -> MaybePythonProg:
484 build_config = self.interpreter.environment.coredata.optstore.get_value_for(OptionKey('python.build_config'))
485 assert isinstance(build_config, str), 'for mypy'
486
487 if not name_or_path:
488 python = PythonExternalProgram('python3', mesonlib.python_command, build_config_path=build_config)
489 else:
490 tmp_python = ExternalProgram.from_entry(display_name, name_or_path)
491 python = PythonExternalProgram(display_name, ext_prog=tmp_python, build_config_path=build_config)
492
493 if not python.found() and mesonlib.is_windows():
494 pythonpath = self._get_win_pythonpath(name_or_path)
495 if pythonpath is not None:
496 name_or_path = pythonpath
497 python = PythonExternalProgram(name_or_path)
498
499 # Last ditch effort, python2 or python3 can be named python
500 # on various platforms, let's not give up just yet, if an executable
501 # named python is available and has a compatible version, let's use
502 # it
503 if not python.found() and name_or_path in {'python2', 'python3'}:
504 tmp_python = ExternalProgram.from_entry(display_name, 'python')
505 python = PythonExternalProgram(name_or_path, ext_prog=tmp_python, build_config_path=build_config)
506
507 if python.found():
508 if python.sanity(state):
509 return python
510 else:
511 sanitymsg = f'{python} is not a valid python or it is missing distutils'
512 if required:
513 raise mesonlib.MesonException(sanitymsg)
514 else:
515 mlog.warning(sanitymsg, location=state.current_node)
516
517 return NonExistingExternalProgram(python.name)
518
519 @disablerIfNotFound
520 @typed_pos_args('python.find_installation', optargs=[str])
521 @typed_kwargs(
522 'python.find_installation',
523 REQUIRED_KW,
524 KwargInfo('disabler', bool, default=False, since='0.49.0'),
525 KwargInfo('modules', ContainerTypeInfo(list, str), listify=True, default=[], since='0.51.0'),
526 _PURE_KW.evolve(default=True, since='0.64.0'),
527 )
528 def find_installation(self, state: 'ModuleState', args: T.Tuple[T.Optional[str]],
529 kwargs: 'FindInstallationKw') -> MaybePythonProg:
530 feature_check = FeatureNew('Passing "feature" option to find_installation', '0.48.0')
531 disabled, required, feature = extract_required_kwarg(kwargs, state.subproject, feature_check)
532
533 # FIXME: this code is *full* of sharp corners. It assumes that it's
534 # going to get a string value (or now a list of length 1), of `python2`
535 # or `python3` which is completely nonsense. On windows the value could
536 # easily be `['py', '-3']`, or `['py', '-3.7']` to get a very specific
537 # version of python. On Linux we might want a python that's not in
538 # $PATH, or that uses a wrapper of some kind.
539 np: T.List[str] = state.environment.lookup_binary_entry(MachineChoice.HOST, 'python') or []
540 fallback = args[0]
541 display_name = fallback or 'python'
542 if not np and fallback is not None:
543 np = [fallback]
544 name_or_path = np[0] if np else None
545
546 if disabled:
547 mlog.log('Program', name_or_path or 'python', 'found:', mlog.red('NO'), '(disabled by:', mlog.bold(feature), ')')
548 return NonExistingExternalProgram()
549
550 python = self.installations.get(name_or_path)
551 if not python:
552 python = self._find_installation_impl(state, display_name, name_or_path, required)
553 self.installations[name_or_path] = python
554
555 want_modules = kwargs['modules']
556 found_modules: T.List[str] = []
557 missing_modules: T.List[str] = []
558 if python.found() and want_modules:
559 for mod in want_modules:
560 p, *_ = mesonlib.Popen_safe(
561 python.command +
562 ['-c', f'import {mod}'])
563 if p.returncode != 0:
564 missing_modules.append(mod)
565 else:
566 found_modules.append(mod)
567
568 msg: T.List['mlog.TV_Loggable'] = ['Program', python.name]
569 if want_modules:
570 msg.append('({})'.format(', '.join(want_modules)))
571 msg.append('found:')
572 if python.found() and not missing_modules:
573 msg.extend([mlog.green('YES'), '({})'.format(' '.join(python.command))])
574 else:
575 msg.append(mlog.red('NO'))
576 if found_modules:
577 msg.append('modules:')
578 msg.append(', '.join(found_modules))
579
580 mlog.log(*msg)
581
582 if not python.found():
583 if required:
584 raise mesonlib.MesonException('{} not found'.format(name_or_path or 'python'))
585 return NonExistingExternalProgram(python.name)
586 elif missing_modules:
587 if required:
588 raise mesonlib.MesonException('{} is missing modules: {}'.format(name_or_path or 'python', ', '.join(missing_modules)))
589 return NonExistingExternalProgram(python.name)
590 else:
591 assert isinstance(python, PythonExternalProgram), 'for mypy'
592 python = copy.copy(python)
593 python.pure = kwargs['pure']
594 return python
595
596 raise mesonlib.MesonBugException('Unreachable code was reached (PythonModule.find_installation).')
597
598
599 def initialize(interpreter: 'Interpreter') -> PythonModule:
600 mod = PythonModule(interpreter)
601 mod.interpreter.append_holder_map(PythonExternalProgram, PythonInstallation)
602 return mod