Skip to content

Commit 0e33d24

Browse files
authored
Update pre-commit hooks with mypy fix (#3454)
* Update pre-commit.com hooks Fixes: #453 * Address mypy failure
1 parent a81c2cb commit 0e33d24

30 files changed

+91
-87
lines changed

docs/tox_conf.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
from docutils.nodes import Element, Node, Text, container, fully_normalize_name, literal, paragraph, reference, strong
66
from docutils.parsers.rst.directives import flag, unchanged, unchanged_required
77
from docutils.statemachine import StringList, string2lines
8-
from sphinx.domains.std import StandardDomain
98
from sphinx.locale import __
109
from sphinx.util.docutils import SphinxDirective
1110
from sphinx.util.logging import getLogger
@@ -14,6 +13,7 @@
1413
from typing import Final
1514

1615
from docutils.parsers.rst.states import RSTState, RSTStateMachine
16+
from sphinx.domains.std import StandardDomain
1717

1818
LOGGER = getLogger(__name__)
1919

@@ -53,7 +53,7 @@ def __init__( # noqa: PLR0913
5353
state,
5454
state_machine,
5555
)
56-
self._std_domain: StandardDomain = cast(StandardDomain, self.env.get_domain("std"))
56+
self._std_domain: StandardDomain = cast("StandardDomain", self.env.get_domain("std"))
5757

5858
def run(self) -> list[Node]:
5959
self.env.note_reread() # this document needs to be always updated

src/tox/config/cli/parse.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ def _get_base(args: Sequence[str]) -> tuple[int, ToxHandler, Source]:
6767
def _get_all(args: Sequence[str]) -> tuple[Parsed, dict[str, Callable[[State], int]]]:
6868
"""Parse all the options."""
6969
tox_parser = _get_parser()
70-
parsed = cast(Parsed, tox_parser.parse_args(args))
70+
parsed = cast("Parsed", tox_parser.parse_args(args))
7171
handlers = {k: p for k, (_, p) in tox_parser.handlers.items()}
7272
return parsed, handlers
7373

src/tox/config/cli/parser.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,7 @@ def verbosity(self) -> int:
123123
@property
124124
def is_colored(self) -> bool:
125125
""":return: flag indicating if the output is colored or not"""
126-
return cast(bool, self.colored == "yes")
126+
return cast("bool", self.colored == "yes")
127127

128128
exit_and_dump_after: int
129129

@@ -205,7 +205,7 @@ def __call__(
205205
result = None
206206
else:
207207
try:
208-
result = int(cast(str, values))
208+
result = int(cast("str", values))
209209
if result <= 0:
210210
msg = "must be greater than zero"
211211
raise ValueError(msg) # noqa: TRY301

src/tox/config/loader/convert.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ def _to_typing(self, raw: T, of_type: type[V], factory: Factory[V]) -> V: # noq
8787
raise ValueError(msg)
8888
result = raw
8989
if result is not _NO_MAPPING:
90-
return cast(V, result)
90+
return cast("V", result)
9191
msg = f"{raw} cannot cast to {of_type!r}"
9292
raise TypeError(msg)
9393

src/tox/config/loader/toml/__init__.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ def load_raw(self, key: str, conf: Config | None, env_name: str | None) -> TomlT
4343
return self.content[key]
4444

4545
def load_raw_from_root(self, path: str) -> TomlTypes:
46-
current = cast(TomlTypes, self._root_content)
46+
current = cast("TomlTypes", self._root_content)
4747
for key in path.split(self.section.SEP):
4848
if isinstance(current, dict):
4949
current = current[key]
@@ -98,7 +98,7 @@ def to_path(value: TomlTypes) -> Path:
9898
@staticmethod
9999
def to_command(value: TomlTypes) -> Command | None:
100100
if value:
101-
return Command(args=cast(List[str], value)) # validated during load in _ensure_type_correct
101+
return Command(args=cast("List[str]", value)) # validated during load in _ensure_type_correct
102102
return None
103103

104104
@staticmethod

src/tox/config/loader/toml/_replace.py

+8-7
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
from tox.config.loader.replacer import MatchRecursionError, ReplaceReference, load_posargs, replace, replace_env
77
from tox.config.loader.stringify import stringify
88

9-
from ._api import TomlTypes
109
from ._validate import validate
1110

1211
if TYPE_CHECKING:
@@ -16,6 +15,8 @@
1615
from tox.config.sets import ConfigSet
1716
from tox.config.source.toml_pyproject import TomlSection
1817

18+
from ._api import TomlTypes
19+
1920

2021
class Unroll:
2122
def __init__(self, conf: Config | None, loader: TomlLoader, args: ConfigLoadArgs) -> None:
@@ -39,7 +40,7 @@ def __call__(self, value: TomlTypes, depth: int = 0) -> TomlTypes: # noqa: C901
3940
for val in value: # apply replacement for every entry
4041
got = self(val, depth)
4142
if isinstance(val, dict) and val.get("replace") and val.get("extend"):
42-
res_list.extend(cast(List[Any], got))
43+
res_list.extend(cast("List[Any]", got))
4344
else:
4445
res_list.append(got)
4546
value = res_list
@@ -49,16 +50,16 @@ def __call__(self, value: TomlTypes, depth: int = 0) -> TomlTypes: # noqa: C901
4950
if replace_type == "posargs" and self.conf is not None:
5051
got_posargs = load_posargs(self.conf, self.args)
5152
return (
52-
[self(v, depth) for v in cast(List[str], value.get("default", []))]
53+
[self(v, depth) for v in cast("List[str]", value.get("default", []))]
5354
if got_posargs is None
5455
else list(got_posargs)
5556
)
5657
if replace_type == "env":
5758
return replace_env(
5859
self.conf,
5960
[
60-
cast(str, validate(value["name"], str)),
61-
cast(str, validate(self(value.get("default", ""), depth), str)),
61+
cast("str", validate(value["name"], str)),
62+
cast("str", validate(self(value.get("default", ""), depth), str)),
6263
],
6364
self.args,
6465
)
@@ -73,9 +74,9 @@ def __call__(self, value: TomlTypes, depth: int = 0) -> TomlTypes: # noqa: C901
7374

7475
def _replace_ref(self, value: dict[str, TomlTypes], depth: int) -> TomlTypes:
7576
if self.conf is not None and (env := value.get("env")) and (key := value.get("key")):
76-
return cast(TomlTypes, self.conf.get_env(cast(str, env))[cast(str, key)])
77+
return cast("TomlTypes", self.conf.get_env(cast("str", env))[cast("str", key)])
7778
if of := value.get("of"):
78-
validated_of = cast(List[str], validate(of, List[str]))
79+
validated_of = cast("List[str]", validate(of, List[str]))
7980
loaded = self.loader.load_raw_from_root(self.loader.section.SEP.join(validated_of))
8081
return self(loaded, depth)
8182
return value

src/tox/config/loader/toml/_validate.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ def validate(val: TomlTypes, of_type: type[T]) -> TypeGuard[T]: # noqa: C901, P
7676
msg = f"{val!r} is not of type {of_type.__name__!r}"
7777
if msg:
7878
raise TypeError(msg)
79-
return cast(T, val) # type: ignore[return-value] # logic too complicated for mypy
79+
return cast("T", val) # type: ignore[return-value] # logic too complicated for mypy
8080

8181

8282
__all__ = [

src/tox/config/of_type.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,7 @@ def __call__(
118118
if self.post_process is not None:
119119
value = self.post_process(value)
120120
self._cache = value
121-
return cast(T, self._cache)
121+
return cast("T", self._cache)
122122

123123
def __repr__(self) -> str:
124124
values = ((k, v) for k, v in vars(self).items() if k not in {"post_process", "_cache"} and v is not None)

src/tox/config/sets.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ def add_config( # noqa: PLR0913
6767
keys_ = self._make_keys(keys)
6868
definition = ConfigDynamicDefinition(keys_, desc, of_type, default, post_process, factory)
6969
result = self._add_conf(keys_, definition)
70-
return cast(ConfigDynamicDefinition[V], result)
70+
return cast("ConfigDynamicDefinition[V]", result)
7171

7272
def add_constant(self, keys: str | Sequence[str], desc: str, value: V) -> ConfigConstantDefinition[V]:
7373
"""
@@ -84,7 +84,7 @@ def add_constant(self, keys: str | Sequence[str], desc: str, value: V) -> Config
8484
keys_ = self._make_keys(keys)
8585
definition = ConfigConstantDefinition(keys_, desc, value)
8686
result = self._add_conf(keys_, definition)
87-
return cast(ConfigConstantDefinition[V], result)
87+
return cast("ConfigConstantDefinition[V]", result)
8888

8989
@staticmethod
9090
def _make_keys(keys: str | Sequence[str]) -> Sequence[str]:
@@ -182,10 +182,10 @@ def __init__(self, conf: Config, section: Section, root: Path, src_path: Path) -
182182
self.add_config(keys=["env_list", "envlist"], of_type=EnvList, default=EnvList([]), desc=desc)
183183

184184
def _default_work_dir(self, conf: Config, env_name: str | None) -> Path: # noqa: ARG002
185-
return cast(Path, self["tox_root"] / ".tox")
185+
return cast("Path", self["tox_root"] / ".tox")
186186

187187
def _default_temp_dir(self, conf: Config, env_name: str | None) -> Path: # noqa: ARG002
188-
return cast(Path, self["work_dir"] / ".tmp")
188+
return cast("Path", self["work_dir"] / ".tmp")
189189

190190
def _work_dir_post_process(self, folder: Path) -> Path:
191191
return self._conf.work_dir if self._conf.options.work_dir else folder

src/tox/config/source/toml_pyproject.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ def transform_section(self, section: Section) -> Section:
9292

9393
def get_loader(self, section: Section, override_map: OverrideMap) -> Loader[Any] | None:
9494
current = self._our_content
95-
sec = cast(TomlSection, section)
95+
sec = cast("TomlSection", section)
9696
for key in sec.keys:
9797
if key in current:
9898
current = current[key]

src/tox/execute/api.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -52,15 +52,15 @@ def register_conf(cls, env: ToxEnv) -> None:
5252

5353
@property
5454
def suicide_timeout(self) -> float:
55-
return cast(float, self._env.conf["suicide_timeout"])
55+
return cast("float", self._env.conf["suicide_timeout"])
5656

5757
@property
5858
def interrupt_timeout(self) -> float:
59-
return cast(float, self._env.conf["interrupt_timeout"])
59+
return cast("float", self._env.conf["interrupt_timeout"])
6060

6161
@property
6262
def terminate_timeout(self) -> float:
63-
return cast(float, self._env.conf["terminate_timeout"])
63+
return cast("float", self._env.conf["terminate_timeout"])
6464

6565

6666
class ExecuteStatus(ABC):

src/tox/provision.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -20,12 +20,12 @@
2020
from tox.report import HandledError
2121
from tox.tox_env.errors import Skip
2222
from tox.tox_env.python.pip.req_file import PythonDeps
23-
from tox.tox_env.python.runner import PythonRun
2423

2524
if TYPE_CHECKING:
2625
from argparse import ArgumentParser
2726

2827
from tox.session.state import State
28+
from tox.tox_env.python.runner import PythonRun
2929

3030

3131
@impl
@@ -141,7 +141,7 @@ def _get_missing(requires: list[Requirement]) -> list[tuple[Requirement, str | N
141141

142142

143143
def run_provision(name: str, state: State) -> int:
144-
tox_env: PythonRun = cast(PythonRun, state.envs[name])
144+
tox_env: PythonRun = cast("PythonRun", state.envs[name])
145145
env_python = tox_env.env_python()
146146
logging.info("will run in a automatically provisioned python environment under %s", env_python)
147147
try:
@@ -152,4 +152,4 @@ def run_provision(name: str, state: State) -> int:
152152
args: list[str] = [str(env_python), "-m", "tox"]
153153
args.extend(state.args)
154154
outcome = tox_env.execute(cmd=args, stdin=StdinSource.user_only(), show=True, run_id="provision", cwd=Path.cwd())
155-
return cast(int, outcome.exit_code)
155+
return cast("int", outcome.exit_code)

src/tox/pytest.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -291,7 +291,7 @@ def our_setup_state(value: Sequence[str]) -> State:
291291
msg = "exit code not set"
292292
raise RuntimeError(msg)
293293
out, err = self._capfd.readouterr()
294-
return ToxRunOutcome(args, self.path, cast(int, code), out, err, state)
294+
return ToxRunOutcome(args, self.path, cast("int", code), out, err, state)
295295

296296
def __repr__(self) -> str:
297297
return f"{type(self).__name__}(path={self.path}) at {id(self)}"
@@ -488,7 +488,7 @@ def pypi_server(tmp_path_factory: pytest.TempPathFactory) -> Iterator[IndexServe
488488
def _invalid_index_fake_port() -> int:
489489
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as socket_handler:
490490
socket_handler.bind(("", 0))
491-
return cast(int, socket_handler.getsockname()[1])
491+
return cast("int", socket_handler.getsockname()[1])
492492

493493

494494
@pytest.fixture(autouse=True)

src/tox/session/cmd/depends.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,11 @@
44

55
from tox.plugin import impl
66
from tox.session.cmd.run.common import env_run_create_flags, run_order
7-
from tox.tox_env.runner import RunToxEnv
87

98
if TYPE_CHECKING:
109
from tox.config.cli.parser import ToxParser
1110
from tox.session.state import State
11+
from tox.tox_env.runner import RunToxEnv
1212

1313

1414
@impl
@@ -34,7 +34,7 @@ def _handle(at: int, env: str) -> None:
3434
print(" " * at, end="") # noqa: T201
3535
print(env, end="") # noqa: T201
3636
if env != "ALL":
37-
run_env = cast(RunToxEnv, state.envs[env])
37+
run_env = cast("RunToxEnv", state.envs[env])
3838
packager_list: list[str] = []
3939
try:
4040
for pkg_env in run_env.package_envs:

src/tox/session/cmd/legacy.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -7,20 +7,20 @@
77

88
from tox.config.cli.parser import DEFAULT_VERBOSITY, Parsed, ToxParser
99
from tox.config.loader.memory import MemoryLoader
10-
from tox.config.set_env import SetEnv
1110
from tox.plugin import impl
1211
from tox.session.cmd.run.common import env_run_create_flags
1312
from tox.session.cmd.run.parallel import OFF_VALUE, parallel_flags, run_parallel
1413
from tox.session.cmd.run.sequential import run_sequential
1514
from tox.session.env_select import CliEnv, EnvSelector, register_env_select_flags
16-
from tox.tox_env.python.pip.req_file import PythonDeps
1715

1816
from .devenv import devenv
1917
from .list_env import list_env
2018
from .show_config import show_config
2119

2220
if TYPE_CHECKING:
21+
from tox.config.set_env import SetEnv
2322
from tox.session.state import State
23+
from tox.tox_env.python.pip.req_file import PythonDeps
2424

2525

2626
@impl
@@ -131,10 +131,10 @@ def _handle_legacy_only_flags(option: Parsed, envs: EnvSelector) -> None: # noq
131131
if override:
132132
env_conf.loaders.insert(0, MemoryLoader(**override))
133133
if set_env:
134-
cast(SetEnv, env_conf["set_env"]).update(set_env, override=True)
134+
cast("SetEnv", env_conf["set_env"]).update(set_env, override=True)
135135
if forced:
136136
to_force = forced.copy()
137-
deps = cast(PythonDeps, env_conf["deps"])
137+
deps = cast("PythonDeps", env_conf["deps"])
138138
as_root_args = deps.as_root_args
139139
for at, entry in enumerate(as_root_args):
140140
try:

src/tox/session/cmd/run/common.py

+8-8
Original file line numberDiff line numberDiff line change
@@ -14,17 +14,17 @@
1414

1515
from colorama import Fore
1616

17-
from tox.config.types import EnvList
1817
from tox.execute import Outcome
1918
from tox.journal import write_journal
2019
from tox.session.cmd.run.single import ToxEnvRunResult, run_one
21-
from tox.tox_env.runner import RunToxEnv
2220
from tox.util.graph import stable_topological_sort
2321
from tox.util.spinner import MISS_DURATION, Spinner
2422

2523
if TYPE_CHECKING:
24+
from tox.config.types import EnvList
2625
from tox.session.state import State
2726
from tox.tox_env.api import ToxEnv
27+
from tox.tox_env.runner import RunToxEnv
2828

2929

3030
class SkipMissingInterpreterAction(Action):
@@ -51,7 +51,7 @@ def __call__(
5151
) -> None:
5252
if not values:
5353
raise ArgumentError(self, "cannot be empty")
54-
path = Path(cast(str, values)).absolute()
54+
path = Path(cast("str", values)).absolute()
5555
if not path.exists():
5656
raise ArgumentError(self, f"{path} does not exist")
5757
if not path.is_file():
@@ -167,7 +167,7 @@ def execute(state: State, max_workers: int | None, has_spinner: bool, live: bool
167167
state.envs.ensure_only_run_env_is_active()
168168
to_run_list: list[str] = list(state.envs.iter())
169169
for name in to_run_list:
170-
cast(RunToxEnv, state.envs[name]).mark_active()
170+
cast("RunToxEnv", state.envs[name]).mark_active()
171171
previous, has_previous = None, False
172172
try:
173173
spinner = ToxSpinner(has_spinner, state, len(to_run_list))
@@ -260,7 +260,7 @@ def _run(tox_env: RunToxEnv) -> ToxEnvRunResult:
260260
env_list: list[str] = []
261261
while True:
262262
for env in env_list: # queue all available
263-
tox_env_to_run = cast(RunToxEnv, state.envs[env])
263+
tox_env_to_run = cast("RunToxEnv", state.envs[env])
264264
if interrupt.is_set(): # queue the rest as failed upfront
265265
tox_env_to_run.teardown()
266266
future: Future[ToxEnvRunResult] = Future()
@@ -322,7 +322,7 @@ def _handle_one_run_done(
322322
) -> None:
323323
success = result.code == Outcome.OK
324324
spinner.update_spinner(result, success)
325-
tox_env = cast(RunToxEnv, state.envs[result.name])
325+
tox_env = cast("RunToxEnv", state.envs[result.name])
326326
if tox_env.journal: # add overall journal entry
327327
tox_env.journal["result"] = {
328328
"success": success,
@@ -362,8 +362,8 @@ def run_order(state: State, to_run: list[str]) -> tuple[list[str], dict[str, set
362362
to_run_set = set(to_run)
363363
todo: dict[str, set[str]] = {}
364364
for env in to_run:
365-
run_env = cast(RunToxEnv, state.envs[env])
366-
depends = set(cast(EnvList, run_env.conf["depends"]).envs)
365+
run_env = cast("RunToxEnv", state.envs[env])
366+
depends = set(cast("EnvList", run_env.conf["depends"]).envs)
367367
todo[env] = to_run_set & depends
368368
order = stable_topological_sort(todo)
369369
return order, todo

0 commit comments

Comments
 (0)