|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import sys |
| 4 | +from inspect import isclass |
| 5 | +from pathlib import Path |
| 6 | +from typing import ( |
| 7 | + TYPE_CHECKING, |
| 8 | + Any, |
| 9 | + Dict, |
| 10 | + Iterator, |
| 11 | + List, |
| 12 | + Literal, |
| 13 | + Mapping, |
| 14 | + Set, |
| 15 | + TypeVar, |
| 16 | + Union, |
| 17 | + cast, |
| 18 | +) |
| 19 | + |
| 20 | +from tox.config.loader.api import Loader, Override |
| 21 | +from tox.config.types import Command, EnvList |
| 22 | + |
| 23 | +if TYPE_CHECKING: |
| 24 | + from tox.config.loader.section import Section |
| 25 | + from tox.config.main import Config |
| 26 | + |
| 27 | +if sys.version_info >= (3, 11): # pragma: no cover (py311+) |
| 28 | + from typing import TypeGuard |
| 29 | +else: # pragma: no cover (py311+) |
| 30 | + from typing_extensions import TypeGuard |
| 31 | +if sys.version_info >= (3, 10): # pragma: no cover (py310+) |
| 32 | + from typing import TypeAlias |
| 33 | +else: # pragma: no cover (py310+) |
| 34 | + from typing_extensions import TypeAlias |
| 35 | + |
| 36 | +TomlTypes: TypeAlias = Union[Dict[str, "TomlTypes"], List["TomlTypes"], str, int, float, bool, None] |
| 37 | + |
| 38 | + |
| 39 | +class TomlLoader(Loader[TomlTypes]): |
| 40 | + """Load configuration from a pyproject.toml file.""" |
| 41 | + |
| 42 | + def __init__( |
| 43 | + self, |
| 44 | + section: Section, |
| 45 | + overrides: list[Override], |
| 46 | + content: Mapping[str, TomlTypes], |
| 47 | + unused_exclude: set[str], |
| 48 | + ) -> None: |
| 49 | + self.content = content |
| 50 | + self._unused_exclude = unused_exclude |
| 51 | + super().__init__(section, overrides) |
| 52 | + |
| 53 | + def __repr__(self) -> str: |
| 54 | + return f"{self.__class__.__name__}({self.section.name}, {self.content!r})" |
| 55 | + |
| 56 | + def load_raw(self, key: str, conf: Config | None, env_name: str | None) -> TomlTypes: # noqa: ARG002 |
| 57 | + return self.content[key] |
| 58 | + |
| 59 | + def found_keys(self) -> set[str]: |
| 60 | + return set(self.content.keys()) - self._unused_exclude |
| 61 | + |
| 62 | + @staticmethod |
| 63 | + def to_str(value: TomlTypes) -> str: |
| 64 | + return _ensure_type_correct(value, str) # type: ignore[return-value] # no mypy support |
| 65 | + |
| 66 | + @staticmethod |
| 67 | + def to_bool(value: TomlTypes) -> bool: |
| 68 | + return _ensure_type_correct(value, bool) |
| 69 | + |
| 70 | + @staticmethod |
| 71 | + def to_list(value: TomlTypes, of_type: type[Any]) -> Iterator[_T]: |
| 72 | + of = List[of_type] # type: ignore[valid-type] # no mypy support |
| 73 | + return iter(_ensure_type_correct(value, of)) # type: ignore[call-overload,no-any-return] |
| 74 | + |
| 75 | + @staticmethod |
| 76 | + def to_set(value: TomlTypes, of_type: type[Any]) -> Iterator[_T]: |
| 77 | + of = Set[of_type] # type: ignore[valid-type] # no mypy support |
| 78 | + return iter(_ensure_type_correct(value, of)) # type: ignore[call-overload,no-any-return] |
| 79 | + |
| 80 | + @staticmethod |
| 81 | + def to_dict(value: TomlTypes, of_type: tuple[type[Any], type[Any]]) -> Iterator[tuple[_T, _T]]: |
| 82 | + of = Dict[of_type[0], of_type[1]] # type: ignore[valid-type] # no mypy support |
| 83 | + return _ensure_type_correct(value, of).items() # type: ignore[attr-defined,no-any-return] |
| 84 | + |
| 85 | + @staticmethod |
| 86 | + def to_path(value: TomlTypes) -> Path: |
| 87 | + return Path(TomlLoader.to_str(value)) |
| 88 | + |
| 89 | + @staticmethod |
| 90 | + def to_command(value: TomlTypes) -> Command: |
| 91 | + return Command(args=cast(List[str], value)) # validated during load in _ensure_type_correct |
| 92 | + |
| 93 | + @staticmethod |
| 94 | + def to_env_list(value: TomlTypes) -> EnvList: |
| 95 | + return EnvList(envs=list(TomlLoader.to_list(value, str))) |
| 96 | + |
| 97 | + |
| 98 | +_T = TypeVar("_T") |
| 99 | + |
| 100 | + |
| 101 | +def _ensure_type_correct(val: TomlTypes, of_type: type[_T]) -> TypeGuard[_T]: # noqa: C901, PLR0912 |
| 102 | + casting_to = getattr(of_type, "__origin__", of_type.__class__) |
| 103 | + msg = "" |
| 104 | + if casting_to in {list, List}: |
| 105 | + entry_type = of_type.__args__[0] # type: ignore[attr-defined] |
| 106 | + if isinstance(val, list): |
| 107 | + for va in val: |
| 108 | + _ensure_type_correct(va, entry_type) |
| 109 | + else: |
| 110 | + msg = f"{val!r} is not list" |
| 111 | + elif isclass(of_type) and issubclass(of_type, Command): |
| 112 | + # first we cast it to list then create commands, so for now just validate is a nested list |
| 113 | + _ensure_type_correct(val, List[str]) |
| 114 | + elif casting_to in {set, Set}: |
| 115 | + entry_type = of_type.__args__[0] # type: ignore[attr-defined] |
| 116 | + if isinstance(val, set): |
| 117 | + for va in val: |
| 118 | + _ensure_type_correct(va, entry_type) |
| 119 | + else: |
| 120 | + msg = f"{val!r} is not set" |
| 121 | + elif casting_to in {dict, Dict}: |
| 122 | + key_type, value_type = of_type.__args__[0], of_type.__args__[1] # type: ignore[attr-defined] |
| 123 | + if isinstance(val, dict): |
| 124 | + for va in val: |
| 125 | + _ensure_type_correct(va, key_type) |
| 126 | + for va in val.values(): |
| 127 | + _ensure_type_correct(va, value_type) |
| 128 | + else: |
| 129 | + msg = f"{val!r} is not dictionary" |
| 130 | + elif casting_to == Union: # handle Optional values |
| 131 | + args: list[type[Any]] = of_type.__args__ # type: ignore[attr-defined] |
| 132 | + for arg in args: |
| 133 | + try: |
| 134 | + _ensure_type_correct(val, arg) |
| 135 | + break |
| 136 | + except TypeError: |
| 137 | + pass |
| 138 | + else: |
| 139 | + msg = f"{val!r} is not union of {', '.join(a.__name__ for a in args)}" |
| 140 | + elif casting_to in {Literal, type(Literal)}: |
| 141 | + choice = of_type.__args__ # type: ignore[attr-defined] |
| 142 | + if val not in choice: |
| 143 | + msg = f"{val!r} is not one of literal {','.join(repr(i) for i in choice)}" |
| 144 | + elif not isinstance(val, of_type): |
| 145 | + msg = f"{val!r} is not of type {of_type.__name__!r}" |
| 146 | + if msg: |
| 147 | + raise TypeError(msg) |
| 148 | + return cast(_T, val) # type: ignore[return-value] # logic too complicated for mypy |
| 149 | + |
| 150 | + |
| 151 | +__all__ = [ |
| 152 | + "TomlLoader", |
| 153 | +] |
0 commit comments