diff options
author | Dylan Baker <dylan@pnwbakers.com> | 2020-09-09 10:31:52 -0700 |
---|---|---|
committer | GitHub <noreply@github.com> | 2020-09-09 10:31:52 -0700 |
commit | 4c2d0eb9bcedefa3ef06a237a0502afbc581268b (patch) | |
tree | 1b08ca5fb0c93573409a7a8954e6e1905f8a5b10 /mesonbuild/mesonlib.py | |
parent | 8d54b7bda30062569c981b50a85a175565a7c15a (diff) | |
parent | 057c77f7d08b3372e99065fb3f3cd37f16801a82 (diff) | |
download | meson-4c2d0eb9bcedefa3ef06a237a0502afbc581268b.zip meson-4c2d0eb9bcedefa3ef06a237a0502afbc581268b.tar.gz meson-4c2d0eb9bcedefa3ef06a237a0502afbc581268b.tar.bz2 |
Merge pull request #7657 from mensinda/moreTyping
typing: Strict type annotations
Diffstat (limited to 'mesonbuild/mesonlib.py')
-rw-r--r-- | mesonbuild/mesonlib.py | 97 |
1 files changed, 36 insertions, 61 deletions
diff --git a/mesonbuild/mesonlib.py b/mesonbuild/mesonlib.py index a510ab9..f649738 100644 --- a/mesonbuild/mesonlib.py +++ b/mesonbuild/mesonlib.py @@ -19,7 +19,7 @@ import stat import time import platform, subprocess, operator, os, shlex, shutil, re import collections -from enum import Enum +from enum import IntEnum from functools import lru_cache, wraps from itertools import tee, filterfalse import typing as T @@ -289,7 +289,7 @@ class File: def split(self, s: str) -> T.List[str]: return self.fname.split(s) - def __eq__(self, other) -> bool: + def __eq__(self, other: object) -> bool: if not isinstance(other, File): return NotImplemented if self.hash != other.hash: @@ -323,32 +323,7 @@ def classify_unity_sources(compilers: T.Iterable['CompilerType'], sources: T.Ite return compsrclist -class OrderedEnum(Enum): - """ - An Enum which additionally offers homogeneous ordered comparison. - """ - def __ge__(self, other): - if self.__class__ is other.__class__: - return self.value >= other.value - return NotImplemented - - def __gt__(self, other): - if self.__class__ is other.__class__: - return self.value > other.value - return NotImplemented - - def __le__(self, other): - if self.__class__ is other.__class__: - return self.value <= other.value - return NotImplemented - - def __lt__(self, other): - if self.__class__ is other.__class__: - return self.value < other.value - return NotImplemented - - -class MachineChoice(OrderedEnum): +class MachineChoice(IntEnum): """Enum class representing one of the two abstract machine names used in most places: the build, and host, machines. @@ -365,7 +340,7 @@ class MachineChoice(OrderedEnum): class PerMachine(T.Generic[_T]): - def __init__(self, build: _T, host: _T): + def __init__(self, build: _T, host: _T) -> None: self.build = build self.host = host @@ -403,7 +378,7 @@ class PerThreeMachine(PerMachine[_T]): need to computer the `target` field so we don't bother overriding the `__getitem__`/`__setitem__` methods. """ - def __init__(self, build: _T, host: _T, target: _T): + def __init__(self, build: _T, host: _T, target: _T) -> None: super().__init__(build, host) self.target = target @@ -434,7 +409,7 @@ class PerThreeMachine(PerMachine[_T]): class PerMachineDefaultable(PerMachine[T.Optional[_T]]): """Extends `PerMachine` with the ability to default from `None`s. """ - def __init__(self): + def __init__(self) -> None: super().__init__(None, None) def default_missing(self) -> "PerMachine[T.Optional[_T]]": @@ -455,7 +430,7 @@ class PerMachineDefaultable(PerMachine[T.Optional[_T]]): class PerThreeMachineDefaultable(PerMachineDefaultable, PerThreeMachine[T.Optional[_T]]): """Extends `PerThreeMachine` with the ability to default from `None`s. """ - def __init__(self): + def __init__(self) -> None: PerThreeMachine.__init__(self, None, None, None) def default_missing(self) -> "PerThreeMachine[T.Optional[_T]]": @@ -589,7 +564,7 @@ def detect_vcs(source_dir: T.Union[str, Path]) -> T.Optional[T.Dict[str, str]]: # a helper class which implements the same version ordering as RPM class Version: - def __init__(self, s: str): + def __init__(self, s: str) -> None: self._s = s # split into numeric, alphabetic and non-alphanumeric sequences @@ -603,38 +578,38 @@ class Version: self._v = sequences3 - def __str__(self): + def __str__(self) -> str: return '%s (V=%s)' % (self._s, str(self._v)) - def __repr__(self): + def __repr__(self) -> str: return '<Version: {}>'.format(self._s) - def __lt__(self, other): + def __lt__(self, other: object) -> bool: if isinstance(other, Version): return self.__cmp(other, operator.lt) return NotImplemented - def __gt__(self, other): + def __gt__(self, other: object) -> bool: if isinstance(other, Version): return self.__cmp(other, operator.gt) return NotImplemented - def __le__(self, other): + def __le__(self, other: object) -> bool: if isinstance(other, Version): return self.__cmp(other, operator.le) return NotImplemented - def __ge__(self, other): + def __ge__(self, other: object) -> bool: if isinstance(other, Version): return self.__cmp(other, operator.ge) return NotImplemented - def __eq__(self, other): + def __eq__(self, other: object) -> bool: if isinstance(other, Version): return self._v == other._v return NotImplemented - def __ne__(self, other): + def __ne__(self, other: object) -> bool: if isinstance(other, Version): return self._v != other._v return NotImplemented @@ -740,7 +715,7 @@ def version_compare_condition_with_min(condition: str, minimum: str) -> bool: if re.match(r'^\d+.\d+$', condition): condition += '.0' - return cmpop(Version(minimum), Version(condition)) + return T.cast(bool, cmpop(Version(minimum), Version(condition))) def default_libdir() -> str: @@ -924,20 +899,20 @@ def do_replacement(regex: T.Pattern[str], line: str, variable_format: str, # Template variable to be replaced else: varname = match.group(1) + var_str = '' if varname in confdata: (var, desc) = confdata.get(varname) if isinstance(var, str): - pass + var_str = var elif isinstance(var, int): - var = str(var) + var_str = str(var) else: msg = 'Tried to replace variable {!r} value with ' \ 'something other than a string or int: {!r}' raise MesonException(msg.format(varname, var)) else: missing_variables.add(varname) - var = '' - return var + return var_str return re.sub(regex, variable_replace, line), missing_variables def do_define(regex: T.Pattern[str], line: str, confdata: 'ConfigurationData', variable_format: str) -> str: @@ -947,7 +922,7 @@ def do_define(regex: T.Pattern[str], line: str, confdata: 'ConfigurationData', v for token in arr[2:]: try: (v, desc) = confdata.get(token) - define_value += [v] + define_value += [str(v)] except KeyError: define_value += [token] return ' '.join(define_value) @@ -981,14 +956,14 @@ def do_define(regex: T.Pattern[str], line: str, confdata: 'ConfigurationData', v def do_conf_str (data: list, confdata: 'ConfigurationData', variable_format: str, encoding: str = 'utf-8') -> T.Tuple[T.List[str],T.Set[str], bool]: - def line_is_valid(line : str, variable_format: str): - if variable_format == 'meson': - if '#cmakedefine' in line: - return False - else: #cmake format - if '#mesondefine' in line: - return False - return True + def line_is_valid(line : str, variable_format: str) -> bool: + if variable_format == 'meson': + if '#cmakedefine' in line: + return False + else: #cmake format + if '#mesondefine' in line: + return False + return True # Only allow (a-z, A-Z, 0-9, _, -) as valid characters for a define # Also allow escaping '@' with '\@' @@ -1115,7 +1090,7 @@ def unholder(item: T.List[_T]) -> T.List[_T]: ... @T.overload def unholder(item: T.List[T.Union[_T, 'ObjectHolder[_T]']]) -> T.List[_T]: ... -def unholder(item): +def unholder(item): # type: ignore # TODO fix overload (somehow) """Get the held item of an object holder or list of object holders.""" if isinstance(item, list): return [i.held_object if hasattr(i, 'held_object') else i for i in item] @@ -1531,10 +1506,10 @@ class OrderedSet(T.MutableSet[_T]): class BuildDirLock: - def __init__(self, builddir: str): + def __init__(self, builddir: str) -> None: self.lockfilename = os.path.join(builddir, 'meson-private/meson.lock') - def __enter__(self): + def __enter__(self) -> None: self.lockfile = open(self.lockfilename, 'w') try: if have_fcntl: @@ -1545,7 +1520,7 @@ class BuildDirLock: self.lockfile.close() raise MesonException('Some other Meson process is already using this build directory. Exiting.') - def __exit__(self, *args): + def __exit__(self, *args: T.Any) -> None: if have_fcntl: fcntl.flock(self.lockfile, fcntl.LOCK_UN) elif have_msvcrt: @@ -1572,7 +1547,7 @@ def path_is_in_root(path: Path, root: Path, resolve: bool = False) -> bool: return False return True -class LibType(Enum): +class LibType(IntEnum): """Enumeration for library types.""" @@ -1636,7 +1611,7 @@ except ImportError: ProgressBar = ProgressBarFallback # type: T.Union[T.Type[ProgressBarFallback], T.Type[ProgressBarTqdm]] else: class ProgressBarTqdm(tqdm): - def __init__(self, *args, bar_type: T.Optional[str] = None, **kwargs): + def __init__(self, *args: T.Any, bar_type: T.Optional[str] = None, **kwargs: T.Any) -> None: if bar_type == 'download': kwargs.update({'unit': 'bytes', 'leave': True}) else: |