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 )
1226 (?!\S) # Must not be followed by non-space char
1227 """, re.VERBOSE)
1228 match = version_regex.search(text)
1229 if match:
1230 return match.group(0)
1231
1232 # try a simpler regex that has like "blah 2020.01.100 foo" or "blah 2020.01 foo"
1233 version_regex = re.compile(r"(\d{1,4}\.\d{1,4}\.?\d{0,4})")
1234 match = version_regex.search(text)
1235 if match:
1236 return match.group(0)
1237
1238 return 'unknown version'
1239
1240
1241 def default_libdir() -> str:
1242 if is_debianlike():
1243 try:
1244 pc = subprocess.Popen(['dpkg-architecture', '-qDEB_HOST_MULTIARCH'],
1245 stdout=subprocess.PIPE,
1246 stderr=subprocess.DEVNULL)
1247 (stdo, _) = pc.communicate()
1248 if pc.returncode == 0:
1249 archpath = stdo.decode().strip()
1250 return 'lib/' + archpath
1251 except Exception:
1252 pass
1253 if is_freebsd() or is_irix():
1254 return 'lib'
1255 if os.path.isdir('/usr/lib64') and not os.path.islink('/usr/lib64'):
1256 return 'lib64'
1257 return 'lib'
1258
1259
1260 def default_libexecdir() -> str:
1261 if is_haiku():
1262 return 'lib'
1263 # There is no way to auto-detect this, so it must be set at build time
1264 return 'libexec'
1265
1266
1267 def default_prefix() -> str:
1268 if is_windows():
1269 return 'c:/'
1270 if is_haiku():
1271 return '/boot/system/non-packaged'
1272 return '/usr/local'
1273
1274
1275 def default_datadir() -> str:
1276 if is_haiku():
1277 return 'data'
1278 return 'share'
1279
1280
1281 def default_includedir() -> str:
1282 if is_haiku():
1283 return 'develop/headers'
1284 return 'include'
1285
1286
1287 def default_infodir() -> str:
1288 if is_haiku():
1289 return 'documentation/info'
1290 return 'share/info'
1291
1292
1293 def default_localedir() -> str:
1294 if is_haiku():
1295 return 'data/locale'
1296 return 'share/locale'
1297
1298
1299 def default_mandir() -> str:
1300 if is_haiku():
1301 return 'documentation/man'
1302 return 'share/man'
1303
1304
1305 def default_sbindir() -> str:
1306 if is_haiku():
1307 return 'bin'
1308 return 'sbin'
1309
1310
1311 def default_sysconfdir() -> str:
1312 if is_haiku():
1313 return 'settings'
1314 return 'etc'
1315
1316
1317 def determine_worker_count(varnames: T.Optional[T.List[str]] = None) -> int:
1318 num_workers = 0
1319 varnames = varnames or []
1320 # Add MESON_NUM_PROCESSES last, so it will prevail if more than one
1321 # variable is present.
1322 varnames.append('MESON_NUM_PROCESSES')
1323 for varname in varnames:
1324 if varname in os.environ:
1325 try:
1326 num_workers = int(os.environ[varname])
1327 if num_workers < 0:
1328 raise ValueError
1329 except ValueError:
1330 print(f'Invalid value in {varname}, using 1 thread.')
1331 num_workers = 1
1332
1333 if num_workers <= 0:
1334 try:
1335 # Fails in some weird environments such as Debian
1336 # reproducible build.
1337 num_workers = multiprocessing.cpu_count()
1338 except Exception:
1339 num_workers = 1
1340 return num_workers
1341
1342 def is_parent_path(parent: str, trial: str) -> bool:
1343 '''Checks if @trial is a file under the directory @parent. Both @trial and @parent should be
1344 adequately normalized, though empty and '.' segments in @parent and @trial are accepted
1345 and discarded, matching the behavior of os.path.commonpath. Either both or none should
1346 be absolute.'''
1347 assert os.path.isabs(parent) == os.path.isabs(trial)
1348 if is_windows():
1349 parent = parent.replace('\\', '/')
1350 trial = trial.replace('\\', '/')
1351
1352 split_parent = parent.split('/')
1353 split_trial = trial.split('/')
1354
1355 split_parent = [c for c in split_parent if c and c != '.']
1356 split_trial = [c for c in split_trial if c and c != '.']
1357
1358 components = len(split_parent)
1359 return len(split_trial) >= components and split_trial[:components] == split_parent
1360
1361
1362 def has_path_sep(name: str, sep: str = '/\\') -> bool:
1363 'Checks if any of the specified @sep path separators are in @name'
1364 for each in sep:
1365 if each in name:
1366 return True
1367 return False
1368
1369
1370 if is_windows():
1371 # shlex.split is not suitable for splitting command line on Window (https://bugs.python.org/issue1724822);
1372 # shlex.quote is similarly problematic. Below are "proper" implementations of these functions according to
1373 # https://docs.microsoft.com/en-us/cpp/c-language/parsing-c-command-line-arguments and
1374 # https://blogs.msdn.microsoft.com/twistylittlepassagesallalike/2011/04/23/everyone-quotes-command-line-arguments-the-wrong-way/
1375
1376 _whitespace = ' \t\n\r'
1377 _find_unsafe_char = re.compile(fr'[{_whitespace}"]').search
1378
1379 @lru_cache(maxsize=4096)
1380 def quote_arg(arg: str) -> str:
1381 if arg and not _find_unsafe_char(arg):
1382 return arg
1383
1384 result = '"'
1385 num_backslashes = 0
1386 for c in arg:
1387 if c == '\\':
1388 num_backslashes += 1
1389 else:
1390 if c == '"':
1391 # Escape all backslashes and the following double quotation mark
1392 num_backslashes = num_backslashes * 2 + 1
1393
1394 result += num_backslashes * '\\' + c
1395 num_backslashes = 0
1396
1397 # Escape all backslashes, but let the terminating double quotation
1398 # mark we add below be interpreted as a metacharacter
1399 result += (num_backslashes * 2) * '\\' + '"'
1400 return result
1401
1402 def split_args(cmd: str) -> T.List[str]:
1403 result: T.List[str] = []
1404 arg = ''
1405 num_backslashes = 0
1406 num_quotes = 0
1407 in_quotes = False
1408 for c in cmd:
1409 if c == '\\':
1410 num_backslashes += 1
1411 else:
1412 if c == '"' and not num_backslashes % 2:
1413 # unescaped quote, eat it
1414 arg += (num_backslashes // 2) * '\\'
1415 num_quotes += 1
1416 in_quotes = not in_quotes
1417 elif c in _whitespace and not in_quotes:
1418 if arg or num_quotes:
1419 # reached the end of the argument
1420 result.append(arg)
1421 arg = ''
1422 num_quotes = 0
1423 else:
1424 if c == '"':
1425 # escaped quote
1426 num_backslashes = (num_backslashes - 1) // 2
1427
1428 arg += num_backslashes * '\\' + c
1429
1430 num_backslashes = 0
1431
1432 if arg or num_quotes:
1433 result.append(arg)
1434
1435 return result
1436 else:
1437 @lru_cache(maxsize=4096)
1438 def quote_arg(arg: str) -> str:
1439 return shlex.quote(arg)
1440
1441 def split_args(cmd: str) -> T.List[str]:
1442 return shlex.split(cmd)
1443
1444
1445 def join_args(args: T.Iterable[str]) -> str:
1446 return ' '.join([quote_arg(x) for x in args])
1447
1448
1449 def do_replacement(regex: T.Pattern[str], line: str,
1450 variable_format: Literal['meson', 'cmake', 'cmake@'],
1451 confdata: T.Union[T.Dict[str, T.Tuple[str, T.Optional[str]]], 'ConfigurationData']) -> T.Tuple[str, T.Set[str]]:
1452 if variable_format == 'meson':
1453 return do_replacement_meson(regex, line, confdata)
1454 elif variable_format in {'cmake', 'cmake@'}:
1455 return do_replacement_cmake(line, variable_format == 'cmake@', confdata)
1456 else:
1457 raise MesonException('Invalid variable format')
1458
1459 def do_replacement_meson(regex: T.Pattern[str], line: str,
1460 confdata: T.Union[T.Dict[str, T.Tuple[str, T.Optional[str]]], 'ConfigurationData']) -> T.Tuple[str, T.Set[str]]:
1461 missing_variables: T.Set[str] = set()
1462
1463 def variable_replace(match: T.Match[str]) -> str:
1464 # Pairs of escape characters before '@', '\@', '${' or '\${'
1465 if match.group(0).endswith('\\'):
1466 num_escapes = match.end(0) - match.start(0)
1467 return '\\' * (num_escapes // 2)
1468 # \@escaped\@ variables
1469 elif match.groupdict().get('escaped') is not None:
1470 return match.group('escaped')[1:-2]+'@'
1471 else:
1472 # Template variable to be replaced
1473 varname = match.group('variable')
1474 var_str = ''
1475 if varname in confdata:
1476 var, _ = confdata.get(varname)
1477 if isinstance(var, str):
1478 var_str = var
1479 elif isinstance(var, int):
1480 if isinstance(var, bool):
1481 msg = f'Variable substitution with boolean value {varname!r} is deprecated.'
1482 mlog.deprecation(msg)
1483 var_str = str(var)
1484 else:
1485 msg = f'Tried to replace variable {varname!r} value with ' \
1486 f'something other than a string or int: {var!r}'
1487 raise MesonException(msg)
1488 else:
1489 missing_variables.add(varname)
1490 return var_str
1491 return re.sub(regex, variable_replace, line), missing_variables
1492
1493 def do_replacement_cmake(line: str, at_only: bool,
1494 confdata: T.Union[T.Dict[str, T.Tuple[str, T.Optional[str]]], 'ConfigurationData']) -> T.Tuple[str, T.Set[str]]:
1495 missing_variables: T.Set[str] = set()
1496
1497 character_regex = re.compile(r'''
1498 [^a-zA-Z0-9_/.+\-]
1499 ''', re.VERBOSE)
1500
1501 def variable_get(varname: str) -> str:
1502 var_str = ''
1503 if varname in confdata:
1504 var, _ = confdata.get(varname)
1505 if isinstance(var, str):
1506 var_str = var
1507 elif isinstance(var, bool):
1508 var_str = str(int(var))
1509 elif isinstance(var, int):
1510 var_str = str(var)
1511 else:
1512 msg = f'Tried to replace variable {varname!r} value with ' \
1513 f'something other than a string or int: {var!r}'
1514 raise MesonException(msg)
1515 else:
1516 missing_variables.add(varname)
1517 return var_str
1518
1519 def parse_line(line: str) -> str:
1520 index = 0
1521 while len(line) > index:
1522 if line[index] == '@':
1523 next_at = line.find("@", index+1)
1524 if next_at > index+1:
1525 varname = line[index+1:next_at]
1526 match = character_regex.search(varname)
1527
1528 # at substituion doesn't occur if they key isn't valid
1529 # however it also doesn't raise an error
1530 if not match:
1531 value = variable_get(varname)
1532 line = line[:index] + value + line[next_at+1:]
1533
1534 elif not at_only and line[index:index+2] == '${':
1535 bracket_count = 1
1536 end_bracket = index + 2
1537 try:
1538 while bracket_count > 0:
1539 if line[end_bracket:end_bracket+2] == "${":
1540 end_bracket += 2
1541 bracket_count += 1
1542 elif line[end_bracket] == "}":
1543 end_bracket += 1
1544 bracket_count -= 1
1545 elif line[end_bracket] in {"@", "\n"}:
1546 # these aren't valid variable characters
1547 # but they are inconsequential at this point
1548 end_bracket += 1
1549 elif character_regex.search(line[end_bracket]):
1550 invalid_character = line[end_bracket]
1551 variable = line[index+2:end_bracket]
1552 msg = f'Found invalid character {invalid_character!r}' \
1553 f' in variable {variable!r}'
1554 raise MesonException(msg)
1555 else:
1556 end_bracket += 1
1557 except IndexError:
1558 msg = f'Found incomplete variable {line[index:-1]!r}'
1559 raise MesonException(msg)
1560
1561 if bracket_count == 0:
1562 varname = parse_line(line[index+2:end_bracket-1])
1563 match = character_regex.search(varname)
1564 if match:
1565 invalid_character = line[end_bracket-2]
1566 variable = line[index+2:end_bracket-3]
1567 msg = f'Found invalid character {invalid_character!r}' \
1568 f' in variable {variable!r}'
1569 raise MesonException(msg)
1570
1571 value = variable_get(varname)
1572 line = line[:index] + value + line[end_bracket:]
1573
1574 index += 1
1575
1576 return line
1577
1578 return parse_line(line), missing_variables
1579
1580 def do_define_meson(regex: T.Pattern[str], line: str, confdata: 'ConfigurationData',
1581 subproject: T.Optional[SubProject] = None) -> str:
1582
1583 arr = line.split()
1584 if len(arr) != 2:
1585 raise MesonException('#mesondefine does not contain exactly two tokens: %s' % line.strip())
1586
1587 varname = arr[1]
1588 try:
1589 v, _ = confdata.get(varname)
1590 except KeyError:
1591 return '/* #undef %s */\n' % varname
1592
1593 if isinstance(v, str):
1594 result = f'#define {varname} {v}'.strip() + '\n'
1595 result, _ = do_replacement_meson(regex, result, confdata)
1596 return result
1597 elif isinstance(v, bool):
1598 if v:
1599 return '#define %s\n' % varname
1600 else:
1601 return '#undef %s\n' % varname
1602 elif isinstance(v, int):
1603 return '#define %s %d\n' % (varname, v)
1604 else:
1605 raise MesonException('#mesondefine argument "%s" is of unknown type.' % varname)
1606
1607 def do_define_cmake(line: str, confdata: 'ConfigurationData', at_only: bool,
1608 subproject: T.Optional[SubProject] = None) -> str:
1609 cmake_bool_define = 'cmakedefine01' in line
1610
1611 def get_cmake_define(line: str, confdata: 'ConfigurationData') -> str:
1612 arr = line[1:].split()
1613
1614 if cmake_bool_define:
1615 (v, desc) = confdata.get(arr[1])
1616 return str(int(bool(v)))
1617
1618 define_value: T.List[str] = []
1619 for token in arr[2:]:
1620 try:
1621 v, _ = confdata.get(token)
1622 define_value += [str(v)]
1623 except KeyError:
1624 define_value += [token]
1625 return ' '.join(define_value)
1626
1627 arr = line[1:].split()
1628
1629 if len(arr) != 2 and subproject is not None:
1630 from ..interpreterbase.decorators import FeatureNew
1631 FeatureNew.single_use('cmakedefine without exactly two tokens', '0.54.1', subproject)
1632
1633 varname = arr[1]
1634 try:
1635 v, _ = confdata.get(varname)
1636 except KeyError:
1637 if cmake_bool_define:
1638 return '#define %s 0\n' % varname
1639 else:
1640 return '/* #undef %s */\n' % varname
1641
1642 if not cmake_bool_define and not v:
1643 return '/* #undef %s */\n' % varname
1644
1645 result = get_cmake_define(line, confdata)
1646 result = f'#define {varname} {result}'.strip() + '\n'
1647 result, _ = do_replacement_cmake(result, at_only, confdata)
1648 return result
1649
1650 def get_variable_regex(variable_format: Literal['meson', 'cmake', 'cmake@'] = 'meson') -> T.Pattern[str]:
1651 # Only allow (a-z, A-Z, 0-9, _, -) as valid characters for a define
1652 if variable_format == 'meson':
1653 # Also allow escaping pairs of '@' with '\@'
1654 regex = re.compile(r'''
1655 (?:\\\\)+(?=\\?@) # Matches multiple backslashes followed by an @ symbol
1656 | # OR
1657 (?<!\\)@(?P<variable>[-a-zA-Z0-9_]+)@ # Match a variable enclosed in @ symbols and capture the variable name; no matches beginning with '\@'
1658 | # OR
1659 (?P<escaped>\\@[-a-zA-Z0-9_]+\\@) # Match an escaped variable enclosed in @ symbols
1660 ''', re.VERBOSE)
1661 elif variable_format == 'cmake@':
1662 regex = re.compile(r'''
1663 (?<!\\)@(?P<variable>[-a-zA-Z0-9_]+)@ # Match a variable enclosed in @ symbols and capture the variable name; no matches beginning with '\@'
1664 ''', re.VERBOSE)
1665 elif variable_format == "cmake":
1666 regex = re.compile(r'''
1667 \${(?P<variable>[-a-zA-Z0-9_]*)} # Match a variable enclosed in curly braces and capture the variable name
1668 ''', re.VERBOSE)
1669 return regex
1670
1671 def do_conf_str(src: str, data: T.List[str], confdata: 'ConfigurationData',
1672 variable_format: Literal['meson', 'cmake', 'cmake@'],
1673 subproject: T.Optional[SubProject] = None) -> T.Tuple[T.List[str], T.Set[str], bool]:
1674 if variable_format == 'meson':
1675 return do_conf_str_meson(src, data, confdata, subproject)
1676 elif variable_format in {'cmake', 'cmake@'}:
1677 return do_conf_str_cmake(src, data, confdata, variable_format == 'cmake@', subproject)
1678 else:
1679 raise MesonException('Invalid variable format')
1680
1681 def do_conf_str_meson(src: str, data: T.List[str], confdata: 'ConfigurationData',
1682 subproject: T.Optional[SubProject] = None) -> T.Tuple[T.List[str], T.Set[str], bool]:
1683
1684 regex = get_variable_regex('meson')
1685
1686 search_token = '#mesondefine'
1687
1688 result: T.List[str] = []
1689 missing_variables: T.Set[str] = set()
1690 # Detect when the configuration data is empty and no tokens were found
1691 # during substitution so we can warn the user to use the `copy:` kwarg.
1692 confdata_useless = not confdata.keys()
1693 for line in data:
1694 if line.lstrip().startswith(search_token):
1695 confdata_useless = False
1696 line = do_define_meson(regex, line, confdata, subproject)
1697 else:
1698 if re.search(r'#\s*cmakedefine', line):
1699 raise MesonException(f'Format error in {src}: saw "{line.strip()}" when format set to "meson"')
1700 line, missing = do_replacement_meson(regex, line, confdata)
1701 missing_variables.update(missing)
1702 if missing:
1703 confdata_useless = False
1704 result.append(line)
1705
1706 return result, missing_variables, confdata_useless
1707
1708 def do_conf_str_cmake(src: str, data: T.List[str], confdata: 'ConfigurationData', at_only: bool,
1709 subproject: T.Optional[SubProject] = None) -> T.Tuple[T.List[str], T.Set[str], bool]:
1710
1711 variable_format: Literal['cmake', 'cmake@'] = 'cmake'
1712 if at_only:
1713 variable_format = 'cmake@'
1714
1715 search_token = 'cmakedefine'
1716
1717 result: T.List[str] = []
1718 missing_variables: T.Set[str] = set()
1719 # Detect when the configuration data is empty and no tokens were found
1720 # during substitution so we can warn the user to use the `copy:` kwarg.
1721 confdata_useless = not confdata.keys()
1722 for line in data:
1723 stripped_line = line.lstrip()
1724 if len(stripped_line) >= 2 and stripped_line[0] == '#' and stripped_line[1:].lstrip().startswith(search_token):
1725 if not stripped_line[1:].startswith(search_token):
1726 from ..interpreterbase.decorators import FeatureNew
1727 FeatureNew.single_use('whitespace between `#` and `cmakedefine`', '1.9.0', subproject)
1728 confdata_useless = False
1729 line = do_define_cmake(line, confdata, at_only, subproject)
1730 else:
1731 if '#mesondefine' in line:
1732 raise MesonException(f'Format error in {src}: saw "{line.strip()}" when format set to "{variable_format}"')
1733 line, missing = do_replacement_cmake(line, at_only, confdata)
1734 missing_variables.update(missing)
1735 if missing:
1736 confdata_useless = False
1737 result.append(line)
1738
1739 return result, missing_variables, confdata_useless
1740
1741 def do_conf_file(src: str, dst: str, confdata: 'ConfigurationData',
1742 variable_format: Literal['meson', 'cmake', 'cmake@'],
1743 encoding: str = 'utf-8', subproject: T.Optional[SubProject] = None) -> T.Tuple[T.Set[str], bool]:
1744 try:
1745 with open(src, encoding=encoding, newline='') as f:
1746 data = f.readlines()
1747 except Exception as e:
1748 raise MesonException(f'Could not read input file {src}: {e!s}')
1749
1750 (result, missing_variables, confdata_useless) = do_conf_str(src, data, confdata, variable_format, subproject)
1751 dst_tmp = dst + '~'
1752 try:
1753 with open(dst_tmp, 'w', encoding=encoding, newline='') as f:
1754 f.writelines(result)
1755 except Exception as e:
1756 raise MesonException(f'Could not write output file {dst}: {e!s}')
1757 shutil.copymode(src, dst_tmp)
1758 replace_if_different(dst, dst_tmp)
1759 return missing_variables, confdata_useless
1760
1761 CONF_C_PRELUDE = '''/*
1762 * Autogenerated by the Meson build system.
1763 * Do not edit, your changes will be lost.
1764 */
1765
1766 {}
1767
1768 '''
1769
1770 CONF_NASM_PRELUDE = '''; Autogenerated by the Meson build system.
1771 ; Do not edit, your changes will be lost.
1772
1773 '''
1774
1775 def _dump_c_header(ofile: T.TextIO,
1776 cdata: ConfigurationData,
1777 output_format: Literal['c', 'nasm'],
1778 macro_name: T.Optional[str]) -> None:
1779 format_desc: T.Callable[[str], str]
1780 if output_format == 'c':
1781 if macro_name:
1782 prelude = CONF_C_PRELUDE.format('#ifndef {0}\n#define {0}'.format(macro_name))
1783 else:
1784 prelude = CONF_C_PRELUDE.format('#pragma once')
1785 prefix = '#'
1786 format_desc = lambda desc: f'/* {desc} */\n'
1787 else: # nasm
1788 prelude = CONF_NASM_PRELUDE
1789 prefix = '%'
1790 format_desc = lambda desc: '; ' + '\n; '.join(desc.splitlines()) + '\n'
1791
1792 ofile.write(prelude)
1793 for k in sorted(cdata.keys()):
1794 (v, desc) = cdata.get(k)
1795 if desc:
1796 ofile.write(format_desc(desc))
1797 if isinstance(v, bool):
1798 if v:
1799 ofile.write(f'{prefix}define {k}\n\n')
1800 else:
1801 ofile.write(f'{prefix}undef {k}\n\n')
1802 elif isinstance(v, (int, str)):
1803 ofile.write(f'{prefix}define {k} {v}\n\n')
1804 else:
1805 raise MesonException('Unknown data type in configuration file entry: ' + k)
1806 if output_format == 'c' and macro_name:
1807 ofile.write('#endif\n')
1808
1809
1810 def dump_conf_header(ofilename: str, cdata: ConfigurationData,
1811 output_format: Literal['c', 'nasm', 'json'],
1812 macro_name: T.Optional[str]) -> None:
1813 ofilename_tmp = ofilename + '~'
1814 with open(ofilename_tmp, 'w', encoding='utf-8') as ofile:
1815 if output_format == 'json':
1816 data = {k: v[0] for k, v in cdata.values.items()}
1817 json.dump(data, ofile, sort_keys=True)
1818 else: # c, nasm
1819 _dump_c_header(ofile, cdata, output_format, macro_name)
1820
1821 replace_if_different(ofilename, ofilename_tmp)
1822
1823
1824 def replace_if_different(dst: str, dst_tmp: str) -> None:
1825 # If contents are identical, don't touch the file to prevent
1826 # unnecessary rebuilds.
1827 different = True
1828 try:
1829 with open(dst, 'rb') as f1, open(dst_tmp, 'rb') as f2:
1830 if f1.read() == f2.read():
1831 different = False
1832 except FileNotFoundError:
1833 pass
1834 if different:
1835 os.replace(dst_tmp, dst)
1836 else:
1837 os.unlink(dst_tmp)
1838
1839
1840 def listify(item: T.Any, flatten: bool = True) -> T.List[T.Any]:
1841 '''
1842 Returns a list with all args embedded in a list if they are not a list.
1843 This function preserves order.
1844 @flatten: Convert lists of lists to a flat list
1845 '''
1846 if not isinstance(item, list):
1847 return [item]
1848 result: T.List[T.Any] = []
1849 for i in item:
1850 if flatten and isinstance(i, list):
1851 result += listify(i, flatten=True)
1852 else:
1853 result.append(i)
1854 return result
1855
1856 def listify_array_value(value: object, shlex_split_args: bool = False) -> T.List[str]:
1857 if isinstance(value, str):
1858 if value.startswith('['):
1859 try:
1860 newvalue = ast.literal_eval(value)
1861 except ValueError:
1862 raise MesonException(f'malformed value {value}')
1863 elif value == '':
1864 newvalue = []
1865 else:
1866 if shlex_split_args:
1867 newvalue = split_args(value)
1868 else:
1869 newvalue = [v.strip() for v in value.split(',')]
1870 elif isinstance(value, list):
1871 newvalue = value
1872 else:
1873 raise MesonException(f'"{value}" should be a string array, but it is not')
1874 assert isinstance(newvalue, list)
1875 return newvalue
1876
1877 def extract_as_list(dict_object: T.Dict[_T, _U], key: _T, pop: bool = False) -> T.List[_U]:
1878 '''
1879 Extracts all values from given dict_object and listifies them.
1880 '''
1881 fetch: T.Callable[[_T], _U] = dict_object.get
1882 if pop:
1883 fetch = dict_object.pop
1884 # If there's only one key, we don't return a list with one element
1885 return listify(fetch(key) or [], flatten=True)
1886
1887
1888 def typeslistify(item: 'T.Union[_T, T.Sequence[_T]]',
1889 types: 'T.Union[T.Type[_T], T.Tuple[T.Type[_T]]]') -> T.List[_T]:
1890 '''
1891 Ensure that type(@item) is one of @types or a
1892 list of items all of which are of type @types
1893 '''
1894 if isinstance(item, types):
1895 item = T.cast('T.List[_T]', [item])
1896 if not isinstance(item, list):
1897 raise MesonException('Item must be a list or one of {!r}, not {!r}'.format(types, type(item)))
1898 for i in item:
1899 if i is not None and not isinstance(i, types):
1900 raise MesonException('List item must be one of {!r}, not {!r}'.format(types, type(i)))
1901 return item
1902
1903
1904 def stringlistify(item: T.Union[T.Any, T.Sequence[T.Any]]) -> T.List[str]:
1905 return typeslistify(item, str)
1906
1907 def underscorify(item: str) -> str:
1908 return re.sub(r'[^a-zA-Z0-9]', '_', item)
1909
1910 def expand_arguments(args: T.Iterable[str]) -> T.Optional[T.List[str]]:
1911 expended_args: T.List[str] = []
1912 for arg in args:
1913 if not arg.startswith('@'):
1914 expended_args.append(arg)
1915 continue
1916
1917 args_file = arg[1:]
1918 try:
1919 with open(args_file, encoding='utf-8') as f:
1920 extended_args = f.read().split()
1921 expended_args += extended_args
1922 except Exception as e:
1923 mlog.error('Expanding command line arguments:', args_file, 'not found')
1924 mlog.exception(e)
1925 return None
1926 return expended_args
1927
1928
1929 def partition(pred: T.Callable[[_T], object], iterable: T.Iterable[_T]) -> T.Tuple[T.Iterator[_T], T.Iterator[_T]]:
1930 """Use a predicate to partition entries into false entries and true
1931 entries.
1932
1933 >>> x, y = partition(is_odd, range(10))
1934 >>> (list(x), list(y))
1935 ([0, 2, 4, 6, 8], [1, 3, 5, 7, 9])
1936 """
1937 t1, t2 = tee(iterable)
1938 return (t for t in t1 if not pred(t)), (t for t in t2 if pred(t))
1939
1940
1941 def Popen_safe(args: T.List[str], write: T.Optional[str] = None,
1942 stdin: T.Union[None, T.TextIO, T.BinaryIO, int] = subprocess.DEVNULL,
1943 stdout: T.Union[None, T.TextIO, T.BinaryIO, int] = subprocess.PIPE,
1944 stderr: T.Union[None, T.TextIO, T.BinaryIO, int] = subprocess.PIPE,
1945 **kwargs: T.Any) -> T.Tuple['subprocess.Popen[str]', str, str]:
1946 import locale
1947 encoding = locale.getpreferredencoding()
1948 # Stdin defaults to DEVNULL otherwise the command run by us here might mess
1949 # up the console and ANSI colors will stop working on Windows.
1950 # If write is not None, set stdin to PIPE so data can be sent.
1951 if write is not None:
1952 stdin = subprocess.PIPE
1953
1954 try:
1955 if not sys.stdout.encoding or encoding.upper() != 'UTF-8':
1956 p, o, e = Popen_safe_legacy(args, write=write, stdin=stdin, stdout=stdout, stderr=stderr, **kwargs)
1957 else:
1958 p = subprocess.Popen(args, universal_newlines=True, encoding=encoding, close_fds=False,
1959 stdin=stdin, stdout=stdout, stderr=stderr, **kwargs)
1960 o, e = p.communicate(write)
1961 except OSError as oserr:
1962 if oserr.errno == errno.ENOEXEC:
1963 raise MesonException(f'Failed running {args[0]!r}, binary or interpreter not executable.\n'
1964 'Possibly wrong architecture or the executable bit is not set.')
1965 raise
1966 # Sometimes the command that we run will call another command which will be
1967 # without the above stdin workaround, so set the console mode again just in
1968 # case.
1969 mlog.setup_console()
1970 return p, o, e
1971
1972
1973 def Popen_safe_legacy(args: T.List[str], write: T.Optional[str] = None,
1974 stdin: T.Union[None, T.TextIO, T.BinaryIO, int] = subprocess.DEVNULL,
1975 stdout: T.Union[None, T.TextIO, T.BinaryIO, int] = subprocess.PIPE,
1976 stderr: T.Union[None, T.TextIO, T.BinaryIO, int] = subprocess.PIPE,
1977 **kwargs: T.Any) -> T.Tuple['subprocess.Popen[str]', str, str]:
1978 p = subprocess.Popen(args, universal_newlines=False, close_fds=False,
1979 stdin=stdin, stdout=stdout, stderr=stderr, **kwargs)
1980 input_: T.Optional[bytes] = None
1981 if write is not None:
1982 input_ = write.encode('utf-8')
1983 o, e = p.communicate(input_)
1984 if o is not None:
1985 if sys.stdout.encoding is not None:
1986 o = o.decode(encoding=sys.stdout.encoding, errors='replace').replace('\r\n', '\n')
1987 else:
1988 o = o.decode(errors='replace').replace('\r\n', '\n')
1989 if e is not None:
1990 if sys.stderr is not None and sys.stderr.encoding:
1991 e = e.decode(encoding=sys.stderr.encoding, errors='replace').replace('\r\n', '\n')
1992 else:
1993 e = e.decode(errors='replace').replace('\r\n', '\n')
1994 return p, o, e
1995
1996
1997 def Popen_safe_logged(args: T.List[str], msg: str = 'Called', **kwargs: T.Any) -> T.Tuple['subprocess.Popen[str]', str, str]:
1998 '''
1999 Wrapper around Popen_safe that assumes standard piped o/e and logs this to the meson log.
2000 '''
2001 try:
2002 p, o, e = Popen_safe(args, **kwargs)
2003 except Exception as excp:
2004 mlog.debug('-----------')
2005 mlog.debug(f'{msg}: `{join_args(args)}` -> {excp}')
2006 raise
2007
2008 rc, out, err = p.returncode, o.strip() if o else None, e.strip() if e else None
2009 mlog.debug('-----------')
2010 mlog.debug(f'{msg}: `{join_args(args)}` -> {rc}')
2011 if out:
2012 mlog.debug(f'stdout:\n{out}\n-----------')
2013 if err:
2014 mlog.debug(f'stderr:\n{err}\n-----------')
2015 return p, o, e
2016
2017
2018 def iter_regexin_iter(regexiter: T.Iterable[str], initer: T.Iterable[object]) -> T.Optional[str]:
2019 '''
2020 Takes each regular expression in @regexiter and tries to search for it in
2021 every item in @initer. If there is a match, returns that match.
2022 Else returns False.
2023 '''
2024 for regex in regexiter:
2025 for ii in initer:
2026 if not isinstance(ii, str):
2027 continue
2028 match = re.search(regex, ii)
2029 if match:
2030 return match.group()
2031 return None
2032
2033
2034 def _substitute_values_check_errors(command: T.Sequence[object], values: T.Dict[str, T.Union[str, T.List[str]]]) -> None:
2035 # Error checking
2036 inregex: T.List[str] = ['@INPUT([0-9]+)?@', '@PLAINNAME@', '@BASENAME@']
2037 outregex: T.List[str] = ['@OUTPUT([0-9]+)?@', '@OUTDIR@']
2038 if '@INPUT@' not in values:
2039 # Error out if any input-derived templates are present in the command
2040 match = iter_regexin_iter(inregex, command)
2041 if match:
2042 raise MesonException(f'Command cannot have {match!r}, since no input files were specified')
2043 else:
2044 if len(values['@INPUT@']) > 1:
2045 # Error out if @PLAINNAME@ or @BASENAME@ is present in the command
2046 match = iter_regexin_iter(inregex[1:], command)
2047 if match:
2048 raise MesonException(f'Command cannot have {match!r} when there is '
2049 'more than one input file')
2050 # Error out if an invalid @INPUTnn@ template was specified
2051 for each in command:
2052 if not isinstance(each, str):
2053 continue
2054 match2 = re.search(inregex[0], each)
2055 if match2 and match2.group() not in values:
2056 m = 'Command cannot have {!r} since there are only {!r} inputs'
2057 raise MesonException(m.format(match2.group(), len(values['@INPUT@'])))
2058 if '@OUTPUT@' not in values:
2059 # Error out if any output-derived templates are present in the command
2060 match = iter_regexin_iter(outregex, command)
2061 if match:
2062 raise MesonException(f'Command cannot have {match!r} since there are no outputs')
2063 else:
2064 # Error out if an invalid @OUTPUTnn@ template was specified
2065 for each in command:
2066 if not isinstance(each, str):
2067 continue
2068 match2 = re.search(outregex[0], each)
2069 if match2 and match2.group() not in values:
2070 m = 'Command cannot have {!r} since there are only {!r} outputs'
2071 raise MesonException(m.format(match2.group(), len(values['@OUTPUT@'])))
2072
2073
2074 def substitute_values(command: T.List[_T],
2075 values: T.Dict[str, T.Union[str, T.List[str]]]
2076 ) -> T.List[_T]:
2077 '''
2078 Substitute the template strings in the @values dict into the list of
2079 strings @command and return a new list. For a full list of the templates,
2080 see get_filenames_templates_dict()
2081
2082 If multiple inputs/outputs are given in the @values dictionary, we
2083 substitute @INPUT@ and @OUTPUT@ only if they are the entire string, not
2084 just a part of it, and in that case we substitute *all* of them.
2085
2086 The typing of this function is difficult, as only @OUTPUT@ and @INPUT@ can
2087 be lists, everything else is a string. However, TypeDict cannot represent
2088 this, as you can have optional keys, but not extra keys. We end up just
2089 having to use asserts to convince type checkers that this is okay.
2090
2091 https://github.com/python/mypy/issues/4617
2092 '''
2093
2094 # Error checking and quick exit
2095 _substitute_values_check_errors(command, values)
2096 if not values:
2097 return list(command)
2098
2099 # Substitution
2100 rx_keys = [re.escape(key) for key in values]
2101 value_rx = re.compile('|'.join(rx_keys))
2102
2103 def replace(m: T.Match[str]) -> str:
2104 v = values[m.group(0)]
2105 if isinstance(v, list):
2106 if len(v) > 1 and m.group(0) == '@INPUT@':
2107 raise MesonException("Command has '@INPUT@' as part of a "
2108 "string and more than one input file")
2109 if len(v) > 1 and m.group(0) == '@OUTPUT@':
2110 raise MesonException("Command has '@OUTPUT@' as part of a "
2111 "string and more than one output file")
2112 return v[0]
2113 return v
2114
2115 outcmd: T.List[_T] = []
2116 for vv in command:
2117 if not isinstance(vv, str):
2118 outcmd.append(vv)
2119 elif vv in values:
2120 # Append values that are exactly a template string.
2121 # This is faster than a string replace, and makes it
2122 # possible to special case @INPUT@ and @OUTPUT@ too
2123
2124 # We have to do a bunch of casting here because mypy doesn't realize
2125 # that if we're adding str to this list then we got string inputs,
2126 # and attempting to set the return type to `_T | str` causes
2127 # problems elswhere, so let's contain the pain here.
2128 if vv == '@INPUT@':
2129 inputs = values['@INPUT@']
2130 assert isinstance(inputs, list)
2131 outcmd += T.cast('list[_T]', inputs)
2132 elif vv == '@OUTPUT@':
2133 outputs = values['@OUTPUT@']
2134 assert isinstance(outputs, list)
2135 outcmd += T.cast('list[_T]', outputs)
2136 else:
2137 o = values[vv]
2138 assert isinstance(o, str), 'for mypy'
2139 outcmd.append(T.cast('_T', o))
2140 else:
2141 # Substitute everything else with replacement
2142 assert values
2143 outcmd.append(T.cast('_T', value_rx.sub(replace, vv)))
2144
2145 return outcmd
2146
2147
2148 def get_filenames_templates_dict(inputs: T.List[str], outputs: T.List[str]) -> T.Dict[str, T.Union[str, T.List[str]]]:
2149 '''
2150 Create a dictionary with template strings as keys and values as values for
2151 the following templates:
2152
2153 @INPUT@ - the full path to one or more input files, from @inputs
2154 @OUTPUT@ - the full path to one or more output files, from @outputs
2155 @OUTDIR@ - the full path to the directory containing the output files
2156
2157 If there is only one input file, the following keys are also created:
2158
2159 @PLAINNAME@ - the filename of the input file
2160 @BASENAME@ - the filename of the input file with the extension removed
2161
2162 If there is more than one input file, the following keys are also created:
2163
2164 @INPUT0@, @INPUT1@, ... one for each input file
2165 @PLAINNAME0@, @PLAINNAME1@, ... one for each input file
2166 @BASENAME0@, @BASENAME1@, ... one for each input file
2167
2168 If there is more than one output file, the following keys are also created:
2169
2170 @OUTPUT0@, @OUTPUT1@, ... one for each output file
2171 '''
2172 values: T.Dict[str, T.Union[str, T.List[str]]] = {}
2173 # Gather values derived from the input
2174 if inputs:
2175 # We want to substitute all the inputs.
2176 values['@INPUT@'] = inputs
2177 for (ii, vv) in enumerate(inputs):
2178 # Write out @INPUT0@, @INPUT1@, ...
2179 values[f'@INPUT{ii}@'] = vv
2180 plain = os.path.basename(vv)
2181 values[f'@PLAINNAME{ii}@'] = plain
2182 values[f'@BASENAME{ii}@'] = os.path.splitext(plain)[0]
2183 if len(inputs) == 1:
2184 # Just one value, substitute @PLAINNAME@ and @BASENAME@
2185 values['@PLAINNAME@'] = plain = os.path.basename(inputs[0])
2186 values['@BASENAME@'] = os.path.splitext(plain)[0]
2187 if outputs:
2188 # Gather values derived from the outputs, similar to above.
2189 values['@OUTPUT@'] = outputs
2190 for (ii, vv) in enumerate(outputs):
2191 values[f'@OUTPUT{ii}@'] = vv
2192 # Outdir should be the same for all outputs
2193 values['@OUTDIR@'] = os.path.dirname(outputs[0])
2194 # Many external programs fail on empty arguments.
2195 if values['@OUTDIR@'] == '':
2196 values['@OUTDIR@'] = '.'
2197 return values
2198
2199
2200 def _make_tree_writable(topdir: T.Union[str, Path]) -> None:
2201 # Ensure all files and directories under topdir are writable
2202 # (and readable) by owner.
2203 for d, _, files in os.walk(topdir):
2204 os.chmod(d, os.stat(d).st_mode | stat.S_IWRITE | stat.S_IREAD)
2205 for fname in files:
2206 fpath = os.path.join(d, fname)
2207 if not os.path.islink(fpath) and os.path.isfile(fpath):
2208 os.chmod(fpath, os.stat(fpath).st_mode | stat.S_IWRITE | stat.S_IREAD)
2209
2210
2211 def windows_proof_rmtree(f: T.Union[str, Path]) -> None:
2212 # On Windows if anyone is holding a file open you can't
2213 # delete it. As an example an anti virus scanner might
2214 # be scanning files you are trying to delete. The only
2215 # way to fix this is to try again and again.
2216 delays = [0.1, 0.1, 0.2, 0.2, 0.2, 0.5, 0.5, 1, 1, 1, 1, 2]
2217 writable = False
2218 for d in delays:
2219 try:
2220 # Start by making the tree writable.
2221 if not writable:
2222 _make_tree_writable(f)
2223 writable = True
2224 except PermissionError:
2225 time.sleep(d)
2226 continue
2227 try:
2228 shutil.rmtree(f)
2229 return
2230 except FileNotFoundError:
2231 return
2232 except OSError:
2233 time.sleep(d)
2234 # Try one last time and throw if it fails.
2235 shutil.rmtree(f)
2236
2237
2238 def windows_proof_rm(fpath: T.Union[str, Path]) -> None:
2239 """Like windows_proof_rmtree, but for a single file."""
2240 if os.path.isfile(fpath):
2241 os.chmod(fpath, os.stat(fpath).st_mode | stat.S_IWRITE | stat.S_IREAD)
2242 delays = [0.1, 0.1, 0.2, 0.2, 0.2, 0.5, 0.5, 1, 1, 1, 1, 2]
2243 for d in delays:
2244 try:
2245 os.unlink(fpath)
2246 return
2247 except FileNotFoundError:
2248 return
2249 except OSError:
2250 time.sleep(d)
2251 os.unlink(fpath)
2252
2253
2254 class TemporaryDirectoryWinProof(TemporaryDirectory):
2255 """
2256 Like TemporaryDirectory, but cleans things up using
2257 windows_proof_rmtree()
2258 """
2259
2260 def __exit__(self, exc: T.Any, value: T.Any, tb: T.Any) -> None:
2261 try:
2262 super().__exit__(exc, value, tb)
2263 except OSError:
2264 windows_proof_rmtree(self.name)
2265
2266 def cleanup(self) -> None:
2267 try:
2268 super().cleanup()
2269 except OSError:
2270 windows_proof_rmtree(self.name)
2271
2272
2273 def detect_subprojects(spdir_name: str, current_dir: str = '',
2274 result: T.Optional[T.Dict[str, T.List[str]]] = None) -> T.Dict[str, T.List[str]]:
2275 if result is None:
2276 result = {}
2277 spdir = os.path.join(current_dir, spdir_name)
2278 if not os.path.exists(spdir):
2279 return result
2280 for trial in glob(os.path.join(spdir, '*')):
2281 basename = os.path.basename(trial)
2282 if trial == 'packagecache':
2283 continue
2284 append_this = True
2285 if os.path.isdir(trial):
2286 spdir_name = get_subproject_dir(trial) or 'subprojects'
2287
2288 detect_subprojects(spdir_name, trial, result)
2289 elif trial.endswith('.wrap') and os.path.isfile(trial):
2290 basename = os.path.splitext(basename)[0]
2291 else:
2292 append_this = False
2293 if append_this:
2294 if basename in result:
2295 result[basename].append(trial)
2296 else:
2297 result[basename] = [trial]
2298 return result
2299
2300
2301 def substring_is_in_list(substr: str, strlist: T.List[str]) -> bool:
2302 for s in strlist:
2303 if substr in s:
2304 return True
2305 return False
2306
2307
2308 def unique_list(x: T.Iterable[_T]) -> T.List[_T]:
2309 return list(dict.fromkeys(x))
2310
2311
2312 class OrderedSet(T.MutableSet[_T]):
2313 """A set that preserves the order in which items are added, by first
2314 insertion.
2315 """
2316 def __init__(self, iterable: T.Optional[T.Iterable[_T]] = None):
2317 self.__container: T.OrderedDict[_T, None] = collections.OrderedDict()
2318 if iterable:
2319 self.update(iterable)
2320
2321 def __contains__(self, value: object) -> bool:
2322 return value in self.__container
2323
2324 def __iter__(self) -> T.Iterator[_T]:
2325 return iter(self.__container.keys())
2326
2327 def __len__(self) -> int:
2328 return len(self.__container)
2329
2330 def __repr__(self) -> str:
2331 # Don't print 'OrderedSet("")' for an empty set.
2332 if self.__container:
2333 return 'OrderedSet([{}])'.format(
2334 ', '.join(repr(e) for e in self.__container.keys()))
2335 return 'OrderedSet()'
2336
2337 def __reversed__(self) -> T.Iterator[_T]:
2338 return reversed(self.__container.keys())
2339
2340 def add(self, value: _T) -> None:
2341 self.__container[value] = None
2342
2343 def discard(self, value: _T) -> None:
2344 if value in self.__container:
2345 del self.__container[value]
2346
2347 def move_to_end(self, value: _T, last: bool = True) -> None:
2348 self.__container.move_to_end(value, last)
2349
2350 def pop(self, last: bool = True) -> _T:
2351 item, _ = self.__container.popitem(last)
2352 return item
2353
2354 def update(self, iterable: T.Iterable[_T]) -> None:
2355 for item in iterable:
2356 self.__container[item] = None
2357
2358 def difference(self, set_: T.Iterable[_T]) -> 'OrderedSet[_T]':
2359 return type(self)(e for e in self if e not in set_)
2360
2361 def difference_update(self, iterable: T.Iterable[_T]) -> None:
2362 for item in iterable:
2363 self.discard(item)
2364
2365 def relpath(path: T.Union[str, Path], start: T.Union[str, Path]) -> str:
2366 # On Windows a relative path can't be evaluated for paths on two different
2367 # drives (i.e. c:\foo and f:\bar). The only thing left to do is to use the
2368 # original absolute path.
2369 try:
2370 return os.path.relpath(path, start)
2371 except (TypeError, ValueError):
2372 return str(path)
2373
2374 def path_is_in_root(path: Path, root: Path, resolve: bool = False) -> bool:
2375 # Check whether a path is within the root directory root
2376 try:
2377 if resolve:
2378 path.resolve().relative_to(root.resolve())
2379 else:
2380 path.relative_to(root)
2381 except ValueError:
2382 return False
2383 return True
2384
2385 def relative_to_if_possible(path: Path, root: Path, resolve: bool = False) -> Path:
2386 try:
2387 if resolve:
2388 return path.resolve().relative_to(root.resolve())
2389 else:
2390 return path.relative_to(root)
2391 except ValueError:
2392 return path
2393
2394 class LibType(enum.IntEnum):
2395
2396 """Enumeration for library types."""
2397
2398 SHARED = 0
2399 STATIC = 1
2400 PREFER_SHARED = 2
2401 PREFER_STATIC = 3
2402
2403
2404 class ProgressBarFallback(T.Generic[_T]):
2405 '''
2406 Fallback progress bar implementation when tqdm is not foundclass OptionType(enum.IntEnum):
2407
2408 """Enum used to specify what kind of argument a thing is."""
2409
2410 BUILTIN = 0
2411 BACKEND = 1
2412 BASE = 2
2413 COMPILER = 3
2414 PROJECT = 4
2415
2416 # This is copied from coredata. There is no way to share this, because this
2417 # is used in the OptionKey constructor, and the coredata lists are
2418 # OptionKeys...
2419 _BUILTIN_NAMES = {
2420 'prefix',
2421 'bindir',
2422 'datadir',
2423 'includedir',
2424 'infodir',
2425 'libdir',
2426 'licensedir',
2427 'libexecdir',
2428 'localedir',
2429 'localstatedir',
2430 'mandir',
2431 'sbindir',
2432 'sharedstatedir',
2433 'sysconfdir',
2434 'auto_features',
2435 'backend',
2436 'buildtype',
2437 'debug',
2438 'default_library',
2439 'errorlogs',
2440 'genvslite',
2441 'install_umask',
2442 'layout',
2443 'optimization',
2444 'prefer_static',
2445 'stdsplit',
2446 'strip',
2447 'unity',
2448 'unity_size',
2449 'warning_level',
2450 'werror',
2451 'wrap_mode',
2452 'force_fallback_for',
2453 'pkg_config_path',
2454 'cmake_prefix_path',
2455 'vsenv',
2456 'os2_emxomf',
2457 }
2458
2459
2460 Since this class is not an actual iterator, but only provides a minimal
2461 fallback, it is safe to ignore the 'Iterator does not return self from
2462 __iter__ method' warning.
2463 '''
2464 def __init__(self, iterable: T.Optional[T.Iterable[_T]] = None, total: T.Optional[int] = None,
2465 bar_type: T.Optional[str] = None, desc: T.Optional[str] = None,
2466 disable: T.Optional[bool] = None):
2467 if iterable is not None:
2468 self.iterable = iter(iterable)
2469 return
2470 self.total = total
2471 self.done = 0
2472 self.printed_dots = 0
2473 self.disable = not mlog.colorize_console() if disable is None else disable
2474 if not self.disable:
2475 if self.total and bar_type == 'download':
2476 print('Download size:', self.total)
2477 if desc:
2478 print(f'{desc}: ', end='')
2479
2480 # Pretend to be an iterator when called as one and don't print any
2481 # progress
2482 def __iter__(self) -> T.Iterator[_T]:
2483 return self.iterable
2484
2485 def __next__(self) -> _T:
2486 return next(self.iterable)
2487
2488 def print_dot(self) -> None:
2489 if not self.disable:
2490 print('.', end='')
2491 sys.stdout.flush()
2492 self.printed_dots += 1
2493
2494 def update(self, progress: int) -> None:
2495 self.done += progress
2496 if not self.total:
2497 # Just print one dot per call if we don't have a total length
2498 self.print_dot()
2499 return
2500 ratio = int(self.done / self.total * 10)
2501 while self.printed_dots < ratio:
2502 self.print_dot()
2503
2504 def close(self) -> None:
2505 if not self.disable:
2506 print()
2507
2508 try:
2509 from tqdm import tqdm
2510 except ImportError:
2511 # ideally we would use a typing.Protocol here, but it's part of typing_extensions until 3.8
2512 ProgressBar: T.Union[T.Type[ProgressBarFallback], T.Type[ProgressBarTqdm]] = ProgressBarFallback
2513 else:
2514 class ProgressBarTqdm(tqdm):
2515 def __init__(self, *args: T.Any, bar_type: T.Optional[str] = None, **kwargs: T.Any) -> None:
2516 if bar_type == 'download':
2517 kwargs.update({'unit': 'B',
2518 'unit_scale': True,
2519 'unit_divisor': 1024,
2520 'leave': True,
2521 'bar_format': '{l_bar}{bar}| {n_fmt}/{total_fmt} {rate_fmt} eta {remaining}',
2522 })
2523
2524 else:
2525 kwargs.update({'leave': False,
2526 'bar_format': '{l_bar}{bar}| {n_fmt}/{total_fmt} eta {remaining}',
2527 })
2528 super().__init__(*args, **kwargs)
2529
2530 ProgressBar = ProgressBarTqdm
2531
2532
2533 class RealPathAction(argparse.Action):
2534 def __init__(self, option_strings: T.List[str], dest: str, default: str = '.', **kwargs: T.Any):
2535 default = os.path.abspath(os.path.realpath(default))
2536 super().__init__(option_strings, dest, nargs=None, default=default, **kwargs)
2537
2538 def __call__(self, parser: argparse.ArgumentParser, namespace: argparse.Namespace,
2539 values: T.Union[str, T.Sequence[T.Any], None], option_string: T.Optional[str] = None) -> None:
2540 assert isinstance(values, str)
2541 setattr(namespace, self.dest, os.path.abspath(os.path.realpath(values)))
2542
2543
2544 def get_wine_shortpath(winecmd: T.List[str], wine_paths: T.List[str],
2545 workdir: T.Optional[str] = None) -> str:
2546 '''
2547 WINEPATH size is limited to 1024 bytes which can easily be exceeded when
2548 adding the path to every dll inside build directory. See
2549 https://bugs.winehq.org/show_bug.cgi?id=45810.
2550
2551 To shorten it as much as possible we use path relative to `workdir`
2552 where possible and convert absolute paths to Windows shortpath (e.g.
2553 "/usr/x86_64-w64-mingw32/lib" to "Z:\\usr\\X86_~FWL\\lib").
2554
2555 This limitation reportedly has been fixed with wine >= 6.4
2556 '''
2557
2558 # Remove duplicates
2559 wine_paths = list(OrderedSet(wine_paths))
2560
2561 # Check if it's already short enough
2562 wine_path = ';'.join(wine_paths)
2563 if len(wine_path) <= 1024:
2564 return wine_path
2565
2566 # Check if we have wine >= 6.4
2567 from ..programs import ExternalProgram
2568 wine = ExternalProgram('wine', winecmd, silent=True)
2569 if version_compare(wine.get_version(), '>=6.4'):
2570 return wine_path
2571
2572 # Check paths that can be reduced by making them relative to workdir.
2573 rel_paths: T.List[str] = []
2574 if workdir:
2575 abs_paths: T.List[str] = []
2576 for p in wine_paths:
2577 try:
2578 rel = Path(p).relative_to(workdir)
2579 rel_paths.append(str(rel))
2580 except ValueError:
2581 abs_paths.append(p)
2582 wine_paths = abs_paths
2583
2584 if wine_paths:
2585 # BAT script that takes a list of paths in argv and prints semi-colon separated shortpaths
2586 with NamedTemporaryFile('w', suffix='.bat', encoding='utf-8', delete=False) as bat_file:
2587 bat_file.write('''
2588 @ECHO OFF
2589 for %%x in (%*) do (
2590 echo|set /p=;%~sx
2591 )
2592 ''')
2593 try:
2594 stdout = subprocess.check_output(winecmd + ['cmd', '/C', bat_file.name] + wine_paths,
2595 encoding='utf-8', stderr=subprocess.DEVNULL)
2596 stdout = stdout.strip(';')
2597 if stdout:
2598 wine_paths = stdout.split(';')
2599 else:
2600 mlog.warning('Could not shorten WINEPATH: empty stdout')
2601 except subprocess.CalledProcessError as e:
2602 mlog.warning(f'Could not shorten WINEPATH: {str(e)}')
2603 finally:
2604 os.unlink(bat_file.name)
2605 wine_path = ';'.join(rel_paths + wine_paths)
2606 if len(wine_path) > 1024:
2607 mlog.warning('WINEPATH exceeds 1024 characters which could cause issues')
2608 return wine_path
2609
2610
2611 def run_once(func: T.Callable[_P, _T]) -> T.Callable[_P, _T]:
2612 ret: T.List[_T] = []
2613
2614 @wraps(func)
2615 def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> _T:
2616 if ret:
2617 return ret[0]
2618
2619 val = func(*args, **kwargs)
2620 ret.append(val)
2621 return val
2622
2623 return wrapper
2624
2625
2626 def generate_list(func: T.Callable[_P, T.Generator[_T, None, None]]) -> T.Callable[_P, T.List[_T]]:
2627 @wraps(func)
2628 def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> T.List[_T]:
2629 return list(func(*args, **kwargs))
2630
2631 return wrapper
2632
2633
2634 def pickle_load(filename: str, object_name: str, object_type: T.Type[_PL], suggest_reconfigure: bool = True) -> _PL:
2635 load_fail_msg = f'{object_name} file {filename!r} is corrupted.'
2636 extra_msg = ' Consider reconfiguring the directory with "meson setup --reconfigure".' if suggest_reconfigure else ''
2637 try:
2638 with open(filename, 'rb') as f:
2639 obj = pickle.load(f)
2640 except (pickle.UnpicklingError, EOFError):
2641 raise MesonException(load_fail_msg + extra_msg)
2642 except (TypeError, ModuleNotFoundError, AttributeError):
2643 raise MesonException(
2644 f"{object_name} file {filename!r} references functions or classes that don't "
2645 "exist. This probably means that it was generated with an old "
2646 "version of meson." + extra_msg)
2647
2648 if not isinstance(obj, object_type):
2649 raise MesonException(load_fail_msg + extra_msg)
2650
2651 # Because these Protocols are not available at runtime (and cannot be made
2652 # available at runtime until we drop support for Python < 3.8), we have to
2653 # do a bit of hackery so that mypy understands what's going on here
2654 version: str
2655 if hasattr(obj, 'version'):
2656 version = T.cast('_VerPickleLoadable', obj).version
2657 else:
2658 version = T.cast('_EnvPickleLoadable', obj).environment.coredata.version
2659
2660 from ..coredata import version as coredata_version
2661 from ..coredata import major_versions_differ, MesonVersionMismatchException
2662 if major_versions_differ(version, coredata_version):
2663 raise MesonVersionMismatchException(version, coredata_version, extra_msg)
2664 return obj
2665
2666
2667 def first(iter: T.Iterable[_T], predicate: T.Callable[[_T], bool]) -> T.Optional[_T]:
2668 """Find the first entry in an iterable where the given predicate is true
2669
2670 :param iter: The iterable to search
2671 :param predicate: A finding function that takes an element from the iterable
2672 and returns True if found, otherwise False
2673 :return: The first found element, or None if it is not found
2674 """
2675 for i in iter:
2676 if predicate(i):
2677 return i
2678 return None
2679
2680
2681 def get_rsp_threshold() -> int:
2682 '''Return a conservative estimate of the commandline size in bytes
2683 above which a response file should be used. May be overridden for
2684 debugging by setting environment variable MESON_RSP_THRESHOLD.'''
2685
2686 if is_windows():
2687 # Usually 32k, but some projects might use cmd.exe,
2688 # and that has a limit of 8k.
2689 limit = 8192
2690 else:
2691 # Unix-like OSes usually have very large command line limits, (On Linux,
2692 # for example, this is limited by the kernel's MAX_ARG_STRLEN). However,
2693 # some programs place much lower limits, notably Wine which enforces a
2694 # 32k limit like Windows. Therefore, we limit the command line to 32k.
2695 limit = 32768
2696
2697 # Be conservative
2698 limit = limit // 2
2699 return int(os.environ.get('MESON_RSP_THRESHOLD', limit))
2700
2701
2702 class lazy_property(T.Generic[_T]):
2703 """Descriptor that replaces the function it wraps with the value generated.
2704
2705 This property will only be calculated the first time it's queried, and will
2706 be cached and the cached value used for subsequent calls.
2707
2708 This works by shadowing itself with the calculated value, in the instance.
2709 Due to Python's MRO that means that the calculated value will be found
2710 before this property, speeding up subsequent lookups.
2711 """
2712 def __init__(self, func: T.Callable[[T.Any], _T]) -> None:
2713 self.__name: T.Optional[str] = None
2714 self.__func = func
2715
2716 def __set_name__(self, owner: T.Any, name: str) -> None:
2717 if self.__name is None:
2718 self.__name = name
2719 else:
2720 assert name == self.__name
2721
2722 def __get__(self, instance: object, cls: T.Type) -> _T:
2723 value = self.__func(instance)
2724 setattr(instance, self.__name, value)
2725 return value
2726
2727
2728 class late_property(T.Generic[_T]):
2729 """Descriptor that allows setting a property late and erroring if it's
2730 accessed early.
2731
2732 This property allows a more ergonomically typed equivalent of
2733 self.value: T | None = None, since you then don't need to worry about
2734 whether self.value is None.
2735 """
2736
2737 def __init__(self) -> None:
2738 self.__name: str | None = None
2739
2740 def __set_name__(self, owner: object, name: str) -> None:
2741 if self.__name is None:
2742 self.__name = name
2743 else:
2744 assert self.__name == name
2745
2746 def __get__(self, instance: T.Any, cls: type) -> _T:
2747 raise MesonBugException(f'Attempted to access attribute {self.__name} before it is set')
2748
2749
2750 def get_subproject_dir(directory: str = '.') -> T.Optional[str]:
2751 """Get the name of the subproject directory for a specific project.
2752
2753 If the subproject does not have a meson.build file, it is called in an
2754 invalid directory, it returns None
2755
2756 :param directory: Where to search, defaults to current working directory
2757 :return: the name of the subproject directory or None.
2758 """
2759 from ..ast import IntrospectionInterpreter
2760 from ..interpreterbase.exceptions import InvalidArguments
2761 intr = IntrospectionInterpreter(directory, '', 'none')
2762 try:
2763 intr.load_root_meson_file()
2764 except InvalidArguments: # Root meson file cannot be found
2765 return None
2766
2767 return intr.extract_subproject_dir() or 'subprojects'
2768
2769
2770 def lookbehind(it_: T.Iterable[_T]) -> T.Iterator[T.Tuple[T.Optional[_T], _T]]:
2771 """Get the current value of the iterable, and the previous if possible.
2772
2773 :param iter: The iterable to look into
2774 :yield: A tuple of the previous value if possible, and the current one
2775 :return: nothing
2776 """
2777 prev: T.Optional[_T] = None
2778 it: T.Iterator[_T] = iter(it_)
2779 while True:
2780 try:
2781 current = next(it)
2782 yield prev, current
2783 prev = current
2784 except StopIteration:
2785 break
2786
2787
2788 def lookahead(it_: T.Iterable[_T]) -> T.Iterator[T.Tuple[_T, T.Optional[_T]]]:
2789 """Get the current value of the iterable, and the next if possible.
2790
2791 :param iter: The iterable to look into
2792 :yield: A tuple of the current value, and, if possible, the next
2793 :return: nothing
2794 """
2795 current: _T
2796 next_: T.Optional[_T]
2797 it: T.Iterator[_T] = iter(it_)
2798 try:
2799 next_ = next(it)
2800 except StopIteration:
2801 # This is an empty iterator, there's nothing to look ahead to
2802 return
2803
2804 while True:
2805 current = next_
2806 try:
2807 next_ = next(it)
2808 except StopIteration:
2809 next_ = None
2810
2811 yield current, next_
2812
2813 if next_ is None:
2814 break
2815
2816
2817 def pathname_sort_key(key: str) -> tuple[tuple[bool, tuple[int | str, ...]], ...]:
2818 '''Sort key for natural pathname sort, as defined in the Meson style guide.
2819 Use as the key= argument to sort() or sorted().'''
2820
2821 def convert(text: str) -> int | str:
2822 return int(text) if text.isdigit() else text.lower()
2823
2824 def alphanum_key(key: str) -> tuple[int | str, ...]:
2825 return tuple(convert(c) for c in re.split('([0-9]+)', key))
2826
2827 return tuple((key.count('/') <= idx, alphanum_key(x))
2828 for idx, x in enumerate(key.split('/')))
2829
2830
2831 def unwrap(value: _T | None, msg: str | None = None) -> _T:
2832 """Remove None from a union type when it is a Meson bug.
2833
2834 This is used for cases where None being in the Union is a bug in Meson
2835 itself.
2836
2837 :param value: The Union
2838 :param msg: A message to print when a buggy value occurs, defaults to None
2839 :raises MesonBugException: When None is in value
2840 :return: The value union with None removed
2841 """
2842 if value is not None:
2843 return value
2844 raise MesonBugException(msg or 'Unexpected None value')
2845
2846
2847 def unwrap_err(value: _T | None, msg: str) -> _T:
2848 """Remove None from a union type when it is not a Meson bug.
2849
2850 This is for cases where None is possible, but it represents a problem
2851 outside of Meson itself.
2852
2853 For example, a missing external program, or a read only file system, or a
2854 missing file
2855
2856 :param value: The Union to remove None from
2857 :param msg: The message to print when None is found
2858 :raises MesonException: When None is found in the union
2859 :return: The Union with None removed
2860 """
2861 if value is not None:
2862 return value
2863 raise MesonException(msg)