| 1 |
# SPDX-License-Identifier: Apache-2.0 |
| 2 |
# Copyright 2012-2022 The Meson development team |
| 3 |
|
| 4 |
""" |
| 5 |
Contains the strict minimum to run scripts. |
| 6 |
|
| 7 |
When the backend needs to call back into Meson during compilation for running |
| 8 |
scripts or wrapping commands, it is important to load as little python modules |
| 9 |
as possible for performance reasons. |
| 10 |
""" |
| 11 |
|
| 12 |
from __future__ import annotations |
| 13 |
from dataclasses import dataclass |
| 14 |
import os |
| 15 |
import typing as T |
| 16 |
|
| 17 |
if T.TYPE_CHECKING: |
| 18 |
from hashlib import _Hash |
| 19 |
from typing_extensions import Literal |
| 20 |
from ..mparser import BaseNode |
| 21 |
from .. import programs |
| 22 |
from .universal import SubProject |
| 23 |
|
| 24 |
EnvironOrDict = T.Union[T.Dict[str, str], os._Environ[str]] |
| 25 |
|
| 26 |
EnvInitValueType = T.Dict[str, T.Union[str, T.List[str]]] |
| 27 |
|
| 28 |
|
| 29 |
class MesonException(Exception): |
| 30 |
'''Exceptions thrown by Meson''' |
| 31 |
|
| 32 |
def __init__(self, *args: object, file: T.Optional[str] = None, |
| 33 |
lineno: T.Optional[int] = None, colno: T.Optional[int] = None): |
| 34 |
super().__init__(*args) |
| 35 |
self.file = file |
| 36 |
self.lineno = lineno |
| 37 |
self.colno = colno |
| 38 |
|
| 39 |
@classmethod |
| 40 |
def from_node(cls, *args: object, node: BaseNode) -> MesonException: |
| 41 |
"""Create a MesonException with location data from a BaseNode |
| 42 |
|
| 43 |
:param node: A BaseNode to set location data from |
| 44 |
:return: A Meson Exception instance |
| 45 |
""" |
| 46 |
return cls(*args, file=node.filename, lineno=node.lineno, colno=node.colno) |
| 47 |
|
| 48 |
class MesonBugException(MesonException): |
| 49 |
'''Exceptions thrown when there is a clear Meson bug that should be reported''' |
| 50 |
|
| 51 |
def __init__(self, msg: str, file: T.Optional[str] = None, |
| 52 |
lineno: T.Optional[int] = None, colno: T.Optional[int] = None): |
| 53 |
super().__init__(msg + '\n\n This is a Meson bug and should be reported!', |
| 54 |
file=file, lineno=lineno, colno=colno) |
| 55 |
|
| 56 |
class HoldableObject: |
| 57 |
''' Dummy base class for all objects that can be |
| 58 |
held by an interpreter.baseobjects.ObjectHolder ''' |
| 59 |
def __new__(cls, *args: T.Any, **kwargs: T.Any) -> HoldableObject: |
| 60 |
if cls is HoldableObject: |
| 61 |
raise TypeError(f"Can't instantiate abstract class {cls.__name__}") |
| 62 |
return super().__new__(cls) |
| 63 |
|
| 64 |
class EnvironmentVariables(HoldableObject): |
| 65 |
def __init__(self, values: T.Optional[EnvInitValueType] = None, |
| 66 |
init_method: Literal['set', 'prepend', 'append'] = 'set', separator: str = os.pathsep) -> None: |
| 67 |
self.envvars: T.List[T.Tuple[T.Callable[[T.Dict[str, str], str, T.List[str], str, T.Optional[str]], str], str, T.List[str], str]] = [] |
| 68 |
# The set of all env vars we have operations for. Only used for self.has_name() |
| 69 |
self.varnames: T.Set[str] = set() |
| 70 |
self.unset_vars: T.Set[str] = set() |
| 71 |
self.can_use_env = True |
| 72 |
|
| 73 |
if values: |
| 74 |
init_func = getattr(self, init_method) |
| 75 |
for name, value in values.items(): |
| 76 |
v = value if isinstance(value, list) else [value] |
| 77 |
init_func(name, v, separator) |
| 78 |
|
| 79 |
def __repr__(self) -> str: |
| 80 |
repr_str = "<{0}: {1}>" |
| 81 |
return repr_str.format(self.__class__.__name__, self.envvars) |
| 82 |
|
| 83 |
def hash(self, hasher: _Hash) -> None: |
| 84 |
myenv = self.get_env({}) |
| 85 |
for key in sorted(myenv.keys()): |
| 86 |
hasher.update(bytes(key, encoding='utf-8')) |
| 87 |
hasher.update(b',') |
| 88 |
hasher.update(bytes(myenv[key], encoding='utf-8')) |
| 89 |
hasher.update(b';') |
| 90 |
|
| 91 |
def has_name(self, name: str) -> bool: |
| 92 |
return name in self.varnames |
| 93 |
|
| 94 |
def get_names(self) -> T.Set[str]: |
| 95 |
return self.varnames |
| 96 |
|
| 97 |
def merge(self, other: EnvironmentVariables) -> None: |
| 98 |
for method, name, values, separator in other.envvars: |
| 99 |
self.varnames.add(name) |
| 100 |
self.envvars.append((method, name, values, separator)) |
| 101 |
if name in self.unset_vars: |
| 102 |
self.unset_vars.remove(name) |
| 103 |
if other.unset_vars: |
| 104 |
self.can_use_env = False |
| 105 |
self.unset_vars.update(other.unset_vars) |
| 106 |
|
| 107 |
def set(self, name: str, values: T.List[str], separator: str = os.pathsep) -> None: |
| 108 |
if name in self.unset_vars: |
| 109 |
raise MesonException(f'You cannot set the already unset variable {name!r}') |
| 110 |
self.varnames.add(name) |
| 111 |
self.envvars.append((self._set, name, values, separator)) |
| 112 |
|
| 113 |
def unset(self, name: str) -> None: |
| 114 |
self.can_use_env = False |
| 115 |
if name in self.varnames: |
| 116 |
raise MesonException(f'You cannot unset the {name!r} variable because it is already set') |
| 117 |
self.unset_vars.add(name) |
| 118 |
|
| 119 |
def append(self, name: str, values: T.List[str], separator: str = os.pathsep) -> None: |
| 120 |
self.can_use_env = False |
| 121 |
if name in self.unset_vars: |
| 122 |
raise MesonException(f'You cannot append to unset variable {name!r}') |
| 123 |
self.varnames.add(name) |
| 124 |
self.envvars.append((self._append, name, values, separator)) |
| 125 |
|
| 126 |
def prepend(self, name: str, values: T.List[str], separator: str = os.pathsep) -> None: |
| 127 |
self.can_use_env = False |
| 128 |
if name in self.unset_vars: |
| 129 |
raise MesonException(f'You cannot prepend to unset variable {name!r}') |
| 130 |
self.varnames.add(name) |
| 131 |
self.envvars.append((self._prepend, name, values, separator)) |
| 132 |
|
| 133 |
@staticmethod |
| 134 |
def _set(env: T.Dict[str, str], name: str, values: T.List[str], separator: str, default_value: T.Optional[str]) -> str: |
| 135 |
return separator.join(values) |
| 136 |
|
| 137 |
@staticmethod |
| 138 |
def _append(env: T.Dict[str, str], name: str, values: T.List[str], separator: str, default_value: T.Optional[str]) -> str: |
| 139 |
curr = env.get(name, default_value) |
| 140 |
return separator.join(values if curr is None else [curr] + values) |
| 141 |
|
| 142 |
@staticmethod |
| 143 |
def _prepend(env: T.Dict[str, str], name: str, values: T.List[str], separator: str, default_value: T.Optional[str]) -> str: |
| 144 |
curr = env.get(name, default_value) |
| 145 |
return separator.join(values if curr is None else values + [curr]) |
| 146 |
|
| 147 |
def get_env(self, full_env: EnvironOrDict, default_fmt: T.Optional[str] = None) -> T.Dict[str, str]: |
| 148 |
env = full_env.copy() |
| 149 |
for method, name, values, separator in self.envvars: |
| 150 |
default_value = default_fmt.format(name) if default_fmt else None |
| 151 |
env[name] = method(env, name, values, separator, default_value) |
| 152 |
for name in self.unset_vars: |
| 153 |
env.pop(name, None) |
| 154 |
return env |
| 155 |
|
| 156 |
|
| 157 |
@dataclass(eq=False) |
| 158 |
class ExecutableSerialisation: |
| 159 |
|
| 160 |
cmd_args: T.List[str] |
| 161 |
env: T.Optional[EnvironmentVariables] = None |
| 162 |
exe_wrapper: T.Optional['programs.ExternalProgram'] = None |
| 163 |
workdir: T.Optional[str] = None |
| 164 |
extra_paths: T.Optional[T.List] = None |
| 165 |
capture: T.Optional[str] = None |
| 166 |
feed: T.Optional[str] = None |
| 167 |
tag: T.Optional[str] = None |
| 168 |
verbose: bool = False |
| 169 |
installdir_map: T.Optional[T.Dict[str, str]] = None |
| 170 |
|
| 171 |
def __post_init__(self) -> None: |
| 172 |
self.pickled = False |
| 173 |
self.skip_if_destdir = False |
| 174 |
self.subproject = T.cast('SubProject', '') # avoid circular import |
| 175 |
self.dry_run = False |