Debian Codegraph @

mesonbuild/utils/universal.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2012-2020 The Meson development team
3
4
5 """A library of random helper functionality."""
6
7 from __future__ import annotations
8 from pathlib import Path
9 import argparse
10 import ast
11 import copy
12 import enum
13 import sys
14 import stat
15 import time
16 import abc
17 import multiprocessing
18 import platform, subprocess, operator, os, shlex, shutil, re
19 import collections
20 from functools import lru_cache, wraps
21 from itertools import tee
22 from tempfile import TemporaryDirectory, NamedTemporaryFile
23 import typing as T
24 import textwrap
25 import pickle
26 import errno
27 import json
28 import dataclasses
29
30 from mesonbuild import mlog
31 from .core import MesonException, MesonBugException, HoldableObject, ExecutableSerialisation
32
33 if T.TYPE_CHECKING:
34 from typing_extensions import Literal, Protocol, Self
35
36 from .._typing import ImmutableListProtocol
37 from ..build import ConfigurationData
38 from ..cmdline import StrOrBytesPath
39 from ..environment import Environment
40 from ..compilers.compilers import Compiler
41
42 class _EnvPickleLoadable(Protocol):
43
44 environment: Environment
45
46 class _VerPickleLoadable(Protocol):
47
48 version: str
49
50 class Comparable(Protocol):
51 """Protocol for annotating comparable types."""
52 def __eq__(self, other: object) -> bool: ...
53 def __ne__(self, other: object) -> bool: ...
54 def __lt__(self, other: Self) -> bool: ...
55 def __le__(self, other: Self) -> bool: ...
56 def __ge__(self, other: Self) -> bool: ...
57 def __gt__(self, other: Self) -> bool: ...
58
59 # A generic type for pickle_load. This allows any type that has either a
60 # .version or a .environment to be passed.
61 _PL = T.TypeVar('_PL', bound=T.Union[_EnvPickleLoadable, _VerPickleLoadable])
62
63 FileLike = T.TypeVar('FileLike', bound='File' | str)
64
65 FileOrString = T.Union['File', str]
66
67 _P = T.ParamSpec('_P')
68 _T = T.TypeVar('_T')
69 _U = T.TypeVar('_U')
70
71 __all__ = [
72 'GIT',
73 'ROOT_SUBPROJECT',
74 'SimpleABC',
75 'python_command',
76 'NoProjectVersion',
77 'project_meson_versions',
78 'SecondLevelHolder',
79 'SubProject',
80 'File',
81 'FileMode',
82 'GitException',
83 'LibType',
84 'MachineChoice',
85 'ThreeMachineChoice',
86 'EnvironmentException',
87 'FileOrString',
88 'GitException',
89 'InstallScript',
90 'InstallScriptFailure',
91 'dump_conf_header',
92 'OrderedSet',
93 'PerMachine',
94 'PerMachineDefaultable',
95 'PerThreeMachine',
96 'PerThreeMachineDefaultable',
97 'ProgressBar',
98 'Range',
99 'RealPathAction',
100 'TemporaryDirectoryWinProof',
101 'Version',
102 'check_direntry_issues',
103 'classify_unity_sources',
104 'current_vs_supports_modules',
105 'darwin_get_object_archs',
106 'default_libdir',
107 'default_libexecdir',
108 'default_prefix',
109 'default_datadir',
110 'default_includedir',
111 'default_infodir',
112 'default_localedir',
113 'default_mandir',
114 'default_sbindir',
115 'default_sysconfdir',
116 'detect_subprojects',
117 'detect_vcs',
118 'determine_worker_count',
119 'do_conf_file',
120 'do_conf_str',
121 'do_replacement',
122 'expand_arguments',
123 'extract_as_list',
124 'first',
125 'generate_list',
126 'get_compiler_for_source',
127 'get_filenames_templates_dict',
128 'get_rsp_threshold',
129 'get_subproject_dir',
130 'get_variable_regex',
131 'get_wine_shortpath',
132 'git',
133 'has_path_sep',
134 'is_aix',
135 'is_android',
136 'is_ascii_string',
137 'is_cygwin',
138 'is_debianlike',
139 'is_dragonflybsd',
140 'is_freebsd',
141 'is_fuchsia',
142 'is_haiku',
143 'is_hurd',
144 'is_irix',
145 'is_linux',
146 'is_netbsd',
147 'is_openbsd',
148 'is_os2',
149 'is_osx',
150 'is_parent_path',
151 'is_qnx',
152 'is_sunos',
153 'is_windows',
154 'is_wsl',
155 'iter_regexin_iter',
156 'join_args',
157 'late_property',
158 'lazy_property',
159 'listify',
160 'listify_array_value',
161 'lookahead',
162 'lookbehind',
163 'partition',
164 'path_is_in_root',
165 'pathname_sort_key',
166 'pickle_load',
167 'Popen_safe',
168 'Popen_safe_logged',
169 'quiet_git',
170 'quote_arg',
171 'relative_to_if_possible',
172 'relpath',
173 'replace_if_different',
174 'run_once',
175 'get_meson_command',
176 'set_meson_command',
177 'split_args',
178 'stringlistify',
179 'underscorify',
180 'substitute_values',
181 'substring_is_in_list',
182 'typeslistify',
183 'unique_list',
184 'unwrap',
185 'unwrap_err',
186 'verbose_git',
187 'version_check_to_range',
188 'version_compare',
189 'version_compare_condition_with_min',
190 'version_compare_many',
191 'search_version',
192 'windows_detect_native_arch',
193 'windows_proof_rm',
194 'windows_proof_rmtree',
195 ]
196
197 SubProject = T.NewType('SubProject', str)
198
199 ROOT_SUBPROJECT = SubProject('')
200
201 class NoProjectVersion:
202 pass
203
204 # TODO: this is such a hack, this really should be either in coredata or in the
205 # interpreter
206 # {subproject: project_meson_version}
207 project_meson_versions: T.Dict[str, T.Union[Range[Version], NoProjectVersion]] = {}
208
209
210 from glob import glob
211
212 if getattr(sys, 'frozen', False):
213 # Using e.g. a PyInstaller bundle, such as the MSI installed executable.
214 # It is conventional for freeze programs to set this attribute to indicate
215 # that the program is self hosted, and for example there is no associated
216 # "python" executable.
217 python_command = [sys.executable, 'runpython']
218 else:
219 python_command = [sys.executable]
220 _meson_command: T.Optional['ImmutableListProtocol[str]'] = None
221
222
223 class EnvironmentException(MesonException):
224 '''Exceptions thrown while processing and creating the build environment'''
225
226 class GitException(MesonException):
227 def __init__(self, msg: str, output: T.Optional[str] = None):
228 super().__init__(msg)
229 self.output = output.strip() if output else ''
230
231 GIT = shutil.which('git')
232 def git(cmd: T.List[str], workingdir: StrOrBytesPath, check: bool = False, **kwargs: T.Any) -> T.Tuple[subprocess.Popen[str], str, str]:
233 cmd = [unwrap(GIT, 'Callers should make sure it exists'), *cmd]
234 p, o, e = Popen_safe(cmd, cwd=workingdir, **kwargs)
235 if check and p.returncode != 0:
236 raise GitException('Git command failed: ' + str(cmd), e)
237 return p, o, e
238
239 def quiet_git(cmd: T.List[str], workingdir: StrOrBytesPath, check: bool = False) -> T.Tuple[bool, str]:
240 if not GIT:
241 m = 'Git program not found.'
242 if check:
243 raise GitException(m)
244 return False, m
245 p, o, e = git(cmd, workingdir, check)
246 if p.returncode != 0:
247 return False, e
248 return True, o
249
250 def verbose_git(cmd: T.List[str], workingdir: StrOrBytesPath, check: bool = False) -> bool:
251 if not GIT:
252 m = 'Git program not found.'
253 if check:
254 raise GitException(m)
255 return False
256 p, _, _ = git(cmd, workingdir, check, stdout=None, stderr=None)
257 return p.returncode == 0
258
259 def set_meson_command(mainfile: str) -> None:
260 global _meson_command # pylint: disable=global-statement
261 # On UNIX-like systems `meson` is a Python script
262 # On Windows `meson` and `meson.exe` are wrapper exes
263 if not mainfile.endswith('.py'):
264 _meson_command = [mainfile]
265 elif os.path.isabs(mainfile) and mainfile.endswith('mesonmain.py'):
266 # Can't actually run meson with an absolute path to mesonmain.py, it must be run as -m mesonbuild.mesonmain
267 _meson_command = python_command + ['-m', 'mesonbuild.mesonmain']
268 else:
269 # Either run uninstalled, or full path to meson-script.py
270 _meson_command = python_command + [mainfile]
271 # We print this value for unit tests.
272 if 'MESON_COMMAND_TESTS' in os.environ:
273 mlog.log(f'meson_command is {_meson_command!r}')
274
275
276 def get_meson_command() -> ImmutableListProtocol[str]:
277 if _meson_command is None:
278 raise MesonBugException('Attempting to use meson_command before it is set')
279 return _meson_command
280
281
282 def is_ascii_string(astring: T.Union[str, bytes]) -> bool:
283 try:
284 if isinstance(astring, str):
285 astring.encode('ascii')
286 elif isinstance(astring, bytes):
287 astring.decode('ascii')
288 except UnicodeDecodeError:
289 return False
290 return True
291
292
293 def check_direntry_issues(direntry_array: T.Iterable[object]) -> None:
294 import locale
295 # Warn if the locale is not UTF-8. This can cause various unfixable issues
296 # such as os.stat not being able to decode filenames with unicode in them.
297 # There is no way to reset both the preferred encoding and the filesystem
298 # encoding, so we can just warn about it.
299 e = locale.getpreferredencoding()
300 if e.upper() != 'UTF-8' and not is_windows():
301 if isinstance(direntry_array, (str, bytes)):
302 direntry_array = [direntry_array]
303 for de in direntry_array:
304 if isinstance(de, (str, bytes)) and not is_ascii_string(de):
305 mlog.warning(textwrap.dedent(f'''
306 You are using {e!r} which is not a Unicode-compatible
307 locale but you are trying to access a file system entry called {de!r} which is
308 not pure ASCII. This may cause problems.
309 '''))
310
311
312 class SimpleABC(type):
313 '''Lightweight replacement for ``abc.ABCMeta``.
314
315 Supports ``@abc.abstractmethod`` but omits virtual subclass
316 registration and ``__subclasshook__``. This way, ``isinstance()``
317 goes through the C fast path. '''
318
319 __abstractmethods__: T.FrozenSet[str]
320
321 def __new__(mcs, name: str, bases: T.Tuple[type, ...],
322 namespace: T.Dict[str, T.Any], **kwargs: T.Any) -> SimpleABC:
323 cls = super().__new__(mcs, name, bases, namespace, **kwargs)
324 abstracts = {n for n, v in namespace.items()
325 if getattr(v, '__isabstractmethod__', False)}
326 for base in bases:
327 for n in getattr(base, '__abstractmethods__', ()):
328 if getattr(getattr(cls, n, None), '__isabstractmethod__', False):
329 abstracts.add(n)
330 cls.__abstractmethods__ = frozenset(abstracts)
331 return cls
332
333 def __call__(cls, *args: T.Any, **kwargs: T.Any) -> T.Any:
334 if cls.__abstractmethods__:
335 raise TypeError(
336 f"Can't instantiate abstract class {cls.__name__} without an "
337 f"implementation for abstract method"
338 f"{'s' if len(cls.__abstractmethods__) > 1 else ''} "
339 f"{', '.join(repr(m) for m in sorted(cls.__abstractmethods__))}")
340 return super().__call__(*args, **kwargs)
341
342
343 class SecondLevelHolder(HoldableObject, metaclass=SimpleABC):
344 ''' A second level object holder. The primary purpose
345 of such objects is to hold multiple objects with one
346 default option. '''
347
348 @abc.abstractmethod
349 def get_default_object(self) -> HoldableObject: ...
350
351 class FileMode:
352 # The first triad is for owner permissions, the second for group permissions,
353 # and the third for others (everyone else).
354 # For the 1st character:
355 # 'r' means can read
356 # '-' means not allowed
357 # For the 2nd character:
358 # 'w' means can write
359 # '-' means not allowed
360 # For the 3rd character:
361 # 'x' means can execute
362 # 's' means can execute and setuid/setgid is set (owner/group triads only)
363 # 'S' means cannot execute and setuid/setgid is set (owner/group triads only)
364 # 't' means can execute and sticky bit is set ("others" triads only)
365 # 'T' means cannot execute and sticky bit is set ("others" triads only)
366 # '-' means none of these are allowed
367 #
368 # The meanings of 'rwx' perms is not obvious for directories; see:
369 # https://www.hackinglinuxexposed.com/articles/20030424.html
370 #
371 # For information on this notation such as setuid/setgid/sticky bits, see:
372 # https://en.wikipedia.org/wiki/File_system_permissions#Symbolic_notation
373 symbolic_perms_regex = re.compile('[r-][w-][xsS-]' # Owner perms
374 '[r-][w-][xsS-]' # Group perms
375 '[r-][w-][xtT-]') # Others perms
376
377 def __init__(self, perms: T.Optional[str] = None, owner: T.Union[str, int, None] = None,
378 group: T.Union[str, int, None] = None):
379 self.perms_s = perms
380 self.perms = self.perms_s_to_bits(perms)
381 self.owner = owner
382 self.group = group
383
384 def __repr__(self) -> str:
385 ret = '<FileMode: {!r} owner={} group={}'
386 return ret.format(self.perms_s, self.owner, self.group)
387
388 @classmethod
389 def perms_s_to_bits(cls, perms_s: T.Optional[str]) -> int:
390 '''
391 Does the opposite of stat.filemode(), converts strings of the form
392 'rwxr-xr-x' to st_mode enums which can be passed to os.chmod()
393 '''
394 if perms_s is None:
395 # No perms specified, we will not touch the permissions
396 return -1
397 eg = 'rwxr-xr-x'
398 if not isinstance(perms_s, str):
399 raise MesonException(f'Install perms must be a string. For example, {eg!r}')
400 if len(perms_s) != 9 or not cls.symbolic_perms_regex.match(perms_s):
401 raise MesonException(f'File perms {perms_s!r} must be exactly 9 chars. For example, {eg!r}')
402 perms = 0
403 # Owner perms
404 if perms_s[0] == 'r':
405 perms |= stat.S_IRUSR
406 if perms_s[1] == 'w':
407 perms |= stat.S_IWUSR
408 if perms_s[2] == 'x':
409 perms |= stat.S_IXUSR
410 elif perms_s[2] == 'S':
411 perms |= stat.S_ISUID
412 elif perms_s[2] == 's':
413 perms |= stat.S_IXUSR
414 perms |= stat.S_ISUID
415 # Group perms
416 if perms_s[3] == 'r':
417 perms |= stat.S_IRGRP
418 if perms_s[4] == 'w':
419 perms |= stat.S_IWGRP
420 if perms_s[5] == 'x':
421 perms |= stat.S_IXGRP
422 elif perms_s[5] == 'S':
423 perms |= stat.S_ISGID
424 elif perms_s[5] == 's':
425 perms |= stat.S_IXGRP
426 perms |= stat.S_ISGID
427 # Others perms
428 if perms_s[6] == 'r':
429 perms |= stat.S_IROTH
430 if perms_s[7] == 'w':
431 perms |= stat.S_IWOTH
432 if perms_s[8] == 'x':
433 perms |= stat.S_IXOTH
434 elif perms_s[8] == 'T':
435 perms |= stat.S_ISVTX
436 elif perms_s[8] == 't':
437 perms |= stat.S_IXOTH
438 perms |= stat.S_ISVTX
439 return perms
440
441 dot_C_dot_H_warning = """You are using .C or .H files in your project. This is deprecated.
442 Currently, Meson treats this as C++ code, but they
443 used to be treated as C code.
444 Note that the situation is a bit more complex if you are using the
445 Visual Studio compiler, as it treats .C files as C code, unless you add
446 the /TP compiler flag, but this is unreliable.
447 See https://github.com/mesonbuild/meson/pull/8747 for the discussions."""
448 class File(HoldableObject):
449 def __init__(self, is_built: bool, subdir: str, fname: str):
450 if fname.endswith(".C") or fname.endswith(".H"):
451 mlog.warning(dot_C_dot_H_warning, once=True)
452 self.is_built = is_built
453 self.subdir = subdir
454 self.fname = fname
455 self.hash = hash((is_built, subdir, fname))
456
457 def __str__(self) -> str:
458 return self.relative_name()
459
460 def __repr__(self) -> str:
461 ret = '<File: {0}'
462 if not self.is_built:
463 ret += ' (not built)'
464 ret += '>'
465 return ret.format(self.relative_name())
466
467 @staticmethod
468 @lru_cache(maxsize=None)
469 def from_source_file(source_root: str, subdir: str, fname: str) -> File:
470 if not os.path.isfile(os.path.join(source_root, subdir, fname)):
471 raise MesonException(f'File {fname} does not exist.')
472 return File(False, subdir, fname)
473
474 @staticmethod
475 @lru_cache(maxsize=None)
476 def from_built_file(subdir: str, fname: str) -> 'File':
477 return File(True, subdir, fname)
478
479 @staticmethod
480 @lru_cache(maxsize=None)
481 def from_built_relative(relative: str) -> 'File':
482 dirpart, fnamepart = os.path.split(relative)
483 return File.from_built_file(dirpart, fnamepart)
484
485 @staticmethod
486 def from_absolute_file(fname: str) -> 'File':
487 return File(False, '', fname)
488
489 @lru_cache(maxsize=None)
490 def rel_to_builddir(self, build_to_src: str) -> str:
491 if self.is_built:
492 return self.relative_name()
493 else:
494 return os.path.join(build_to_src, self.subdir, self.fname)
495
496 @lru_cache(maxsize=None)
497 def absolute_path(self, srcdir: str, builddir: str) -> str:
498 absdir = srcdir
499 if self.is_built:
500 absdir = builddir
501 return os.path.normpath(os.path.join(absdir, self.relative_name()))
502
503 @property
504 def suffix(self) -> str:
505 return os.path.splitext(self.fname)[1][1:].lower()
506
507 def endswith(self, ending: T.Union[str, T.Tuple[str, ...]]) -> bool:
508 return self.fname.endswith(ending)
509
510 def split(self, s: str, maxsplit: int = -1) -> T.List[str]:
511 return self.fname.split(s, maxsplit=maxsplit)
512
513 def rsplit(self, s: str, maxsplit: int = -1) -> T.List[str]:
514 return self.fname.rsplit(s, maxsplit=maxsplit)
515
516 def __eq__(self, other: object) -> bool:
517 if not isinstance(other, File):
518 return NotImplemented
519 if self.hash != other.hash:
520 return False
521 return (self.fname, self.subdir, self.is_built) == (other.fname, other.subdir, other.is_built)
522
523 def __hash__(self) -> int:
524 return self.hash
525
526 @lru_cache(maxsize=None)
527 def relative_name(self) -> str:
528 return os.path.join(self.subdir, self.fname)
529
530
531 def get_compiler_for_source(compilers: T.Iterable['Compiler'], src: 'FileOrString') -> 'Compiler':
532 """Given a set of compilers and a source, find the compiler for that source type."""
533 for comp in compilers:
534 if comp.can_compile(src):
535 return comp
536 raise MesonException(f'No specified compiler can handle file {src!s}')
537
538
539 def classify_unity_sources(compilers: T.Iterable['Compiler'], sources: T.List[FileLike]) -> T.Dict['Compiler', T.List[FileLike]]:
540 compsrclist: T.Dict['Compiler', T.List[FileLike]] = {}
541 for src in sources:
542 comp = get_compiler_for_source(compilers, src)
543 if comp not in compsrclist:
544 compsrclist[comp] = [src]
545 else:
546 compsrclist[comp].append(src)
547 return compsrclist
548
549
550 MACHINE_NAMES = ['build', 'host', 'target']
551 MACHINE_PREFIXES = ['build.', '']
552
553
554 class MachineChoice(enum.IntEnum):
555
556 """Enum class representing one of the two abstract machine names used in
557 most places: the build, and host, machines.
558 """
559
560 BUILD = 0
561 HOST = 1
562
563 def __str__(self) -> str:
564 return f'{self.get_lower_case_name()} machine'
565
566 def get_lower_case_name(self) -> str:
567 return MACHINE_NAMES[self.value]
568
569 def get_prefix(self) -> str:
570 return MACHINE_PREFIXES[self.value]
571
572
573 class ThreeMachineChoice(enum.IntEnum):
574
575 """Enum class representing any of the three abstract machine names:
576 the build, host, and target, machines.
577 """
578
579 BUILD = MachineChoice.BUILD.value
580 HOST = MachineChoice.HOST.value
581 TARGET = 2
582
583 def __str__(self) -> str:
584 return f'{self.get_lower_case_name()} machine'
585
586 def get_lower_case_name(self) -> str:
587 return MACHINE_NAMES[self.value]
588
589
590 @dataclasses.dataclass(eq=False, order=False)
591 class PerMachine(T.Generic[_T]):
592 build: _T
593 host: _T
594
595 def __getitem__(self, machine: MachineChoice) -> _T:
596 return [self.build, self.host][machine.value]
597
598 def __setitem__(self, machine: MachineChoice, val: _T) -> None:
599 setattr(self, machine.get_lower_case_name(), val)
600
601 def miss_defaulting(self) -> PerMachineDefaultable[T.Optional[_T]]:
602 """Unset definition duplicated from their previous to None
603
604 This is the inverse of ''default_missing''. By removing defaulted
605 machines, we can elaborate the original and then redefault them and thus
606 avoid repeating the elaboration explicitly.
607 """
608 unfreeze: PerMachineDefaultable[T.Optional[_T]] = PerMachineDefaultable()
609 unfreeze.build = self.build
610 unfreeze.host = self.host
611 if unfreeze.host == unfreeze.build:
612 unfreeze.host = None
613 return unfreeze
614
615 def assign(self, build: _T, host: _T) -> None:
616 self.build = build
617 self.host = host
618
619 def __copy__(self) -> PerMachine[_T]:
620 build = copy.copy(self.build)
621 if self.host is self.build:
622 host = build
623 else:
624 host = copy.copy(self.host)
625 return PerMachine(build, host)
626
627
628 @dataclasses.dataclass(eq=False, order=False)
629 class PerThreeMachine(PerMachine[_T]):
630 """Like `PerMachine` but includes `target` too.
631
632 It turns out just one thing do we need track the target machine. There's no
633 need to computer the `target` field so we don't bother overriding the
634 `__getitem__`/`__setitem__` methods.
635 """
636
637 target: _T
638
639 def __getitem__(self, machine: MachineChoice | ThreeMachineChoice) -> _T:
640 return [self.build, self.host, self.target][machine.value]
641
642 def __setitem__(self, machine: MachineChoice | ThreeMachineChoice, val: _T) -> None:
643 setattr(self, machine.get_lower_case_name(), val)
644
645 def miss_defaulting(self) -> "PerThreeMachineDefaultable[_T]":
646 """Unset definition duplicated from their previous to None
647
648 This is the inverse of ''default_missing''. By removing defaulted
649 machines, we can elaborate the original and then redefault them and thus
650 avoid repeating the elaboration explicitly.
651 """
652 unfreeze: PerThreeMachineDefaultable[_T] = PerThreeMachineDefaultable()
653 unfreeze.build = self.build
654 unfreeze.host = self.host
655 unfreeze.target = self.target
656 if unfreeze.target == unfreeze.host:
657 unfreeze.target = None
658 if unfreeze.host == unfreeze.build:
659 unfreeze.host = None
660 return unfreeze
661
662 def matches_build_machine(self, machine: MachineChoice) -> bool:
663 return self.build == self[machine]
664
665 def __copy__(self) -> PerMachine[_T]:
666 build = copy.copy(self.build)
667 if self.host is self.build:
668 host = build
669 else:
670 host = copy.copy(self.host)
671
672 if self.target is self.host:
673 target = host
674 else:
675 target = copy.copy(self.target)
676
677 return PerThreeMachine(build, host, target)
678
679
680 @dataclasses.dataclass(eq=False, order=False)
681 class PerMachineDefaultable(PerMachine[T.Optional[_T]]):
682 """Extends `PerMachine` with the ability to default from `None`s.
683 """
684
685 build: T.Optional[_T] = None
686 host: T.Optional[_T] = None
687
688 def default_missing(self) -> PerMachine[_T]:
689 """Default host to build
690
691 This allows just specifying nothing in the native case, and just host in the
692 cross non-compiler case.
693 """
694 build = unwrap(self.build, 'Cannot fill in missing when all fields are empty')
695 return PerMachine(build, self.host if self.host is not None else build)
696
697 @classmethod
698 def default(cls, is_cross: bool, build: _T, host: _T) -> PerMachine[_T]:
699 """Easy way to get a defaulted value
700
701 This allows simplifying the case where you can control whether host and
702 build are separate or not with a boolean. If the is_cross value is set
703 to true then the optional host value will be used, otherwise the host
704 will be set to the build value.
705 """
706 m = cls(build)
707 if is_cross:
708 m.host = host
709 return m.default_missing()
710
711
712 @dataclasses.dataclass(eq=False, order=False)
713 class PerThreeMachineDefaultable(PerMachineDefaultable[T.Optional[_T]], PerThreeMachine[T.Optional[_T]]):
714 """Extends `PerThreeMachine` with the ability to default from `None`s.
715 """
716
717 target: T.Optional[_T] = None
718
719 def default_missing(self) -> PerThreeMachine[_T]:
720 """Default host to build and target to host.
721
722 This allows just specifying nothing in the native case, just host in the
723 cross non-compiler case, and just target in the native-built
724 cross-compiler case.
725 """
726 build = unwrap(self.build, 'Cannot fill in missing when all fields are empty')
727 host = self.host if self.host is not None else build
728 target = self.target if self.target is not None else host
729 return PerThreeMachine(build, host, target)
730
731 @dataclasses.dataclass(eq=False)
732 class InstallScriptFailure:
733
734 name: str
735 reason: str
736 tag: T.Optional[str] = None
737
738 subproject = ROOT_SUBPROJECT
739
740 InstallScript = T.Union[ExecutableSerialisation, InstallScriptFailure]
741
742 _PLATFORM_SYSTEM_LOWER = platform.system().lower()
743 _PLATFORM_RELEASE_LOWER = platform.release().lower()
744
745 def is_sunos() -> bool:
746 return _PLATFORM_SYSTEM_LOWER == 'sunos'
747
748
749 def is_osx() -> bool:
750 return _PLATFORM_SYSTEM_LOWER == 'darwin'
751
752
753 def is_linux() -> bool:
754 return _PLATFORM_SYSTEM_LOWER == 'linux'
755
756
757 def is_android() -> bool:
758 return _PLATFORM_SYSTEM_LOWER == 'android'
759
760
761 def is_fuchsia() -> bool:
762 return _PLATFORM_SYSTEM_LOWER == 'fuchsia'
763
764
765 def is_haiku() -> bool:
766 return _PLATFORM_SYSTEM_LOWER == 'haiku'
767
768
769 def is_openbsd() -> bool:
770 return _PLATFORM_SYSTEM_LOWER == 'openbsd'
771
772
773 def is_windows() -> bool:
774 return _PLATFORM_SYSTEM_LOWER == 'windows'
775
776 def is_wsl() -> bool:
777 return is_linux() and 'microsoft' in _PLATFORM_RELEASE_LOWER
778
779 def is_cygwin() -> bool:
780 return sys.platform == 'cygwin'
781
782
783 def is_debianlike() -> bool:
784 return os.path.isfile('/etc/debian_version')
785
786
787 def is_dragonflybsd() -> bool:
788 return _PLATFORM_SYSTEM_LOWER == 'dragonfly'
789
790
791 def is_netbsd() -> bool:
792 return _PLATFORM_SYSTEM_LOWER == 'netbsd'
793
794
795 def is_freebsd() -> bool:
796 return _PLATFORM_SYSTEM_LOWER == 'freebsd'
797
798 def is_irix() -> bool:
799 return _PLATFORM_SYSTEM_LOWER == 'irix'
800
801 def is_hurd() -> bool:
802 return platform.system().lower() == 'gnu'
803
804 def is_qnx() -> bool:
805 return platform.system().lower() == 'qnx'
806
807 def is_aix() -> bool:
808 return platform.system().lower() == 'aix'
809
810 def is_os2() -> bool:
811 return platform.system().lower() == 'os/2'
812
813 @lru_cache(maxsize=None)
814 def darwin_get_object_archs(objpath: str) -> 'ImmutableListProtocol[str]':
815 '''
816 For a specific object (executable, static library, dylib, etc), run `lipo`
817 to fetch the list of archs supported by it. Supports both thin objects and
818 'fat' objects.
819 '''
820 _, stdo, stderr = Popen_safe(['lipo', '-info', objpath])
821 if not stdo:
822 mlog.debug(f'lipo {objpath}: {stderr}')
823 return None
824 stdo = stdo.rsplit(': ', 1)[1]
825
826 # Convert from lipo-style archs to meson-style CPUs
827 map_arch = {
828 'i386': 'x86',
829 'arm64': 'aarch64',
830 'arm64e': 'aarch64',
831 'ppc7400': 'ppc',
832 'ppc970': 'ppc',
833 }
834 lipo_archs = stdo.split()
835 meson_archs = [map_arch.get(lipo_arch, lipo_arch) for lipo_arch in lipo_archs]
836
837 # Add generic name for armv7 and armv7s
838 if 'armv7' in stdo:
839 meson_archs.append('arm')
840
841 return meson_archs
842
843 def windows_detect_native_arch() -> str:
844 """
845 The architecture of Windows itself: x86, amd64 or arm64
846 """
847 if sys.platform != 'win32':
848 return ''
849 try:
850 import ctypes
851 process_arch = ctypes.c_ushort()
852 native_arch = ctypes.c_ushort()
853 kernel32 = ctypes.windll.kernel32
854 process = ctypes.c_void_p(kernel32.GetCurrentProcess())
855 # This is the only reliable way to detect an arm system if we are an x86/x64 process being emulated
856 if kernel32.IsWow64Process2(process, ctypes.byref(process_arch), ctypes.byref(native_arch)):
857 # https://docs.microsoft.com/en-us/windows/win32/sysinfo/image-file-machine-constants
858 if native_arch.value == 0x8664:
859 return 'amd64'
860 elif native_arch.value == 0x014C:
861 return 'x86'
862 elif native_arch.value == 0xAA64:
863 return 'arm64'
864 elif native_arch.value == 0x01C4:
865 return 'arm'
866 except (OSError, AttributeError):
867 pass
868 # These env variables are always available. See:
869 # https://msdn.microsoft.com/en-us/library/aa384274(VS.85).aspx
870 # https://blogs.msdn.microsoft.com/david.wang/2006/03/27/howto-detect-process-bitness/
871 arch = os.environ.get('PROCESSOR_ARCHITEW6432', '').lower()
872 if not arch:
873 try:
874 # If this doesn't exist, something is messing with the environment
875 arch = os.environ['PROCESSOR_ARCHITECTURE'].lower()
876 except KeyError:
877 raise EnvironmentException('Unable to detect native OS architecture')
878 return arch
879
880 @dataclasses.dataclass
881 class VcsData:
882 name: str
883 cmd: str
884 repo_dir: str
885 get_rev: T.List[str]
886 rev_regex: str
887 dep: str
888 wc_dir: T.Optional[str] = None
889 repo_can_be_file: bool = False
890
891 def repo_exists(self, curdir: Path) -> bool:
892 if not shutil.which(self.cmd):
893 return False
894
895 repo = curdir / self.repo_dir
896 if repo.is_dir():
897 return True
898 if repo.is_file() and self.repo_can_be_file:
899 return True
900
901 return False
902
903
904 def detect_vcs(source_dir: T.Union[str, Path]) -> T.Optional[VcsData]:
905 vcs_systems = [
906 VcsData(
907 name = 'git',
908 cmd = 'git',
909 repo_dir = '.git',
910 get_rev = ['git', 'describe', '--dirty=+', '--always'],
911 rev_regex = '(.*)',
912 dep = '.git/logs/HEAD',
913 repo_can_be_file=True,
914 ),
915 VcsData(
916 name = 'mercurial',
917 cmd = 'hg',
918 repo_dir = '.hg',
919 get_rev = ['hg', 'id', '-i'],
920 rev_regex = '(.*)',
921 dep= '.hg/dirstate',
922 ),
923 VcsData(
924 name = 'subversion',
925 cmd = 'svn',
926 repo_dir = '.svn',
927 get_rev = ['svn', 'info'],
928 rev_regex = 'Revision: (.*)',
929 dep = '.svn/wc.db',
930 ),
931 VcsData(
932 name = 'bazaar',
933 cmd = 'bzr',
934 repo_dir = '.bzr',
935 get_rev = ['bzr', 'revno'],
936 rev_regex = '(.*)',
937 dep = '.bzr',
938 ),
939 ]
940 if isinstance(source_dir, str):
941 source_dir = Path(source_dir)
942
943 parent_paths_and_self = collections.deque(source_dir.parents)
944 # Prepend the source directory to the front so we can check it;
945 # source_dir.parents doesn't include source_dir
946 parent_paths_and_self.appendleft(source_dir)
947 for curdir in parent_paths_and_self:
948 for vcs in vcs_systems:
949 if vcs.repo_exists(curdir):
950 vcs.wc_dir = str(curdir)
951 return vcs
952 return None
953
954 def current_vs_supports_modules() -> bool:
955 # if in a developer terminal, the version is available
956 # and can be used to avoid using modules for older versions
957 # of the MSVC executable.
958 vsver = os.environ.get('VSCMD_VER', '')
959 return not vsver \
960 or version_compare(vsver, '>=16.10.0') \
961 or (vsver.startswith('16.9.0') and '-pre.' in vsver)
962
963 _VERSION_TOK_RE = re.compile(r'(\d+)|([a-zA-Z]+)')
964
965 # a helper class which implements the same version ordering as RPM
966 class Version:
967 def __init__(self, s: str) -> None:
968 self._s = s
969
970 # extract numeric and alphabetic sequences
971 # numeric sequences are converted from strings to ints
972 self._v = [
973 int(m.group(1)) if m.group(1) else m.group(2)
974 for m in _VERSION_TOK_RE.finditer(s)]
975
976 def __str__(self) -> str:
977 return self._s
978
979 def __repr__(self) -> str:
980 return f'<Version: {self._s!r} V={self._v!r}>'
981
982 def __lt__(self, other: object) -> bool:
983 if isinstance(other, Version):
984 return self.__cmp(other, operator.lt)
985 return NotImplemented
986
987 def __gt__(self, other: object) -> bool:
988 if isinstance(other, Version):
989 return self.__cmp(other, operator.gt)
990 return NotImplemented
991
992 def __le__(self, other: object) -> bool:
993 if isinstance(other, Version):
994 return self.__cmp(other, operator.le)
995 return NotImplemented
996
997 def __ge__(self, other: object) -> bool:
998 if isinstance(other, Version):
999 return self.__cmp(other, operator.ge)
1000 return NotImplemented
1001
1002 def __eq__(self, other: object) -> bool:
1003 if isinstance(other, Version):
1004 return self._v == other._v
1005 return NotImplemented
1006
1007 def __ne__(self, other: object) -> bool:
1008 if isinstance(other, Version):
1009 return self._v != other._v
1010 return NotImplemented
1011
1012 def __cmp(self, other: 'Version', comparator: T.Callable[[T.Any, T.Any], bool]) -> bool:
1013 # compare each sequence in order
1014 for ours, theirs in zip(self._v, other._v):
1015 # sort a non-digit sequence before a digit sequence
1016 ours_is_int = isinstance(ours, int)
1017 theirs_is_int = isinstance(theirs, int)
1018 if ours_is_int != theirs_is_int:
1019 return comparator(ours_is_int, theirs_is_int)
1020
1021 if ours != theirs:
1022 return comparator(ours, theirs)
1023
1024 # if equal length, all components have matched, so equal
1025 # otherwise, the version with a suffix remaining is greater
1026 return comparator(len(self._v), len(other._v))
1027
1028
1029 def _version_extract_cmpop(vstr2: str) -> T.Tuple[T.Callable[[T.Any, T.Any], bool], str]:
1030 if vstr2.startswith('>='):
1031 cmpop = operator.ge
1032 vstr2 = vstr2[2:]
1033 elif vstr2.startswith('<='):
1034 cmpop = operator.le
1035 vstr2 = vstr2[2:]
1036 elif vstr2.startswith('!='):
1037 cmpop = operator.ne
1038 vstr2 = vstr2[2:]
1039 elif vstr2.startswith('=='):
1040 cmpop = operator.eq
1041 vstr2 = vstr2[2:]
1042 elif vstr2.startswith('='):
1043 cmpop = operator.eq
1044 vstr2 = vstr2[1:]
1045 elif vstr2.startswith('>'):
1046 cmpop = operator.gt
1047 vstr2 = vstr2[1:]
1048 elif vstr2.startswith('<'):
1049 cmpop = operator.lt
1050 vstr2 = vstr2[1:]
1051 else:
1052 cmpop = operator.eq
1053
1054 return (cmpop, vstr2.strip())
1055
1056
1057 def version_compare(vstr1: str, vstr2: str) -> bool:
1058 (cmpop, vstr2) = _version_extract_cmpop(vstr2)
1059 return cmpop(Version(vstr1), Version(vstr2))
1060
1061
1062 def version_compare_many(vstr1: str, conditions: T.Union[str, T.Iterable[str]]) -> T.Tuple[bool, T.List[str], T.List[str]]:
1063 if isinstance(conditions, str):
1064 conditions = [conditions]
1065 found: T.List[str] = []
1066 not_found: T.List[str] = []
1067 for req in conditions:
1068 if not version_compare(vstr1, req):
1069 not_found.append(req)
1070 else:
1071 found.append(req)
1072 return not not_found, not_found, found
1073
1074
1075 _V = T.TypeVar('_V', bound='Comparable')
1076
1077 @dataclasses.dataclass(order=False)
1078 class Range(T.Generic[_V]):
1079 min: T.Optional[_V] = None
1080 min_eq: bool = False
1081 max: T.Optional[_V] = None
1082 max_eq: bool = False
1083 is_empty: bool = False
1084
1085 def __str__(self) -> str:
1086 if self.is_empty:
1087 return '(empty)'
1088 if self.min is not None and self.max is not None and self.min == self.max:
1089 return f'== {self.min}'
1090 parts = []
1091 if self.min is not None:
1092 parts.append(f'>{"=" if self.min_eq else ""} {self.min}')
1093 if self.max is not None:
1094 parts.append(f'<{"=" if self.max_eq else ""} {self.max}')
1095 return ', '.join(parts) if parts else '(any)'
1096
1097 def __contains__(self, x: _V) -> bool:
1098 if self.is_empty:
1099 return False
1100 if self.min is not None and (x < self.min if self.min_eq else x <= self.min):
1101 return False
1102 if self.max is not None and (x > self.max if self.max_eq else x >= self.max):
1103 return False
1104 return True
1105
1106 def __post_init__(self) -> None:
1107 if self.min is None or self.max is None:
1108 return
1109 self.is_empty = False
1110 if self.min < self.max:
1111 return
1112 if self.min == self.max and self.min_eq and self.max_eq:
1113 return
1114 self.min = None
1115 self.max = None
1116 self.is_empty = True
1117
1118 def _intersect_min(self, v: _V, eq: bool) -> None:
1119 if self.min is None or v > self.min:
1120 self.min, self.min_eq = v, eq
1121 elif v == self.min:
1122 self.min_eq = eq and self.min_eq
1123
1124 def _intersect_max(self, v: _V, eq: bool) -> None:
1125 if self.max is None or v < self.max:
1126 self.max, self.max_eq = v, eq
1127 elif v == self.max:
1128 self.max_eq = eq and self.max_eq
1129
1130 def intersect(self, x: Range[_V]) -> Range[_V]:
1131 if x.is_empty:
1132 return copy.copy(x)
1133 result = copy.copy(self)
1134 if self.is_empty:
1135 return result
1136 if x.min is not None:
1137 result._intersect_min(x.min, x.min_eq)
1138 if x.max is not None:
1139 result._intersect_max(x.max, x.max_eq)
1140 result.__post_init__()
1141 return result
1142
1143 def always(self, inner: Range[_V]) -> T.Optional[bool]:
1144 """Check if inner is always true or always false given self.
1145
1146 Returns True if inner is always satisfied by any value in self,
1147 False if no value in self satisfies inner, None if indeterminate."""
1148 narrowed = self.intersect(inner)
1149 if narrowed.is_empty:
1150 return False
1151 if narrowed == self:
1152 return True
1153 return None
1154
1155
1156 # note that Range is immutable, so no need to have Range() | None
1157 def version_check_to_range(checks: T.List[str], start: Range[Version] = Range()) -> Range[Version]:
1158 for x in checks:
1159 op, v = _version_extract_cmpop(x)
1160 if op is operator.ge:
1161 r = Range(min=Version(v), min_eq=True)
1162 elif op is operator.gt:
1163 r = Range(min=Version(v), min_eq=False)
1164 elif op is operator.le:
1165 r = Range(max=Version(v), max_eq=True)
1166 elif op is operator.lt:
1167 r = Range(max=Version(v), max_eq=False)
1168 elif op is operator.eq:
1169 r = Range(min=Version(v), max=Version(v), min_eq=True, max_eq=True)
1170 elif op is operator.ne:
1171 v_ = Version(v)
1172 # Do the best that we can, remove the extrema
1173 r = Range()
1174 if v_ == start.min:
1175 r = Range(min=v_, min_eq=False)
1176 if v_ == start.max:
1177 r = r.intersect(Range(max=v_, max_eq=False))
1178 start = start.intersect(r)
1179 return start
1180
1181
1182 # determine if the minimum version satisfying the condition |condition| exceeds
1183 # the minimum version for a feature |minimum|
1184 def version_compare_condition_with_min(condition: T.Union[str, Range[Version]], minimum: str) -> bool:
1185 if isinstance(condition, str):
1186 condition = version_check_to_range([condition])
1187
1188 if condition.min is None:
1189 # A < constraint on the project version (max is not None) or a full
1190 # range should always include versions older than minimum, return False.
1191 # is_empty=True instead behaves like an absurdly high min and returns True.
1192 return condition.is_empty
1193 else:
1194 return Version(minimum) <= condition.min
1195
1196 def search_version(text: str) -> str:
1197 # Usually of the type 4.1.4 but compiler output may contain
1198 # stuff like this:
1199 # (Sourcery CodeBench Lite 2014.05-29) 4.8.3 20140320 (prerelease)
1200 # Limiting major version number to two digits seems to work
1201 # thus far. When we get to GCC 100, this will break, but
1202 # if we are still relevant when that happens, it can be
1203 # considered an achievement in itself.
1204 #
1205 # This regex is reaching magic levels. If it ever needs
1206 # to be updated, do not complexify but convert to something
1207 # saner instead.
1208 # We'll demystify it a bit with a verbose definition.
1209 version_regex = re.compile(r"""
1210 (?<! # Zero-width negative lookbehind assertion
1211 (
1212 \d # One digit
1213 | \. # Or one period
1214 ) # One occurrence
1215 )
1216 # Following pattern must not follow a digit or period
1217 (
1218 \d{1,2} # One or two digits
1219 (
1220 \.\d+ # Period and one or more digits
1221 )+ # One or more occurrences
1222 (
1223 -[a-zA-Z0-9]+ # Hyphen and one or more alphanumeric
1224 )? # Zero or one occurrence
1225 ) # One occurrence
1226 """, re.VERBOSE)
1227 match = version_regex.search(text)
1228 if match:
1229 return match.group(0)
1230
1231 # try a simpler regex that has like "blah 2020.01.100 foo" or "blah 2020.01 foo"
1232 version_regex = re.compile(r"(\d{1,4}\.\d{1,4}\.?\d{0,4})")
1233 match = version_regex.search(text)
1234 if match:
1235 return match.group(0)
1236
1237 return 'unknown version'
1238
1239
1240 def default_libdir() -> str:
1241 if is_debianlike():
1242 try:
1243 pc = subprocess.Popen(['dpkg-architecture', '-qDEB_HOST_MULTIARCH'],
1244 stdout=subprocess.PIPE,
1245 stderr=subprocess.DEVNULL)
1246 (stdo, _) = pc.communicate()
1247 if pc.returncode == 0:
1248 archpath = stdo.decode().strip()
1249 return 'lib/' + archpath
1250 except Exception:
1251 pass
1252 if is_freebsd() or is_irix():
1253 return 'lib'
1254 if os.path.isdir('/usr/lib64') and not os.path.islink('/usr/lib64'):
1255 return 'lib64'
1256 return 'lib'
1257
1258
1259 def default_libexecdir() -> str:
1260 if is_haiku():
1261 return 'lib'
1262 # There is no way to auto-detect this, so it must be set at build time
1263 return 'libexec'
1264
1265
1266 def default_prefix() -> str:
1267 if is_windows():
1268 return 'c:/'
1269 if is_haiku():
1270 return '/boot/system/non-packaged'
1271 return '/usr/local'
1272
1273
1274 def default_datadir() -> str:
1275 if is_haiku():
1276 return 'data'
1277 return 'share'
1278
1279
1280 def default_includedir() -> str:
1281 if is_haiku():
1282 return 'develop/headers'
1283 return 'include'
1284
1285
1286 def default_infodir() -> str:
1287 if is_haiku():
1288 return 'documentation/info'
1289 return 'share/info'
1290
1291
1292 def default_localedir() -> str:
1293 if is_haiku():
1294 return 'data/locale'
1295 return 'share/locale'
1296
1297
1298 def default_mandir() -> str:
1299 if is_haiku():
1300 return 'documentation/man'
1301 return 'share/man'
1302
1303
1304 def default_sbindir() -> str:
1305 if is_haiku():
1306 return 'bin'
1307 return 'sbin'
1308
1309
1310 def default_sysconfdir() -> str:
1311 if is_haiku():
1312 return 'settings'
1313 return 'etc'
1314
1315
1316 def determine_worker_count(varnames: T.Optional[T.List[str]] = None) -> int:
1317 num_workers = 0
1318 varnames = varnames or []
1319 # Add MESON_NUM_PROCESSES last, so it will prevail if more than one
1320 # variable is present.
1321 varnames.append('MESON_NUM_PROCESSES')
1322 for varname in varnames:
1323 if varname in os.environ:
1324 try:
1325 num_workers = int(os.environ[varname])
1326 if num_workers < 0:
1327 raise ValueError
1328 except ValueError:
1329 print(f'Invalid value in {varname}, using 1 thread.')
1330 num_workers = 1
1331
1332 if num_workers <= 0:
1333 try:
1334 # Fails in some weird environments such as Debian
1335 # reproducible build.
1336 num_workers = multiprocessing.cpu_count()
1337 except Exception:
1338 num_workers = 1
1339 return num_workers
1340
1341 def is_parent_path(parent: str, trial: str) -> bool:
1342 '''Checks if @trial is a file under the directory @parent. Both @trial and @parent should be
1343 adequately normalized, though empty and '.' segments in @parent and @trial are accepted
1344 and discarded, matching the behavior of os.path.commonpath. Either both or none should
1345 be absolute.'''
1346 assert os.path.isabs(parent) == os.path.isabs(trial)
1347 if is_windows():
1348 parent = parent.replace('\\', '/')
1349 trial = trial.replace('\\', '/')
1350
1351 split_parent = parent.split('/')
1352 split_trial = trial.split('/')
1353
1354 split_parent = [c for c in split_parent if c and c != '.']
1355 split_trial = [c for c in split_trial if c and c != '.']
1356
1357 components = len(split_parent)
1358 return len(split_trial) >= components and split_trial[:components] == split_parent
1359
1360
1361 def has_path_sep(name: str, sep: str = '/\\') -> bool:
1362 'Checks if any of the specified @sep path separators are in @name'
1363 for each in sep:
1364 if each in name:
1365 return True
1366 return False
1367
1368
1369 if is_windows():
1370 # shlex.split is not suitable for splitting command line on Window (https://bugs.python.org/issue1724822);
1371 # shlex.quote is similarly problematic. Below are "proper" implementations of these functions according to
1372 # https://docs.microsoft.com/en-us/cpp/c-language/parsing-c-command-line-arguments and
1373 # https://blogs.msdn.microsoft.com/twistylittlepassagesallalike/2011/04/23/everyone-quotes-command-line-arguments-the-wrong-way/
1374
1375 _whitespace = ' \t\n\r'
1376 _find_unsafe_char = re.compile(fr'[{_whitespace}"]').search
1377
1378 @lru_cache(maxsize=4096)
1379 def quote_arg(arg: str) -> str:
1380 if arg and not _find_unsafe_char(arg):
1381 return arg
1382
1383 result = '"'
1384 num_backslashes = 0
1385 for c in arg:
1386 if c == '\\':
1387 num_backslashes += 1
1388 else:
1389 if c == '"':
1390 # Escape all backslashes and the following double quotation mark
1391 num_backslashes = num_backslashes * 2 + 1
1392
1393 result += num_backslashes * '\\' + c
1394 num_backslashes = 0
1395
1396 # Escape all backslashes, but let the terminating double quotation
1397 # mark we add below be interpreted as a metacharacter
1398 result += (num_backslashes * 2) * '\\' + '"'
1399 return result
1400
1401 def split_args(cmd: str) -> T.List[str]:
1402 result: T.List[str] = []
1403 arg = ''
1404 num_backslashes = 0
1405 num_quotes = 0
1406 in_quotes = False
1407 for c in cmd:
1408 if c == '\\':
1409 num_backslashes += 1
1410 else:
1411 if c == '"' and not num_backslashes % 2:
1412 # unescaped quote, eat it
1413 arg += (num_backslashes // 2) * '\\'
1414 num_quotes += 1
1415 in_quotes = not in_quotes
1416 elif c in _whitespace and not in_quotes:
1417 if arg or num_quotes:
1418 # reached the end of the argument
1419 result.append(arg)
1420 arg = ''
1421 num_quotes = 0
1422 else:
1423 if c == '"':
1424 # escaped quote
1425 num_backslashes = (num_backslashes - 1) // 2
1426
1427 arg += num_backslashes * '\\' + c
1428
1429 num_backslashes = 0
1430
1431 if arg or num_quotes:
1432 result.append(arg)
1433
1434 return result
1435 else:
1436 @lru_cache(maxsize=4096)
1437 def quote_arg(arg: str) -> str:
1438 return shlex.quote(arg)
1439
1440 def split_args(cmd: str) -> T.List[str]:
1441 return shlex.split(cmd)
1442
1443
1444 def join_args(args: T.Iterable[str]) -> str:
1445 return ' '.join([quote_arg(x) for x in args])
1446
1447
1448 def do_replacement(regex: T.Pattern[str], line: str,
1449 variable_format: Literal['meson', 'cmake', 'cmake@'],
1450 confdata: T.Union[T.Dict[str, T.Tuple[str, T.Optional[str]]], 'ConfigurationData']) -> T.Tuple[str, T.Set[str]]:
1451 if variable_format == 'meson':
1452 return do_replacement_meson(regex, line, confdata)
1453 elif variable_format in {'cmake', 'cmake@'}:
1454 return do_replacement_cmake(line, variable_format == 'cmake@', confdata)
1455 else:
1456 raise MesonException('Invalid variable format')
1457
1458 def do_replacement_meson(regex: T.Pattern[str], line: str,
1459 confdata: T.Union[T.Dict[str, T.Tuple[str, T.Optional[str]]], 'ConfigurationData']) -> T.Tuple[str, T.Set[str]]:
1460 missing_variables: T.Set[str] = set()
1461
1462 def variable_replace(match: T.Match[str]) -> str:
1463 # Pairs of escape characters before '@', '\@', '${' or '\${'
1464 if match.group(0).endswith('\\'):
1465 num_escapes = match.end(0) - match.start(0)
1466 return '\\' * (num_escapes // 2)
1467 # \@escaped\@ variables
1468 elif match.groupdict().get('escaped') is not None:
1469 return match.group('escaped')[1:-2]+'@'
1470 else:
1471 # Template variable to be replaced
1472 varname = match.group('variable')
1473 var_str = ''
1474 if varname in confdata:
1475 var, _ = confdata.get(varname)
1476 if isinstance(var, str):
1477 var_str = var
1478 elif isinstance(var, int):
1479 if isinstance(var, bool):
1480 msg = f'Variable substitution with boolean value {varname!r} is deprecated.'
1481 mlog.deprecation(msg)
1482 var_str = str(var)
1483 else:
1484 msg = f'Tried to replace variable {varname!r} value with ' \
1485 f'something other than a string or int: {var!r}'
1486 raise MesonException(msg)
1487 else:
1488 missing_variables.add(varname)
1489 return var_str
1490 return re.sub(regex, variable_replace, line), missing_variables
1491
1492 def do_replacement_cmake(line: str, at_only: bool,
1493 confdata: T.Union[T.Dict[str, T.Tuple[str, T.Optional[str]]], 'ConfigurationData']) -> T.Tuple[str, T.Set[str]]:
1494 missing_variables: T.Set[str] = set()
1495
1496 character_regex = re.compile(r'''
1497 [^a-zA-Z0-9_/.+\-]
1498 ''', re.VERBOSE)
1499
1500 def variable_get(varname: str) -> str:
1501 var_str = ''
1502 if varname in confdata:
1503 var, _ = confdata.get(varname)
1504 if isinstance(var, str):
1505 var_str = var
1506 elif isinstance(var, bool):
1507 var_str = str(int(var))
1508 elif isinstance(var, int):
1509 var_str = str(var)
1510 else:
1511 msg = f'Tried to replace variable {varname!r} value with ' \
1512 f'something other than a string or int: {var!r}'
1513 raise MesonException(msg)
1514 else:
1515 missing_variables.add(varname)
1516 return var_str
1517
1518 def parse_line(line: str) -> str:
1519 index = 0
1520 while len(line) > index:
1521 if line[index] == '@':
1522 next_at = line.find("@", index+1)
1523 if next_at > index+1:
1524 varname = line[index+1:next_at]
1525 match = character_regex.search(varname)
1526
1527 # at substituion doesn't occur if they key isn't valid
1528 # however it also doesn't raise an error
1529 if not match:
1530 value = variable_get(varname)
1531 line = line[:index] + value + line[next_at+1:]
1532
1533 elif not at_only and line[index:index+2] == '${':
1534 bracket_count = 1
1535 end_bracket = index + 2
1536 try:
1537 while bracket_count > 0:
1538 if line[end_bracket:end_bracket+2] == "${":
1539 end_bracket += 2
1540 bracket_count += 1
1541 elif line[end_bracket] == "}":
1542 end_bracket += 1
1543 bracket_count -= 1
1544 elif line[end_bracket] in {"@", "\n"}:
1545 # these aren't valid variable characters
1546 # but they are inconsequential at this point
1547 end_bracket += 1
1548 elif character_regex.search(line[end_bracket]):
1549 invalid_character = line[end_bracket]
1550 variable = line[index+2:end_bracket]
1551 msg = f'Found invalid character {invalid_character!r}' \
1552 f' in variable {variable!r}'
1553 raise MesonException(msg)
1554 else:
1555 end_bracket += 1
1556 except IndexError:
1557 msg = f'Found incomplete variable {line[index:-1]!r}'
1558 raise MesonException(msg)
1559
1560 if bracket_count == 0:
1561 varname = parse_line(line[index+2:end_bracket-1])
1562 match = character_regex.search(varname)
1563 if match:
1564 invalid_character = line[end_bracket-2]
1565 variable = line[index+2:end_bracket-3]
1566 msg = f'Found invalid character {invalid_character!r}' \
1567 f' in variable {variable!r}'
1568 raise MesonException(msg)
1569
1570 value = variable_get(varname)
1571 line = line[:index] + value + line[end_bracket:]
1572
1573 index += 1
1574
1575 return line
1576
1577 return parse_line(line), missing_variables
1578
1579 def do_define_meson(regex: T.Pattern[str], line: str, confdata: 'ConfigurationData',
1580 subproject: T.Optional[SubProject] = None) -> str:
1581
1582 arr = line.split()
1583 if len(arr) != 2:
1584 raise MesonException('#mesondefine does not contain exactly two tokens: %s' % line.strip())
1585
1586 varname = arr[1]
1587 try:
1588 v, _ = confdata.get(varname)
1589 except KeyError:
1590 return '/* #undef %s */\n' % varname
1591
1592 if isinstance(v, str):
1593 result = f'#define {varname} {v}'.strip() + '\n'
1594 result, _ = do_replacement_meson(regex, result, confdata)
1595 return result
1596 elif isinstance(v, bool):
1597 if v:
1598 return '#define %s\n' % varname
1599 else:
1600 return '#undef %s\n' % varname
1601 elif isinstance(v, int):
1602 return '#define %s %d\n' % (varname, v)
1603 else:
1604 raise MesonException('#mesondefine argument "%s" is of unknown type.' % varname)
1605
1606 def do_define_cmake(line: str, confdata: 'ConfigurationData', at_only: bool,
1607 subproject: T.Optional[SubProject] = None) -> str:
1608 cmake_bool_define = 'cmakedefine01' in line
1609
1610 def get_cmake_define(line: str, confdata: 'ConfigurationData') -> str:
1611 arr = line[1:].split()
1612
1613 if cmake_bool_define:
1614 (v, desc) = confdata.get(arr[1])
1615 return str(int(bool(v)))
1616
1617 define_value: T.List[str] = []
1618 for token in arr[2:]:
1619 try:
1620 v, _ = confdata.get(token)
1621 define_value += [str(v)]
1622 except KeyError:
1623 define_value += [token]
1624 return ' '.join(define_value)
1625
1626 arr = line[1:].split()
1627
1628 if len(arr) != 2 and subproject is not None:
1629 from ..interpreterbase.decorators import FeatureNew
1630 FeatureNew.single_use('cmakedefine without exactly two tokens', '0.54.1', subproject)
1631
1632 varname = arr[1]
1633 try:
1634 v, _ = confdata.get(varname)
1635 except KeyError:
1636 if cmake_bool_define:
1637 return '#define %s 0\n' % varname
1638 else:
1639 return '/* #undef %s */\n' % varname
1640
1641 if not cmake_bool_define and not v:
1642 return '/* #undef %s */\n' % varname
1643
1644 result = get_cmake_define(line, confdata)
1645 result = f'#define {varname} {result}'.strip() + '\n'
1646 result, _ = do_replacement_cmake(result, at_only, confdata)
1647 return result
1648
1649 def get_variable_regex(variable_format: Literal['meson', 'cmake', 'cmake@'] = 'meson') -> T.Pattern[str]:
1650 # Only allow (a-z, A-Z, 0-9, _, -) as valid characters for a define
1651 if variable_format == 'meson':
1652 # Also allow escaping pairs of '@' with '\@'
1653 regex = re.compile(r'''
1654 (?:\\\\)+(?=\\?@) # Matches multiple backslashes followed by an @ symbol
1655 | # OR
1656 (?<!\\)@(?P<variable>[-a-zA-Z0-9_]+)@ # Match a variable enclosed in @ symbols and capture the variable name; no matches beginning with '\@'
1657 | # OR
1658 (?P<escaped>\\@[-a-zA-Z0-9_]+\\@) # Match an escaped variable enclosed in @ symbols
1659 ''', re.VERBOSE)
1660 elif variable_format == 'cmake@':
1661 regex = re.compile(r'''
1662 (?<!\\)@(?P<variable>[-a-zA-Z0-9_]+)@ # Match a variable enclosed in @ symbols and capture the variable name; no matches beginning with '\@'
1663 ''', re.VERBOSE)
1664 elif variable_format == "cmake":
1665 regex = re.compile(r'''
1666 \${(?P<variable>[-a-zA-Z0-9_]*)} # Match a variable enclosed in curly braces and capture the variable name
1667 ''', re.VERBOSE)
1668 return regex
1669
1670 def do_conf_str(src: str, data: T.List[str], confdata: 'ConfigurationData',
1671 variable_format: Literal['meson', 'cmake', 'cmake@'],
1672 subproject: T.Optional[SubProject] = None) -> T.Tuple[T.List[str], T.Set[str], bool]:
1673 if variable_format == 'meson':
1674 return do_conf_str_meson(src, data, confdata, subproject)
1675 elif variable_format in {'cmake', 'cmake@'}:
1676 return do_conf_str_cmake(src, data, confdata, variable_format == 'cmake@', subproject)
1677 else:
1678 raise MesonException('Invalid variable format')
1679
1680 def do_conf_str_meson(src: str, data: T.List[str], confdata: 'ConfigurationData',
1681 subproject: T.Optional[SubProject] = None) -> T.Tuple[T.List[str], T.Set[str], bool]:
1682
1683 regex = get_variable_regex('meson')
1684
1685 search_token = '#mesondefine'
1686
1687 result: T.List[str] = []
1688 missing_variables: T.Set[str] = set()
1689 # Detect when the configuration data is empty and no tokens were found
1690 # during substitution so we can warn the user to use the `copy:` kwarg.
1691 confdata_useless = not confdata.keys()
1692 for line in data:
1693 if line.lstrip().startswith(search_token):
1694 confdata_useless = False
1695 line = do_define_meson(regex, line, confdata, subproject)
1696 else:
1697 if re.search(r'#\s*cmakedefine', line):
1698 raise MesonException(f'Format error in {src}: saw "{line.strip()}" when format set to "meson"')
1699 line, missing = do_replacement_meson(regex, line, confdata)
1700 missing_variables.update(missing)
1701 if missing:
1702 confdata_useless = False
1703 result.append(line)
1704
1705 return result, missing_variables, confdata_useless
1706
1707 def do_conf_str_cmake(src: str, data: T.List[str], confdata: 'ConfigurationData', at_only: bool,
1708 subproject: T.Optional[SubProject] = None) -> T.Tuple[T.List[str], T.Set[str], bool]:
1709
1710 variable_format: Literal['cmake', 'cmake@'] = 'cmake'
1711 if at_only:
1712 variable_format = 'cmake@'
1713
1714 search_token = 'cmakedefine'
1715
1716 result: T.List[str] = []
1717 missing_variables: T.Set[str] = set()
1718 # Detect when the configuration data is empty and no tokens were found
1719 # during substitution so we can warn the user to use the `copy:` kwarg.
1720 confdata_useless = not confdata.keys()
1721 for line in data:
1722 stripped_line = line.lstrip()
1723 if len(stripped_line) >= 2 and stripped_line[0] == '#' and stripped_line[1:].lstrip().startswith(search_token):
1724 if not stripped_line[1:].startswith(search_token):
1725 from ..interpreterbase.decorators import FeatureNew
1726 FeatureNew.single_use('whitespace between `#` and `cmakedefine`', '1.9.0', subproject)
1727 confdata_useless = False
1728 line = do_define_cmake(line, confdata, at_only, subproject)
1729 else:
1730 if '#mesondefine' in line:
1731 raise MesonException(f'Format error in {src}: saw "{line.strip()}" when format set to "{variable_format}"')
1732 line, missing = do_replacement_cmake(line, at_only, confdata)
1733 missing_variables.update(missing)
1734 if missing:
1735 confdata_useless = False
1736 result.append(line)
1737
1738 return result, missing_variables, confdata_useless
1739
1740 def do_conf_file(src: str, dst: str, confdata: 'ConfigurationData',
1741 variable_format: Literal['meson', 'cmake', 'cmake@'],
1742 encoding: str = 'utf-8', subproject: T.Optional[SubProject] = None) -> T.Tuple[T.Set[str], bool]:
1743 try:
1744 with open(src, encoding=encoding, newline='') as f:
1745 data = f.readlines()
1746 except Exception as e:
1747 raise MesonException(f'Could not read input file {src}: {e!s}')
1748
1749 (result, missing_variables, confdata_useless) = do_conf_str(src, data, confdata, variable_format, subproject)
1750 dst_tmp = dst + '~'
1751 try:
1752 with open(dst_tmp, 'w', encoding=encoding, newline='') as f:
1753 f.writelines(result)
1754 except Exception as e:
1755 raise MesonException(f'Could not write output file {dst}: {e!s}')
1756 shutil.copymode(src, dst_tmp)
1757 replace_if_different(dst, dst_tmp)
1758 return missing_variables, confdata_useless
1759
1760 CONF_C_PRELUDE = '''/*
1761 * Autogenerated by the Meson build system.
1762 * Do not edit, your changes will be lost.
1763 */
1764
1765 {}
1766
1767 '''
1768
1769 CONF_NASM_PRELUDE = '''; Autogenerated by the Meson build system.
1770 ; Do not edit, your changes will be lost.
1771
1772 '''
1773
1774 def _dump_c_header(ofile: T.TextIO,
1775 cdata: ConfigurationData,
1776 output_format: Literal['c', 'nasm'],
1777 macro_name: T.Optional[str]) -> None:
1778 format_desc: T.Callable[[str], str]
1779 if output_format == 'c':
1780 if macro_name:
1781 prelude = CONF_C_PRELUDE.format('#ifndef {0}\n#define {0}'.format(macro_name))
1782 else:
1783 prelude = CONF_C_PRELUDE.format('#pragma once')
1784 prefix = '#'
1785 format_desc = lambda desc: f'/* {desc} */\n'
1786 else: # nasm
1787 prelude = CONF_NASM_PRELUDE
1788 prefix = '%'
1789 format_desc = lambda desc: '; ' + '\n; '.join(desc.splitlines()) + '\n'
1790
1791 ofile.write(prelude)
1792 for k in sorted(cdata.keys()):
1793 (v, desc) = cdata.get(k)
1794 if desc:
1795 ofile.write(format_desc(desc))
1796 if isinstance(v, bool):
1797 if v:
1798 ofile.write(f'{prefix}define {k}\n\n')
1799 else:
1800 ofile.write(f'{prefix}undef {k}\n\n')
1801 elif isinstance(v, (int, str)):
1802 ofile.write(f'{prefix}define {k} {v}\n\n')
1803 else:
1804 raise MesonException('Unknown data type in configuration file entry: ' + k)
1805 if output_format == 'c' and macro_name:
1806 ofile.write('#endif\n')
1807
1808
1809 def dump_conf_header(ofilename: str, cdata: ConfigurationData,
1810 output_format: Literal['c', 'nasm', 'json'],
1811 macro_name: T.Optional[str]) -> None:
1812 ofilename_tmp = ofilename + '~'
1813 with open(ofilename_tmp, 'w', encoding='utf-8') as ofile:
1814 if output_format == 'json':
1815 data = {k: v[0] for k, v in cdata.values.items()}
1816 json.dump(data, ofile, sort_keys=True)
1817 else: # c, nasm
1818 _dump_c_header(ofile, cdata, output_format, macro_name)
1819
1820 replace_if_different(ofilename, ofilename_tmp)
1821
1822
1823 def replace_if_different(dst: str, dst_tmp: str) -> None:
1824 # If contents are identical, don't touch the file to prevent
1825 # unnecessary rebuilds.
1826 different = True
1827 try:
1828 with open(dst, 'rb') as f1, open(dst_tmp, 'rb') as f2:
1829 if f1.read() == f2.read():
1830 different = False
1831 except FileNotFoundError:
1832 pass
1833 if different:
1834 os.replace(dst_tmp, dst)
1835 else:
1836 os.unlink(dst_tmp)
1837
1838
1839 def listify(item: T.Any, flatten: bool = True) -> T.List[T.Any]:
1840 '''
1841 Returns a list with all args embedded in a list if they are not a list.
1842 This function preserves order.
1843 @flatten: Convert lists of lists to a flat list
1844 '''
1845 if not isinstance(item, list):
1846 return [item]
1847 result: T.List[T.Any] = []
1848 for i in item:
1849 if flatten and isinstance(i, list):
1850 result += listify(i, flatten=True)
1851 else:
1852 result.append(i)
1853 return result
1854
1855 def listify_array_value(value: object, shlex_split_args: bool = False) -> T.List[str]:
1856 if isinstance(value, str):
1857 if value.startswith('['):
1858 try:
1859 newvalue = ast.literal_eval(value)
1860 except ValueError:
1861 raise MesonException(f'malformed value {value}')
1862 elif value == '':
1863 newvalue = []
1864 else:
1865 if shlex_split_args:
1866 newvalue = split_args(value)
1867 else:
1868 newvalue = [v.strip() for v in value.split(',')]
1869 elif isinstance(value, list):
1870 newvalue = value
1871 else:
1872 raise MesonException(f'"{value}" should be a string array, but it is not')
1873 assert isinstance(newvalue, list)
1874 return newvalue
1875
1876 def extract_as_list(dict_object: T.Dict[_T, _U], key: _T, pop: bool = False) -> T.List[_U]:
1877 '''
1878 Extracts all values from given dict_object and listifies them.
1879 '''
1880 fetch: T.Callable[[_T], _U] = dict_object.get
1881 if pop:
1882 fetch = dict_object.pop
1883 # If there's only one key, we don't return a list with one element
1884 return listify(fetch(key) or [], flatten=True)
1885
1886
1887 def typeslistify(item: 'T.Union[_T, T.Sequence[_T]]',
1888 types: 'T.Union[T.Type[_T], T.Tuple[T.Type[_T]]]') -> T.List[_T]:
1889 '''
1890 Ensure that type(@item) is one of @types or a
1891 list of items all of which are of type @types
1892 '''
1893 if isinstance(item, types):
1894 item = T.cast('T.List[_T]', [item])
1895 if not isinstance(item, list):
1896 raise MesonException('Item must be a list or one of {!r}, not {!r}'.format(types, type(item)))
1897 for i in item:
1898 if i is not None and not isinstance(i, types):
1899 raise MesonException('List item must be one of {!r}, not {!r}'.format(types, type(i)))
1900 return item
1901
1902
1903 def stringlistify(item: T.Union[T.Any, T.Sequence[T.Any]]) -> T.List[str]:
1904 return typeslistify(item, str)
1905
1906 def underscorify(item: str) -> str:
1907 return re.sub(r'[^a-zA-Z0-9]', '_', item)
1908
1909 def expand_arguments(args: T.Iterable[str]) -> T.Optional[T.List[str]]:
1910 expended_args: T.List[str] = []
1911 for arg in args:
1912 if not arg.startswith('@'):
1913 expended_args.append(arg)
1914 continue
1915
1916 args_file = arg[1:]
1917 try:
1918 with open(args_file, encoding='utf-8') as f:
1919 extended_args = f.read().split()
1920 expended_args += extended_args
1921 except Exception as e:
1922 mlog.error('Expanding command line arguments:', args_file, 'not found')
1923 mlog.exception(e)
1924 return None
1925 return expended_args
1926
1927
1928 def partition(pred: T.Callable[[_T], object], iterable: T.Iterable[_T]) -> T.Tuple[T.Iterator[_T], T.Iterator[_T]]:
1929 """Use a predicate to partition entries into false entries and true
1930 entries.
1931
1932 >>> x, y = partition(is_odd, range(10))
1933 >>> (list(x), list(y))
1934 ([0, 2, 4, 6, 8], [1, 3, 5, 7, 9])
1935 """
1936 t1, t2 = tee(iterable)
1937 return (t for t in t1 if not pred(t)), (t for t in t2 if pred(t))
1938
1939
1940 def Popen_safe(args: T.List[str], write: T.Optional[str] = None,
1941 stdin: T.Union[None, T.TextIO, T.BinaryIO, int] = subprocess.DEVNULL,
1942 stdout: T.Union[None, T.TextIO, T.BinaryIO, int] = subprocess.PIPE,
1943 stderr: T.Union[None, T.TextIO, T.BinaryIO, int] = subprocess.PIPE,
1944 **kwargs: T.Any) -> T.Tuple['subprocess.Popen[str]', str, str]:
1945 import locale
1946 encoding = locale.getpreferredencoding()
1947 # Stdin defaults to DEVNULL otherwise the command run by us here might mess
1948 # up the console and ANSI colors will stop working on Windows.
1949 # If write is not None, set stdin to PIPE so data can be sent.
1950 if write is not None:
1951 stdin = subprocess.PIPE
1952
1953 try:
1954 if not sys.stdout.encoding or encoding.upper() != 'UTF-8':
1955 p, o, e = Popen_safe_legacy(args, write=write, stdin=stdin, stdout=stdout, stderr=stderr, **kwargs)
1956 else:
1957 p = subprocess.Popen(args, universal_newlines=True, encoding=encoding, close_fds=False,
1958 stdin=stdin, stdout=stdout, stderr=stderr, **kwargs)
1959 o, e = p.communicate(write)
1960 except OSError as oserr:
1961 if oserr.errno == errno.ENOEXEC:
1962 raise MesonException(f'Failed running {args[0]!r}, binary or interpreter not executable.\n'
1963 'Possibly wrong architecture or the executable bit is not set.')
1964 raise
1965 # Sometimes the command that we run will call another command which will be
1966 # without the above stdin workaround, so set the console mode again just in
1967 # case.
1968 mlog.setup_console()
1969 return p, o, e
1970
1971
1972 def Popen_safe_legacy(args: T.List[str], write: T.Optional[str] = None,
1973 stdin: T.Union[None, T.TextIO, T.BinaryIO, int] = subprocess.DEVNULL,
1974 stdout: T.Union[None, T.TextIO, T.BinaryIO, int] = subprocess.PIPE,
1975 stderr: T.Union[None, T.TextIO, T.BinaryIO, int] = subprocess.PIPE,
1976 **kwargs: T.Any) -> T.Tuple['subprocess.Popen[str]', str, str]:
1977 p = subprocess.Popen(args, universal_newlines=False, close_fds=False,
1978 stdin=stdin, stdout=stdout, stderr=stderr, **kwargs)
1979 input_: T.Optional[bytes] = None
1980 if write is not None:
1981 input_ = write.encode('utf-8')
1982 o, e = p.communicate(input_)
1983 if o is not None:
1984 if sys.stdout.encoding is not None:
1985 o = o.decode(encoding=sys.stdout.encoding, errors='replace').replace('\r\n', '\n')
1986 else:
1987 o = o.decode(errors='replace').replace('\r\n', '\n')
1988 if e is not None:
1989 if sys.stderr is not None and sys.stderr.encoding:
1990 e = e.decode(encoding=sys.stderr.encoding, errors='replace').replace('\r\n', '\n')
1991 else:
1992 e = e.decode(errors='replace').replace('\r\n', '\n')
1993 return p, o, e
1994
1995
1996 def Popen_safe_logged(args: T.List[str], msg: str = 'Called', **kwargs: T.Any) -> T.Tuple['subprocess.Popen[str]', str, str]:
1997 '''
1998 Wrapper around Popen_safe that assumes standard piped o/e and logs this to the meson log.
1999 '''
2000 try:
2001 p, o, e = Popen_safe(args, **kwargs)
2002 except Exception as excp:
2003 mlog.debug('-----------')
2004 mlog.debug(f'{msg}: `{join_args(args)}` -> {excp}')
2005 raise
2006
2007 rc, out, err = p.returncode, o.strip() if o else None, e.strip() if e else None
2008 mlog.debug('-----------')
2009 mlog.debug(f'{msg}: `{join_args(args)}` -> {rc}')
2010 if out:
2011 mlog.debug(f'stdout:\n{out}\n-----------')
2012 if err:
2013 mlog.debug(f'stderr:\n{err}\n-----------')
2014 return p, o, e
2015
2016
2017 def iter_regexin_iter(regexiter: T.Iterable[str], initer: T.Iterable[object]) -> T.Optional[str]:
2018 '''
2019 Takes each regular expression in @regexiter and tries to search for it in
2020 every item in @initer. If there is a match, returns that match.
2021 Else returns False.
2022 '''
2023 for regex in regexiter:
2024 for ii in initer:
2025 if not isinstance(ii, str):
2026 continue
2027 match = re.search(regex, ii)
2028 if match:
2029 return match.group()
2030 return None
2031
2032
2033 def _substitute_values_check_errors(command: T.Sequence[object], values: T.Dict[str, T.Union[str, T.List[str]]]) -> None:
2034 # Error checking
2035 inregex: T.List[str] = ['@INPUT([0-9]+)?@', '@PLAINNAME@', '@BASENAME@']
2036 outregex: T.List[str] = ['@OUTPUT([0-9]+)?@', '@OUTDIR@']
2037 if '@INPUT@' not in values:
2038 # Error out if any input-derived templates are present in the command
2039 match = iter_regexin_iter(inregex, command)
2040 if match:
2041 raise MesonException(f'Command cannot have {match!r}, since no input files were specified')
2042 else:
2043 if len(values['@INPUT@']) > 1:
2044 # Error out if @PLAINNAME@ or @BASENAME@ is present in the command
2045 match = iter_regexin_iter(inregex[1:], command)
2046 if match:
2047 raise MesonException(f'Command cannot have {match!r} when there is '
2048 'more than one input file')
2049 # Error out if an invalid @INPUTnn@ template was specified
2050 for each in command:
2051 if not isinstance(each, str):
2052 continue
2053 match2 = re.search(inregex[0], each)
2054 if match2 and match2.group() not in values:
2055 m = 'Command cannot have {!r} since there are only {!r} inputs'
2056 raise MesonException(m.format(match2.group(), len(values['@INPUT@'])))
2057 if '@OUTPUT@' not in values:
2058 # Error out if any output-derived templates are present in the command
2059 match = iter_regexin_iter(outregex, command)
2060 if match:
2061 raise MesonException(f'Command cannot have {match!r} since there are no outputs')
2062 else:
2063 # Error out if an invalid @OUTPUTnn@ template was specified
2064 for each in command:
2065 if not isinstance(each, str):
2066 continue
2067 match2 = re.search(outregex[0], each)
2068 if match2 and match2.group() not in values:
2069 m = 'Command cannot have {!r} since there are only {!r} outputs'
2070 raise MesonException(m.format(match2.group(), len(values['@OUTPUT@'])))
2071
2072
2073 def substitute_values(command: T.List[_T],
2074 values: T.Dict[str, T.Union[str, T.List[str]]]
2075 ) -> T.List[_T]:
2076 '''
2077 Substitute the template strings in the @values dict into the list of
2078 strings @command and return a new list. For a full list of the templates,
2079 see get_filenames_templates_dict()
2080
2081 If multiple inputs/outputs are given in the @values dictionary, we
2082 substitute @INPUT@ and @OUTPUT@ only if they are the entire string, not
2083 just a part of it, and in that case we substitute *all* of them.
2084
2085 The typing of this function is difficult, as only @OUTPUT@ and @INPUT@ can
2086 be lists, everything else is a string. However, TypeDict cannot represent
2087 this, as you can have optional keys, but not extra keys. We end up just
2088 having to use asserts to convince type checkers that this is okay.
2089
2090 https://github.com/python/mypy/issues/4617
2091 '''
2092
2093 # Error checking and quick exit
2094 _substitute_values_check_errors(command, values)
2095 if not values:
2096 return list(command)
2097
2098 # Substitution
2099 rx_keys = [re.escape(key) for key in values]
2100 value_rx = re.compile('|'.join(rx_keys))
2101
2102 def replace(m: T.Match[str]) -> str:
2103 v = values[m.group(0)]
2104 if isinstance(v, list):
2105 if len(v) > 1 and m.group(0) == '@INPUT@':
2106 raise MesonException("Command has '@INPUT@' as part of a "
2107 "string and more than one input file")
2108 if len(v) > 1 and m.group(0) == '@OUTPUT@':
2109 raise MesonException("Command has '@OUTPUT@' as part of a "
2110 "string and more than one output file")
2111 return v[0]
2112 return v
2113
2114 outcmd: T.List[_T] = []
2115 for vv in command:
2116 if not isinstance(vv, str):
2117 outcmd.append(vv)
2118 elif vv in values:
2119 # Append values that are exactly a template string.
2120 # This is faster than a string replace, and makes it
2121 # possible to special case @INPUT@ and @OUTPUT@ too
2122
2123 # We have to do a bunch of casting here because mypy doesn't realize
2124 # that if we're adding str to this list then we got string inputs,
2125 # and attempting to set the return type to `_T | str` causes
2126 # problems elswhere, so let's contain the pain here.
2127 if vv == '@INPUT@':
2128 inputs = values['@INPUT@']
2129 assert isinstance(inputs, list)
2130 outcmd += T.cast('list[_T]', inputs)
2131 elif vv == '@OUTPUT@':
2132 outputs = values['@OUTPUT@']
2133 assert isinstance(outputs, list)
2134 outcmd += T.cast('list[_T]', outputs)
2135 else:
2136 o = values[vv]
2137 assert isinstance(o, str), 'for mypy'
2138 outcmd.append(T.cast('_T', o))
2139 else:
2140 # Substitute everything else with replacement
2141 assert values
2142 outcmd.append(T.cast('_T', value_rx.sub(replace, vv)))
2143
2144 return outcmd
2145
2146
2147 def get_filenames_templates_dict(inputs: T.List[str], outputs: T.List[str]) -> T.Dict[str, T.Union[str, T.List[str]]]:
2148 '''
2149 Create a dictionary with template strings as keys and values as values for
2150 the following templates:
2151
2152 @INPUT@ - the full path to one or more input files, from @inputs
2153 @OUTPUT@ - the full path to one or more output files, from @outputs
2154 @OUTDIR@ - the full path to the directory containing the output files
2155
2156 If there is only one input file, the following keys are also created:
2157
2158 @PLAINNAME@ - the filename of the input file
2159 @BASENAME@ - the filename of the input file with the extension removed
2160
2161 If there is more than one input file, the following keys are also created:
2162
2163 @INPUT0@, @INPUT1@, ... one for each input file
2164 @PLAINNAME0@, @PLAINNAME1@, ... one for each input file
2165 @BASENAME0@, @BASENAME1@, ... one for each input file
2166
2167 If there is more than one output file, the following keys are also created:
2168
2169 @OUTPUT0@, @OUTPUT1@, ... one for each output file
2170 '''
2171 values: T.Dict[str, T.Union[str, T.List[str]]] = {}
2172 # Gather values derived from the input
2173 if inputs:
2174 # We want to substitute all the inputs.
2175 values['@INPUT@'] = inputs
2176 for (ii, vv) in enumerate(inputs):
2177 # Write out @INPUT0@, @INPUT1@, ...
2178 values[f'@INPUT{ii}@'] = vv
2179 plain = os.path.basename(vv)
2180 values[f'@PLAINNAME{ii}@'] = plain
2181 values[f'@BASENAME{ii}@'] = os.path.splitext(plain)[0]
2182 if len(inputs) == 1:
2183 # Just one value, substitute @PLAINNAME@ and @BASENAME@
2184 values['@PLAINNAME@'] = plain = os.path.basename(inputs[0])
2185 values['@BASENAME@'] = os.path.splitext(plain)[0]
2186 if outputs:
2187 # Gather values derived from the outputs, similar to above.
2188 values['@OUTPUT@'] = outputs
2189 for (ii, vv) in enumerate(outputs):
2190 values[f'@OUTPUT{ii}@'] = vv
2191 # Outdir should be the same for all outputs
2192 values['@OUTDIR@'] = os.path.dirname(outputs[0])
2193 # Many external programs fail on empty arguments.
2194 if values['@OUTDIR@'] == '':
2195 values['@OUTDIR@'] = '.'
2196 return values
2197
2198
2199 def _make_tree_writable(topdir: T.Union[str, Path]) -> None:
2200 # Ensure all files and directories under topdir are writable
2201 # (and readable) by owner.
2202 for d, _, files in os.walk(topdir):
2203 os.chmod(d, os.stat(d).st_mode | stat.S_IWRITE | stat.S_IREAD)
2204 for fname in files:
2205 fpath = os.path.join(d, fname)
2206 if not os.path.islink(fpath) and os.path.isfile(fpath):
2207 os.chmod(fpath, os.stat(fpath).st_mode | stat.S_IWRITE | stat.S_IREAD)
2208
2209
2210 def windows_proof_rmtree(f: T.Union[str, Path]) -> None:
2211 # On Windows if anyone is holding a file open you can't
2212 # delete it. As an example an anti virus scanner might
2213 # be scanning files you are trying to delete. The only
2214 # way to fix this is to try again and again.
2215 delays = [0.1, 0.1, 0.2, 0.2, 0.2, 0.5, 0.5, 1, 1, 1, 1, 2]
2216 writable = False
2217 for d in delays:
2218 try:
2219 # Start by making the tree writable.
2220 if not writable:
2221 _make_tree_writable(f)
2222 writable = True
2223 except PermissionError:
2224 time.sleep(d)
2225 continue
2226 try:
2227 shutil.rmtree(f)
2228 return
2229 except FileNotFoundError:
2230 return
2231 except OSError:
2232 time.sleep(d)
2233 # Try one last time and throw if it fails.
2234 shutil.rmtree(f)
2235
2236
2237 def windows_proof_rm(fpath: T.Union[str, Path]) -> None:
2238 """Like windows_proof_rmtree, but for a single file."""
2239 if os.path.isfile(fpath):
2240 os.chmod(fpath, os.stat(fpath).st_mode | stat.S_IWRITE | stat.S_IREAD)
2241 delays = [0.1, 0.1, 0.2, 0.2, 0.2, 0.5, 0.5, 1, 1, 1, 1, 2]
2242 for d in delays:
2243 try:
2244 os.unlink(fpath)
2245 return
2246 except FileNotFoundError:
2247 return
2248 except OSError:
2249 time.sleep(d)
2250 os.unlink(fpath)
2251
2252
2253 class TemporaryDirectoryWinProof(TemporaryDirectory):
2254 """
2255 Like TemporaryDirectory, but cleans things up using
2256 windows_proof_rmtree()
2257 """
2258
2259 def __exit__(self, exc: T.Any, value: T.Any, tb: T.Any) -> None:
2260 try:
2261 super().__exit__(exc, value, tb)
2262 except OSError:
2263 windows_proof_rmtree(self.name)
2264
2265 def cleanup(self) -> None:
2266 try:
2267 super().cleanup()
2268 except OSError:
2269 windows_proof_rmtree(self.name)
2270
2271
2272 def detect_subprojects(spdir_name: str, current_dir: str = '',
2273 result: T.Optional[T.Dict[str, T.List[str]]] = None) -> T.Dict[str, T.List[str]]:
2274 if result is None:
2275 result = {}
2276 spdir = os.path.join(current_dir, spdir_name)
2277 if not os.path.exists(spdir):
2278 return result
2279 for trial in glob(os.path.join(spdir, '*')):
2280 basename = os.path.basename(trial)
2281 if trial == 'packagecache':
2282 continue
2283 append_this = True
2284 if os.path.isdir(trial):
2285 spdir_name = get_subproject_dir(trial) or 'subprojects'
2286
2287 detect_subprojects(spdir_name, trial, result)
2288 elif trial.endswith('.wrap') and os.path.isfile(trial):
2289 basename = os.path.splitext(basename)[0]
2290 else:
2291 append_this = False
2292 if append_this:
2293 if basename in result:
2294 result[basename].append(trial)
2295 else:
2296 result[basename] = [trial]
2297 return result
2298
2299
2300 def substring_is_in_list(substr: str, strlist: T.List[str]) -> bool:
2301 for s in strlist:
2302 if substr in s:
2303 return True
2304 return False
2305
2306
2307 def unique_list(x: T.Iterable[_T]) -> T.List[_T]:
2308 return list(dict.fromkeys(x))
2309
2310
2311 class OrderedSet(T.MutableSet[_T]):
2312 """A set that preserves the order in which items are added, by first
2313 insertion.
2314 """
2315 def __init__(self, iterable: T.Optional[T.Iterable[_T]] = None):
2316 self.__container: T.OrderedDict[_T, None] = collections.OrderedDict()
2317 if iterable:
2318 self.update(iterable)
2319
2320 def __contains__(self, value: object) -> bool:
2321 return value in self.__container
2322
2323 def __iter__(self) -> T.Iterator[_T]:
2324 return iter(self.__container.keys())
2325
2326 def __len__(self) -> int:
2327 return len(self.__container)
2328
2329 def __repr__(self) -> str:
2330 # Don't print 'OrderedSet("")' for an empty set.
2331 if self.__container:
2332 return 'OrderedSet([{}])'.format(
2333 ', '.join(repr(e) for e in self.__container.keys()))
2334 return 'OrderedSet()'
2335
2336 def __reversed__(self) -> T.Iterator[_T]:
2337 return reversed(self.__container.keys())
2338
2339 def add(self, value: _T) -> None:
2340 self.__container[value] = None
2341
2342 def discard(self, value: _T) -> None:
2343 if value in self.__container:
2344 del self.__container[value]
2345
2346 def move_to_end(self, value: _T, last: bool = True) -> None:
2347 self.__container.move_to_end(value, last)
2348
2349 def pop(self, last: bool = True) -> _T:
2350 item, _ = self.__container.popitem(last)
2351 return item
2352
2353 def update(self, iterable: T.Iterable[_T]) -> None:
2354 for item in iterable:
2355 self.__container[item] = None
2356
2357 def difference(self, set_: T.Iterable[_T]) -> 'OrderedSet[_T]':
2358 return type(self)(e for e in self if e not in set_)
2359
2360 def difference_update(self, iterable: T.Iterable[_T]) -> None:
2361 for item in iterable:
2362 self.discard(item)
2363
2364 def relpath(path: T.Union[str, Path], start: T.Union[str, Path]) -> str:
2365 # On Windows a relative path can't be evaluated for paths on two different
2366 # drives (i.e. c:\foo and f:\bar). The only thing left to do is to use the
2367 # original absolute path.
2368 try:
2369 return os.path.relpath(path, start)
2370 except (TypeError, ValueError):
2371 return str(path)
2372
2373 def path_is_in_root(path: Path, root: Path, resolve: bool = False) -> bool:
2374 # Check whether a path is within the root directory root
2375 try:
2376 if resolve:
2377 path.resolve().relative_to(root.resolve())
2378 else:
2379 path.relative_to(root)
2380 except ValueError:
2381 return False
2382 return True
2383
2384 def relative_to_if_possible(path: Path, root: Path, resolve: bool = False) -> Path:
2385 try:
2386 if resolve:
2387 return path.resolve().relative_to(root.resolve())
2388 else:
2389 return path.relative_to(root)
2390 except ValueError:
2391 return path
2392
2393 class LibType(enum.IntEnum):
2394
2395 """Enumeration for library types."""
2396
2397 SHARED = 0
2398 STATIC = 1
2399 PREFER_SHARED = 2
2400 PREFER_STATIC = 3
2401
2402
2403 class ProgressBarFallback(T.Generic[_T]):
2404 '''
2405 Fallback progress bar implementation when tqdm is not foundclass OptionType(enum.IntEnum):
2406
2407 """Enum used to specify what kind of argument a thing is."""
2408
2409 BUILTIN = 0
2410 BACKEND = 1
2411 BASE = 2
2412 COMPILER = 3
2413 PROJECT = 4
2414
2415 # This is copied from coredata. There is no way to share this, because this
2416 # is used in the OptionKey constructor, and the coredata lists are
2417 # OptionKeys...
2418 _BUILTIN_NAMES = {
2419 'prefix',
2420 'bindir',
2421 'datadir',
2422 'includedir',
2423 'infodir',
2424 'libdir',
2425 'licensedir',
2426 'libexecdir',
2427 'localedir',
2428 'localstatedir',
2429 'mandir',
2430 'sbindir',
2431 'sharedstatedir',
2432 'sysconfdir',
2433 'auto_features',
2434 'backend',
2435 'buildtype',
2436 'debug',
2437 'default_library',
2438 'errorlogs',
2439 'genvslite',
2440 'install_umask',
2441 'layout',
2442 'optimization',
2443 'prefer_static',
2444 'stdsplit',
2445 'strip',
2446 'unity',
2447 'unity_size',
2448 'warning_level',
2449 'werror',
2450 'wrap_mode',
2451 'force_fallback_for',
2452 'pkg_config_path',
2453 'cmake_prefix_path',
2454 'vsenv',
2455 'os2_emxomf',
2456 }
2457
2458
2459 Since this class is not an actual iterator, but only provides a minimal
2460 fallback, it is safe to ignore the 'Iterator does not return self from
2461 __iter__ method' warning.
2462 '''
2463 def __init__(self, iterable: T.Optional[T.Iterable[_T]] = None, total: T.Optional[int] = None,
2464 bar_type: T.Optional[str] = None, desc: T.Optional[str] = None,
2465 disable: T.Optional[bool] = None):
2466 if iterable is not None:
2467 self.iterable = iter(iterable)
2468 return
2469 self.total = total
2470 self.done = 0
2471 self.printed_dots = 0
2472 self.disable = not mlog.colorize_console() if disable is None else disable
2473 if not self.disable:
2474 if self.total and bar_type == 'download':
2475 print('Download size:', self.total)
2476 if desc:
2477 print(f'{desc}: ', end='')
2478
2479 # Pretend to be an iterator when called as one and don't print any
2480 # progress
2481 def __iter__(self) -> T.Iterator[_T]:
2482 return self.iterable
2483
2484 def __next__(self) -> _T:
2485 return next(self.iterable)
2486
2487 def print_dot(self) -> None:
2488 if not self.disable:
2489 print('.', end='')
2490 sys.stdout.flush()
2491 self.printed_dots += 1
2492
2493 def update(self, progress: int) -> None:
2494 self.done += progress
2495 if not self.total:
2496 # Just print one dot per call if we don't have a total length
2497 self.print_dot()
2498 return
2499 ratio = int(self.done / self.total * 10)
2500 while self.printed_dots < ratio:
2501 self.print_dot()
2502
2503 def close(self) -> None:
2504 if not self.disable:
2505 print()
2506
2507 try:
2508 from tqdm import tqdm
2509 except ImportError:
2510 # ideally we would use a typing.Protocol here, but it's part of typing_extensions until 3.8
2511 ProgressBar: T.Union[T.Type[ProgressBarFallback], T.Type[ProgressBarTqdm]] = ProgressBarFallback
2512 else:
2513 class ProgressBarTqdm(tqdm):
2514 def __init__(self, *args: T.Any, bar_type: T.Optional[str] = None, **kwargs: T.Any) -> None:
2515 if bar_type == 'download':
2516 kwargs.update({'unit': 'B',
2517 'unit_scale': True,
2518 'unit_divisor': 1024,
2519 'leave': True,
2520 'bar_format': '{l_bar}{bar}| {n_fmt}/{total_fmt} {rate_fmt} eta {remaining}',
2521 })
2522
2523 else:
2524 kwargs.update({'leave': False,
2525 'bar_format': '{l_bar}{bar}| {n_fmt}/{total_fmt} eta {remaining}',
2526 })
2527 super().__init__(*args, **kwargs)
2528
2529 ProgressBar = ProgressBarTqdm
2530
2531
2532 class RealPathAction(argparse.Action):
2533 def __init__(self, option_strings: T.List[str], dest: str, default: str = '.', **kwargs: T.Any):
2534 default = os.path.abspath(os.path.realpath(default))
2535 super().__init__(option_strings, dest, nargs=None, default=default, **kwargs)
2536
2537 def __call__(self, parser: argparse.ArgumentParser, namespace: argparse.Namespace,
2538 values: T.Union[str, T.Sequence[T.Any], None], option_string: T.Optional[str] = None) -> None:
2539 assert isinstance(values, str)
2540 setattr(namespace, self.dest, os.path.abspath(os.path.realpath(values)))
2541
2542
2543 def get_wine_shortpath(winecmd: T.List[str], wine_paths: T.List[str],
2544 workdir: T.Optional[str] = None) -> str:
2545 '''
2546 WINEPATH size is limited to 1024 bytes which can easily be exceeded when
2547 adding the path to every dll inside build directory. See
2548 https://bugs.winehq.org/show_bug.cgi?id=45810.
2549
2550 To shorten it as much as possible we use path relative to `workdir`
2551 where possible and convert absolute paths to Windows shortpath (e.g.
2552 "/usr/x86_64-w64-mingw32/lib" to "Z:\\usr\\X86_~FWL\\lib").
2553
2554 This limitation reportedly has been fixed with wine >= 6.4
2555 '''
2556
2557 # Remove duplicates
2558 wine_paths = list(OrderedSet(wine_paths))
2559
2560 # Check if it's already short enough
2561 wine_path = ';'.join(wine_paths)
2562 if len(wine_path) <= 1024:
2563 return wine_path
2564
2565 # Check if we have wine >= 6.4
2566 from ..programs import ExternalProgram
2567 wine = ExternalProgram('wine', winecmd, silent=True)
2568 if version_compare(wine.get_version(), '>=6.4'):
2569 return wine_path
2570
2571 # Check paths that can be reduced by making them relative to workdir.
2572 rel_paths: T.List[str] = []
2573 if workdir:
2574 abs_paths: T.List[str] = []
2575 for p in wine_paths:
2576 try:
2577 rel = Path(p).relative_to(workdir)
2578 rel_paths.append(str(rel))
2579 except ValueError:
2580 abs_paths.append(p)
2581 wine_paths = abs_paths
2582
2583 if wine_paths:
2584 # BAT script that takes a list of paths in argv and prints semi-colon separated shortpaths
2585 with NamedTemporaryFile('w', suffix='.bat', encoding='utf-8', delete=False) as bat_file:
2586 bat_file.write('''
2587 @ECHO OFF
2588 for %%x in (%*) do (
2589 echo|set /p=;%~sx
2590 )
2591 ''')
2592 try:
2593 stdout = subprocess.check_output(winecmd + ['cmd', '/C', bat_file.name] + wine_paths,
2594 encoding='utf-8', stderr=subprocess.DEVNULL)
2595 stdout = stdout.strip(';')
2596 if stdout:
2597 wine_paths = stdout.split(';')
2598 else:
2599 mlog.warning('Could not shorten WINEPATH: empty stdout')
2600 except subprocess.CalledProcessError as e:
2601 mlog.warning(f'Could not shorten WINEPATH: {str(e)}')
2602 finally:
2603 os.unlink(bat_file.name)
2604 wine_path = ';'.join(rel_paths + wine_paths)
2605 if len(wine_path) > 1024:
2606 mlog.warning('WINEPATH exceeds 1024 characters which could cause issues')
2607 return wine_path
2608
2609
2610 def run_once(func: T.Callable[_P, _T]) -> T.Callable[_P, _T]:
2611 ret: T.List[_T] = []
2612
2613 @wraps(func)
2614 def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> _T:
2615 if ret:
2616 return ret[0]
2617
2618 val = func(*args, **kwargs)
2619 ret.append(val)
2620 return val
2621
2622 return wrapper
2623
2624
2625 def generate_list(func: T.Callable[_P, T.Generator[_T, None, None]]) -> T.Callable[_P, T.List[_T]]:
2626 @wraps(func)
2627 def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> T.List[_T]:
2628 return list(func(*args, **kwargs))
2629
2630 return wrapper
2631
2632
2633 def pickle_load(filename: str, object_name: str, object_type: T.Type[_PL], suggest_reconfigure: bool = True) -> _PL:
2634 load_fail_msg = f'{object_name} file {filename!r} is corrupted.'
2635 extra_msg = ' Consider reconfiguring the directory with "meson setup --reconfigure".' if suggest_reconfigure else ''
2636 try:
2637 with open(filename, 'rb') as f:
2638 obj = pickle.load(f)
2639 except (pickle.UnpicklingError, EOFError):
2640 raise MesonException(load_fail_msg + extra_msg)
2641 except (TypeError, ModuleNotFoundError, AttributeError):
2642 raise MesonException(
2643 f"{object_name} file {filename!r} references functions or classes that don't "
2644 "exist. This probably means that it was generated with an old "
2645 "version of meson." + extra_msg)
2646
2647 if not isinstance(obj, object_type):
2648 raise MesonException(load_fail_msg + extra_msg)
2649
2650 # Because these Protocols are not available at runtime (and cannot be made
2651 # available at runtime until we drop support for Python < 3.8), we have to
2652 # do a bit of hackery so that mypy understands what's going on here
2653 version: str
2654 if hasattr(obj, 'version'):
2655 version = T.cast('_VerPickleLoadable', obj).version
2656 else:
2657 version = T.cast('_EnvPickleLoadable', obj).environment.coredata.version
2658
2659 from ..coredata import version as coredata_version
2660 from ..coredata import major_versions_differ, MesonVersionMismatchException
2661 if major_versions_differ(version, coredata_version):
2662 raise MesonVersionMismatchException(version, coredata_version, extra_msg)
2663 return obj
2664
2665
2666 def first(iter: T.Iterable[_T], predicate: T.Callable[[_T], bool]) -> T.Optional[_T]:
2667 """Find the first entry in an iterable where the given predicate is true
2668
2669 :param iter: The iterable to search
2670 :param predicate: A finding function that takes an element from the iterable
2671 and returns True if found, otherwise False
2672 :return: The first found element, or None if it is not found
2673 """
2674 for i in iter:
2675 if predicate(i):
2676 return i
2677 return None
2678
2679
2680 def get_rsp_threshold() -> int:
2681 '''Return a conservative estimate of the commandline size in bytes
2682 above which a response file should be used. May be overridden for
2683 debugging by setting environment variable MESON_RSP_THRESHOLD.'''
2684
2685 if is_windows():
2686 # Usually 32k, but some projects might use cmd.exe,
2687 # and that has a limit of 8k.
2688 limit = 8192
2689 else:
2690 # Unix-like OSes usually have very large command line limits, (On Linux,
2691 # for example, this is limited by the kernel's MAX_ARG_STRLEN). However,
2692 # some programs place much lower limits, notably Wine which enforces a
2693 # 32k limit like Windows. Therefore, we limit the command line to 32k.
2694 limit = 32768
2695
2696 # Be conservative
2697 limit = limit // 2
2698 return int(os.environ.get('MESON_RSP_THRESHOLD', limit))
2699
2700
2701 class lazy_property(T.Generic[_T]):
2702 """Descriptor that replaces the function it wraps with the value generated.
2703
2704 This property will only be calculated the first time it's queried, and will
2705 be cached and the cached value used for subsequent calls.
2706
2707 This works by shadowing itself with the calculated value, in the instance.
2708 Due to Python's MRO that means that the calculated value will be found
2709 before this property, speeding up subsequent lookups.
2710 """
2711 def __init__(self, func: T.Callable[[T.Any], _T]) -> None:
2712 self.__name: T.Optional[str] = None
2713 self.__func = func
2714
2715 def __set_name__(self, owner: T.Any, name: str) -> None:
2716 if self.__name is None:
2717 self.__name = name
2718 else:
2719 assert name == self.__name
2720
2721 def __get__(self, instance: object, cls: T.Type) -> _T:
2722 value = self.__func(instance)
2723 setattr(instance, self.__name, value)
2724 return value
2725
2726
2727 class late_property(T.Generic[_T]):
2728 """Descriptor that allows setting a property late and erroring if it's
2729 accessed early.
2730
2731 This property allows a more ergonomically typed equivalent of
2732 self.value: T | None = None, since you then don't need to worry about
2733 whether self.value is None.
2734 """
2735
2736 def __init__(self) -> None:
2737 self.__name: str | None = None
2738
2739 def __set_name__(self, owner: object, name: str) -> None:
2740 if self.__name is None:
2741 self.__name = name
2742 else:
2743 assert self.__name == name
2744
2745 def __get__(self, instance: T.Any, cls: type) -> _T:
2746 raise MesonBugException(f'Attempted to access attribute {self.__name} before it is set')
2747
2748
2749 def get_subproject_dir(directory: str = '.') -> T.Optional[str]:
2750 """Get the name of the subproject directory for a specific project.
2751
2752 If the subproject does not have a meson.build file, it is called in an
2753 invalid directory, it returns None
2754
2755 :param directory: Where to search, defaults to current working directory
2756 :return: the name of the subproject directory or None.
2757 """
2758 from ..ast import IntrospectionInterpreter
2759 from ..interpreterbase.exceptions import InvalidArguments
2760 intr = IntrospectionInterpreter(directory, '', 'none')
2761 try:
2762 intr.load_root_meson_file()
2763 except InvalidArguments: # Root meson file cannot be found
2764 return None
2765
2766 return intr.extract_subproject_dir() or 'subprojects'
2767
2768
2769 def lookbehind(it_: T.Iterable[_T]) -> T.Iterator[T.Tuple[T.Optional[_T], _T]]:
2770 """Get the current value of the iterable, and the previous if possible.
2771
2772 :param iter: The iterable to look into
2773 :yield: A tuple of the previous value if possible, and the current one
2774 :return: nothing
2775 """
2776 prev: T.Optional[_T] = None
2777 it: T.Iterator[_T] = iter(it_)
2778 while True:
2779 try:
2780 current = next(it)
2781 yield prev, current
2782 prev = current
2783 except StopIteration:
2784 break
2785
2786
2787 def lookahead(it_: T.Iterable[_T]) -> T.Iterator[T.Tuple[_T, T.Optional[_T]]]:
2788 """Get the current value of the iterable, and the next if possible.
2789
2790 :param iter: The iterable to look into
2791 :yield: A tuple of the current value, and, if possible, the next
2792 :return: nothing
2793 """
2794 current: _T
2795 next_: T.Optional[_T]
2796 it: T.Iterator[_T] = iter(it_)
2797 try:
2798 next_ = next(it)
2799 except StopIteration:
2800 # This is an empty iterator, there's nothing to look ahead to
2801 return
2802
2803 while True:
2804 current = next_
2805 try:
2806 next_ = next(it)
2807 except StopIteration:
2808 next_ = None
2809
2810 yield current, next_
2811
2812 if next_ is None:
2813 break
2814
2815
2816 def pathname_sort_key(key: str) -> tuple[tuple[bool, tuple[int | str, ...]], ...]:
2817 '''Sort key for natural pathname sort, as defined in the Meson style guide.
2818 Use as the key= argument to sort() or sorted().'''
2819
2820 def convert(text: str) -> int | str:
2821 return int(text) if text.isdigit() else text.lower()
2822
2823 def alphanum_key(key: str) -> tuple[int | str, ...]:
2824 return tuple(convert(c) for c in re.split('([0-9]+)', key))
2825
2826 return tuple((key.count('/') <= idx, alphanum_key(x))
2827 for idx, x in enumerate(key.split('/')))
2828
2829
2830 def unwrap(value: _T | None, msg: str | None = None) -> _T:
2831 """Remove None from a union type when it is a Meson bug.
2832
2833 This is used for cases where None being in the Union is a bug in Meson
2834 itself.
2835
2836 :param value: The Union
2837 :param msg: A message to print when a buggy value occurs, defaults to None
2838 :raises MesonBugException: When None is in value
2839 :return: The value union with None removed
2840 """
2841 if value is not None:
2842 return value
2843 raise MesonBugException(msg or 'Unexpected None value')
2844
2845
2846 def unwrap_err(value: _T | None, msg: str) -> _T:
2847 """Remove None from a union type when it is not a Meson bug.
2848
2849 This is for cases where None is possible, but it represents a problem
2850 outside of Meson itself.
2851
2852 For example, a missing external program, or a read only file system, or a
2853 missing file
2854
2855 :param value: The Union to remove None from
2856 :param msg: The message to print when None is found
2857 :raises MesonException: When None is found in the union
2858 :return: The Union with None removed
2859 """
2860 if value is not None:
2861 return value
2862 raise MesonException(msg)