Skip to content

Commit

Permalink
Update pre-commit hooks with mypy fix (#3454)
Browse files Browse the repository at this point in the history
* Update pre-commit.com hooks

Fixes: #453

* Address mypy failure
  • Loading branch information
ssbarnea authored Dec 3, 2024
1 parent a81c2cb commit 0e33d24
Show file tree
Hide file tree
Showing 30 changed files with 91 additions and 87 deletions.
4 changes: 2 additions & 2 deletions docs/tox_conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
from docutils.nodes import Element, Node, Text, container, fully_normalize_name, literal, paragraph, reference, strong
from docutils.parsers.rst.directives import flag, unchanged, unchanged_required
from docutils.statemachine import StringList, string2lines
from sphinx.domains.std import StandardDomain
from sphinx.locale import __
from sphinx.util.docutils import SphinxDirective
from sphinx.util.logging import getLogger
Expand All @@ -14,6 +13,7 @@
from typing import Final

from docutils.parsers.rst.states import RSTState, RSTStateMachine
from sphinx.domains.std import StandardDomain

LOGGER = getLogger(__name__)

Expand Down Expand Up @@ -53,7 +53,7 @@ def __init__( # noqa: PLR0913
state,
state_machine,
)
self._std_domain: StandardDomain = cast(StandardDomain, self.env.get_domain("std"))
self._std_domain: StandardDomain = cast("StandardDomain", self.env.get_domain("std"))

def run(self) -> list[Node]:
self.env.note_reread() # this document needs to be always updated
Expand Down
2 changes: 1 addition & 1 deletion src/tox/config/cli/parse.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ def _get_base(args: Sequence[str]) -> tuple[int, ToxHandler, Source]:
def _get_all(args: Sequence[str]) -> tuple[Parsed, dict[str, Callable[[State], int]]]:
"""Parse all the options."""
tox_parser = _get_parser()
parsed = cast(Parsed, tox_parser.parse_args(args))
parsed = cast("Parsed", tox_parser.parse_args(args))
handlers = {k: p for k, (_, p) in tox_parser.handlers.items()}
return parsed, handlers

Expand Down
4 changes: 2 additions & 2 deletions src/tox/config/cli/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ def verbosity(self) -> int:
@property
def is_colored(self) -> bool:
""":return: flag indicating if the output is colored or not"""
return cast(bool, self.colored == "yes")
return cast("bool", self.colored == "yes")

exit_and_dump_after: int

Expand Down Expand Up @@ -205,7 +205,7 @@ def __call__(
result = None
else:
try:
result = int(cast(str, values))
result = int(cast("str", values))
if result <= 0:
msg = "must be greater than zero"
raise ValueError(msg) # noqa: TRY301
Expand Down
2 changes: 1 addition & 1 deletion src/tox/config/loader/convert.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ def _to_typing(self, raw: T, of_type: type[V], factory: Factory[V]) -> V: # noq
raise ValueError(msg)
result = raw
if result is not _NO_MAPPING:
return cast(V, result)
return cast("V", result)
msg = f"{raw} cannot cast to {of_type!r}"
raise TypeError(msg)

Expand Down
4 changes: 2 additions & 2 deletions src/tox/config/loader/toml/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def load_raw(self, key: str, conf: Config | None, env_name: str | None) -> TomlT
return self.content[key]

def load_raw_from_root(self, path: str) -> TomlTypes:
current = cast(TomlTypes, self._root_content)
current = cast("TomlTypes", self._root_content)
for key in path.split(self.section.SEP):
if isinstance(current, dict):
current = current[key]
Expand Down Expand Up @@ -98,7 +98,7 @@ def to_path(value: TomlTypes) -> Path:
@staticmethod
def to_command(value: TomlTypes) -> Command | None:
if value:
return Command(args=cast(List[str], value)) # validated during load in _ensure_type_correct
return Command(args=cast("List[str]", value)) # validated during load in _ensure_type_correct
return None

@staticmethod
Expand Down
15 changes: 8 additions & 7 deletions src/tox/config/loader/toml/_replace.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
from tox.config.loader.replacer import MatchRecursionError, ReplaceReference, load_posargs, replace, replace_env
from tox.config.loader.stringify import stringify

from ._api import TomlTypes
from ._validate import validate

if TYPE_CHECKING:
Expand All @@ -16,6 +15,8 @@
from tox.config.sets import ConfigSet
from tox.config.source.toml_pyproject import TomlSection

from ._api import TomlTypes


class Unroll:
def __init__(self, conf: Config | None, loader: TomlLoader, args: ConfigLoadArgs) -> None:
Expand All @@ -39,7 +40,7 @@ def __call__(self, value: TomlTypes, depth: int = 0) -> TomlTypes: # noqa: C901
for val in value: # apply replacement for every entry
got = self(val, depth)
if isinstance(val, dict) and val.get("replace") and val.get("extend"):
res_list.extend(cast(List[Any], got))
res_list.extend(cast("List[Any]", got))
else:
res_list.append(got)
value = res_list
Expand All @@ -49,16 +50,16 @@ def __call__(self, value: TomlTypes, depth: int = 0) -> TomlTypes: # noqa: C901
if replace_type == "posargs" and self.conf is not None:
got_posargs = load_posargs(self.conf, self.args)
return (
[self(v, depth) for v in cast(List[str], value.get("default", []))]
[self(v, depth) for v in cast("List[str]", value.get("default", []))]
if got_posargs is None
else list(got_posargs)
)
if replace_type == "env":
return replace_env(
self.conf,
[
cast(str, validate(value["name"], str)),
cast(str, validate(self(value.get("default", ""), depth), str)),
cast("str", validate(value["name"], str)),
cast("str", validate(self(value.get("default", ""), depth), str)),
],
self.args,
)
Expand All @@ -73,9 +74,9 @@ def __call__(self, value: TomlTypes, depth: int = 0) -> TomlTypes: # noqa: C901

def _replace_ref(self, value: dict[str, TomlTypes], depth: int) -> TomlTypes:
if self.conf is not None and (env := value.get("env")) and (key := value.get("key")):
return cast(TomlTypes, self.conf.get_env(cast(str, env))[cast(str, key)])
return cast("TomlTypes", self.conf.get_env(cast("str", env))[cast("str", key)])
if of := value.get("of"):
validated_of = cast(List[str], validate(of, List[str]))
validated_of = cast("List[str]", validate(of, List[str]))
loaded = self.loader.load_raw_from_root(self.loader.section.SEP.join(validated_of))
return self(loaded, depth)
return value
Expand Down
2 changes: 1 addition & 1 deletion src/tox/config/loader/toml/_validate.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ def validate(val: TomlTypes, of_type: type[T]) -> TypeGuard[T]: # noqa: C901, P
msg = f"{val!r} is not of type {of_type.__name__!r}"
if msg:
raise TypeError(msg)
return cast(T, val) # type: ignore[return-value] # logic too complicated for mypy
return cast("T", val) # type: ignore[return-value] # logic too complicated for mypy


__all__ = [
Expand Down
2 changes: 1 addition & 1 deletion src/tox/config/of_type.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ def __call__(
if self.post_process is not None:
value = self.post_process(value)
self._cache = value
return cast(T, self._cache)
return cast("T", self._cache)

def __repr__(self) -> str:
values = ((k, v) for k, v in vars(self).items() if k not in {"post_process", "_cache"} and v is not None)
Expand Down
8 changes: 4 additions & 4 deletions src/tox/config/sets.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ def add_config( # noqa: PLR0913
keys_ = self._make_keys(keys)
definition = ConfigDynamicDefinition(keys_, desc, of_type, default, post_process, factory)
result = self._add_conf(keys_, definition)
return cast(ConfigDynamicDefinition[V], result)
return cast("ConfigDynamicDefinition[V]", result)

def add_constant(self, keys: str | Sequence[str], desc: str, value: V) -> ConfigConstantDefinition[V]:
"""
Expand All @@ -84,7 +84,7 @@ def add_constant(self, keys: str | Sequence[str], desc: str, value: V) -> Config
keys_ = self._make_keys(keys)
definition = ConfigConstantDefinition(keys_, desc, value)
result = self._add_conf(keys_, definition)
return cast(ConfigConstantDefinition[V], result)
return cast("ConfigConstantDefinition[V]", result)

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

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

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

def _work_dir_post_process(self, folder: Path) -> Path:
return self._conf.work_dir if self._conf.options.work_dir else folder
Expand Down
2 changes: 1 addition & 1 deletion src/tox/config/source/toml_pyproject.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ def transform_section(self, section: Section) -> Section:

def get_loader(self, section: Section, override_map: OverrideMap) -> Loader[Any] | None:
current = self._our_content
sec = cast(TomlSection, section)
sec = cast("TomlSection", section)
for key in sec.keys:
if key in current:
current = current[key]
Expand Down
6 changes: 3 additions & 3 deletions src/tox/execute/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,15 +52,15 @@ def register_conf(cls, env: ToxEnv) -> None:

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

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

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


class ExecuteStatus(ABC):
Expand Down
6 changes: 3 additions & 3 deletions src/tox/provision.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,12 @@
from tox.report import HandledError
from tox.tox_env.errors import Skip
from tox.tox_env.python.pip.req_file import PythonDeps
from tox.tox_env.python.runner import PythonRun

if TYPE_CHECKING:
from argparse import ArgumentParser

from tox.session.state import State
from tox.tox_env.python.runner import PythonRun


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


def run_provision(name: str, state: State) -> int:
tox_env: PythonRun = cast(PythonRun, state.envs[name])
tox_env: PythonRun = cast("PythonRun", state.envs[name])
env_python = tox_env.env_python()
logging.info("will run in a automatically provisioned python environment under %s", env_python)
try:
Expand All @@ -152,4 +152,4 @@ def run_provision(name: str, state: State) -> int:
args: list[str] = [str(env_python), "-m", "tox"]
args.extend(state.args)
outcome = tox_env.execute(cmd=args, stdin=StdinSource.user_only(), show=True, run_id="provision", cwd=Path.cwd())
return cast(int, outcome.exit_code)
return cast("int", outcome.exit_code)
4 changes: 2 additions & 2 deletions src/tox/pytest.py
Original file line number Diff line number Diff line change
Expand Up @@ -291,7 +291,7 @@ def our_setup_state(value: Sequence[str]) -> State:
msg = "exit code not set"
raise RuntimeError(msg)
out, err = self._capfd.readouterr()
return ToxRunOutcome(args, self.path, cast(int, code), out, err, state)
return ToxRunOutcome(args, self.path, cast("int", code), out, err, state)

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


@pytest.fixture(autouse=True)
Expand Down
4 changes: 2 additions & 2 deletions src/tox/session/cmd/depends.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@

from tox.plugin import impl
from tox.session.cmd.run.common import env_run_create_flags, run_order
from tox.tox_env.runner import RunToxEnv

if TYPE_CHECKING:
from tox.config.cli.parser import ToxParser
from tox.session.state import State
from tox.tox_env.runner import RunToxEnv


@impl
Expand All @@ -34,7 +34,7 @@ def _handle(at: int, env: str) -> None:
print(" " * at, end="") # noqa: T201
print(env, end="") # noqa: T201
if env != "ALL":
run_env = cast(RunToxEnv, state.envs[env])
run_env = cast("RunToxEnv", state.envs[env])
packager_list: list[str] = []
try:
for pkg_env in run_env.package_envs:
Expand Down
8 changes: 4 additions & 4 deletions src/tox/session/cmd/legacy.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,20 @@

from tox.config.cli.parser import DEFAULT_VERBOSITY, Parsed, ToxParser
from tox.config.loader.memory import MemoryLoader
from tox.config.set_env import SetEnv
from tox.plugin import impl
from tox.session.cmd.run.common import env_run_create_flags
from tox.session.cmd.run.parallel import OFF_VALUE, parallel_flags, run_parallel
from tox.session.cmd.run.sequential import run_sequential
from tox.session.env_select import CliEnv, EnvSelector, register_env_select_flags
from tox.tox_env.python.pip.req_file import PythonDeps

from .devenv import devenv
from .list_env import list_env
from .show_config import show_config

if TYPE_CHECKING:
from tox.config.set_env import SetEnv
from tox.session.state import State
from tox.tox_env.python.pip.req_file import PythonDeps


@impl
Expand Down Expand Up @@ -131,10 +131,10 @@ def _handle_legacy_only_flags(option: Parsed, envs: EnvSelector) -> None: # noq
if override:
env_conf.loaders.insert(0, MemoryLoader(**override))
if set_env:
cast(SetEnv, env_conf["set_env"]).update(set_env, override=True)
cast("SetEnv", env_conf["set_env"]).update(set_env, override=True)
if forced:
to_force = forced.copy()
deps = cast(PythonDeps, env_conf["deps"])
deps = cast("PythonDeps", env_conf["deps"])
as_root_args = deps.as_root_args
for at, entry in enumerate(as_root_args):
try:
Expand Down
16 changes: 8 additions & 8 deletions src/tox/session/cmd/run/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,17 @@

from colorama import Fore

from tox.config.types import EnvList
from tox.execute import Outcome
from tox.journal import write_journal
from tox.session.cmd.run.single import ToxEnvRunResult, run_one
from tox.tox_env.runner import RunToxEnv
from tox.util.graph import stable_topological_sort
from tox.util.spinner import MISS_DURATION, Spinner

if TYPE_CHECKING:
from tox.config.types import EnvList
from tox.session.state import State
from tox.tox_env.api import ToxEnv
from tox.tox_env.runner import RunToxEnv


class SkipMissingInterpreterAction(Action):
Expand All @@ -51,7 +51,7 @@ def __call__(
) -> None:
if not values:
raise ArgumentError(self, "cannot be empty")
path = Path(cast(str, values)).absolute()
path = Path(cast("str", values)).absolute()
if not path.exists():
raise ArgumentError(self, f"{path} does not exist")
if not path.is_file():
Expand Down Expand Up @@ -167,7 +167,7 @@ def execute(state: State, max_workers: int | None, has_spinner: bool, live: bool
state.envs.ensure_only_run_env_is_active()
to_run_list: list[str] = list(state.envs.iter())
for name in to_run_list:
cast(RunToxEnv, state.envs[name]).mark_active()
cast("RunToxEnv", state.envs[name]).mark_active()
previous, has_previous = None, False
try:
spinner = ToxSpinner(has_spinner, state, len(to_run_list))
Expand Down Expand Up @@ -260,7 +260,7 @@ def _run(tox_env: RunToxEnv) -> ToxEnvRunResult:
env_list: list[str] = []
while True:
for env in env_list: # queue all available
tox_env_to_run = cast(RunToxEnv, state.envs[env])
tox_env_to_run = cast("RunToxEnv", state.envs[env])
if interrupt.is_set(): # queue the rest as failed upfront
tox_env_to_run.teardown()
future: Future[ToxEnvRunResult] = Future()
Expand Down Expand Up @@ -322,7 +322,7 @@ def _handle_one_run_done(
) -> None:
success = result.code == Outcome.OK
spinner.update_spinner(result, success)
tox_env = cast(RunToxEnv, state.envs[result.name])
tox_env = cast("RunToxEnv", state.envs[result.name])
if tox_env.journal: # add overall journal entry
tox_env.journal["result"] = {
"success": success,
Expand Down Expand Up @@ -362,8 +362,8 @@ def run_order(state: State, to_run: list[str]) -> tuple[list[str], dict[str, set
to_run_set = set(to_run)
todo: dict[str, set[str]] = {}
for env in to_run:
run_env = cast(RunToxEnv, state.envs[env])
depends = set(cast(EnvList, run_env.conf["depends"]).envs)
run_env = cast("RunToxEnv", state.envs[env])
depends = set(cast("EnvList", run_env.conf["depends"]).envs)
todo[env] = to_run_set & depends
order = stable_topological_sort(todo)
return order, todo
Loading

0 comments on commit 0e33d24

Please sign in to comment.