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