Skip to content

Commit

Permalink
Fix remaining errors
Browse files Browse the repository at this point in the history
Signed-off-by: Bernát Gábor <bgabor8@bloomberg.net>
  • Loading branch information
gaborbernat committed Jun 14, 2023
1 parent 7fe5204 commit b580e46
Show file tree
Hide file tree
Showing 50 changed files with 237 additions and 230 deletions.
17 changes: 17 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,23 @@ repos:
hooks:
- id: prettier
args: ["--print-width=120", "--prose-wrap=always"]
- repo: https://github.com/asottile/blacken-docs
rev: 1.13.0
hooks:
- id: blacken-docs
additional_dependencies: [black==23.3]
- repo: https://github.com/pre-commit/pygrep-hooks
rev: v1.10.0
hooks:
- id: rst-backticks
- repo: local
hooks:
- id: changelogs-rst
name: changelog filenames
language: fail
entry: "changelog files must be named ####.(feature|bugfix|doc|removal|misc).rst"
exclude: ^docs/changelog/(\d+\.(feature|bugfix|doc|removal|misc).rst|template.jinja2)
files: ^docs/changelog/
- repo: meta
hooks:
- id: check-hooks-apply
Expand Down
8 changes: 4 additions & 4 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@

company, name = "tox-dev", "tox"
release, version = __version__, ".".join(__version__.split(".")[:2])
copyright = f"{company}"
copyright = f"{company}" # noqa: A001
master_doc, source_suffix = "index", ".rst"

html_theme = "furo"
Expand Down Expand Up @@ -97,7 +97,7 @@ def setup(app: Sphinx) -> None:
root, exe = here.parent, Path(sys.executable)
towncrier = exe.with_name(f"towncrier{exe.suffix}")
cmd = [str(towncrier), "build", "--draft", "--version", "NEXT"]
new = check_output(cmd, cwd=root, text=True, stderr=subprocess.DEVNULL)
new = check_output(cmd, cwd=root, text=True, stderr=subprocess.DEVNULL) # noqa: S603
(root / "docs" / "_draft.rst").write_text("" if "No significant changes" in new else new)

class PatchedPythonDomain(PythonDomain):
Expand All @@ -106,7 +106,7 @@ def resolve_xref( # noqa: PLR0913
env: BuildEnvironment,
fromdocname: str,
builder: Builder,
type: str,
type: str, # noqa: A002
target: str,
node: pending_xref,
contnode: Element,
Expand All @@ -129,7 +129,7 @@ def resolve_xref( # noqa: PLR0913
tox_cfg = SourceFileLoader("tox_conf", str(here / "tox_conf.py")).load_module().ToxConfig
app.add_directive(tox_cfg.name, tox_cfg)

def check_uri(self, refnode: reference) -> None:
def check_uri(self: ExternalLinksChecker, refnode: reference) -> None: #
if refnode.document.attributes["source"].endswith("index.rst"):
return None # do not use for the index file
return prev_check(self, refnode)
Expand Down
3 changes: 3 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ optional-dependencies.docs = [
optional-dependencies.testing = [
"build[virtualenv]>=0.10",
"covdefaults>=2.3",
"detect-test-pollution>=1.1.1",
"devpi-process>=0.3",
"diff-cover>=7.6",
"distlib>=0.3.6",
Expand All @@ -84,6 +85,7 @@ optional-dependencies.testing = [
"pytest>=7.3.2",
"pytest-cov>=4.1",
"pytest-mock>=3.10",
"pytest-timeout>=2.1",
"pytest-xdist>=3.3.1",
"re-assert>=1.1",
'time-machine>=2.9; implementation_name != "pypy"',
Expand All @@ -106,6 +108,7 @@ version.source = "vcs"
line-length = 120

[tool.pytest.ini_options]
timeout = 10
testpaths = ["tests"]
addopts = "--tb=auto -ra --showlocals --no-success-flaky-report"

Expand Down
4 changes: 2 additions & 2 deletions src/tox/config/cli/env_var.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,7 @@ def get_env_var(key: str, of_type: type[Any]) -> tuple[Any, str] | None:
if environ_key in os.environ:
value = os.environ[environ_key]
try:
source = f"env var {environ_key}"
result = CONVERT.to(raw=value, of_type=of_type, factory=None)
return result, source
except Exception as exception: # noqa: BLE001
logging.warning(
"env var %s=%r cannot be transformed to %r because %r",
Expand All @@ -34,6 +32,8 @@ def get_env_var(key: str, of_type: type[Any]) -> tuple[Any, str] | None:
of_type,
exception,
)
else:
return result, f"env var {environ_key}"
return None


Expand Down
2 changes: 1 addition & 1 deletion src/tox/config/cli/ini.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ def __init__(self) -> None:
if self.has_tox_section:
self.ini = IniLoader(CORE, parser, overrides=[], core_section=CORE)
except Exception as exception: # noqa: BLE001
logging.error("failed to read config file %s because %r", config_file, exception)
logging.error("failed to read config file %s because %r", config_file, exception) # noqa: TRY400
self.has_config_file = None

def get(self, key: str, of_type: type[Any]) -> Any:
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 @@ -45,7 +45,7 @@ def _get_base(args: Sequence[str]) -> tuple[int, ToxHandler, Source]:
tox_parser = ToxParser.base()
parsed = Parsed()
try:
with open(os.devnull, "w") as file_handler, redirect_stderr(file_handler):
with Path(os.devnull).open("w") as file_handler, redirect_stderr(file_handler):
tox_parser.parse_known_args(args, namespace=parsed)
except SystemExit:
... # ignore parse errors, such as -va raises ignored explicit argument 'a'
Expand Down
8 changes: 4 additions & 4 deletions src/tox/config/cli/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ def fix_default(self, action: Action) -> None:
for values in action.choices.values():
if not isinstance(values, ToxParser): # pragma: no cover
msg = "detected sub-parser added without using our own add command"
raise RuntimeError(msg)
raise RuntimeError(msg) # noqa: TRY004
values.fix_defaults()

@staticmethod
Expand All @@ -64,7 +64,7 @@ def get_type(action: Action) -> type[Any]:
loc = locals()
loc["Literal"] = Literal
as_literal = f"Literal[{', '.join(repr(i) for i in action.choices)}]"
of_type = eval(as_literal, globals(), loc)
of_type = eval(as_literal, globals(), loc) # noqa: PGH001
elif action.default is not None:
of_type = type(action.default)
elif isinstance(action, argparse._StoreConstAction) and action.const is not None: # noqa: SLF001
Expand Down Expand Up @@ -265,7 +265,7 @@ def parse_known_args( # type: ignore[override]
def add_verbosity_flags(parser: ArgumentParser) -> None:
from tox.report import LEVELS

level_map = "|".join(f"{c}={logging.getLevelName(l)}" for c, l in sorted(LEVELS.items()))
level_map = "|".join(f"{c}={logging.getLevelName(level)}" for c, level in sorted(LEVELS.items()))
verbosity_group = parser.add_argument_group("verbosity")
verbosity_group.description = (
f"every -v increases, every -q decreases verbosity level, "
Expand All @@ -285,7 +285,7 @@ def add_verbosity_flags(parser: ArgumentParser) -> None:

def add_color_flags(parser: ArgumentParser) -> None:
converter = StrConvert()
if os.environ.get("NO_COLOR", "") != "":
if os.environ.get("NO_COLOR", ""):
color = "no"
elif converter.to_bool(os.environ.get("FORCE_COLOR", "")):
color = "yes"
Expand Down
5 changes: 2 additions & 3 deletions src/tox/config/loader/ini/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,12 +50,11 @@ def process_raw(conf: Config | None, env_name: str | None, value: str) -> str:
part = _COMMENTS.sub("", line)
elements.append(part.replace("\\#", "#"))
strip_comments = "\n".join(elements)
if conf is None: # conf is None when we're loading the global tox configuration file for the CLI
if conf is None: # noqa: SIM108 # conf is None when we're loading the global tox configuration file for the CLI
factor_filtered = strip_comments # we don't support factor and replace functionality there
else:
factor_filtered = filter_for_env(strip_comments, env_name) # select matching factors
collapsed = factor_filtered.replace("\r", "").replace("\\\n", "") # collapse explicit new-line escape
return collapsed
return factor_filtered.replace("\r", "").replace("\\\n", "") # collapse explicit new-line escape

def build( # noqa: PLR0913
self,
Expand Down
3 changes: 1 addition & 2 deletions src/tox/config/loader/ini/factor.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,7 @@ def filter_for_env(value: str, name: str | None) -> str:
if all((a_name in current) ^ negate for a_name, negate in group):
overall.append(content)
break # if any match we use it, and then bail
result = "\n".join(overall)
return result
return "\n".join(overall)


def find_envs(value: str) -> Iterator[str]:
Expand Down
24 changes: 13 additions & 11 deletions src/tox/config/loader/ini/replace.py
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ def _replace_match(self, value: MatchExpression) -> str:
of_type, *args = flattened_args
if of_type == "/":
replace_value: str | None = os.sep
elif of_type == "" and args == [""]:
elif not of_type and args == [""]:
replace_value = os.pathsep
elif of_type == "env":
replace_value = replace_env(self.conf, args, conf_args)
Expand Down Expand Up @@ -232,7 +232,12 @@ def _replace_ref(env: str | None) -> Pattern[str]:
)


def replace_reference(conf: Config, loader: IniLoader, value: str, conf_args: ConfigLoadArgs) -> str | None:
def replace_reference( # noqa: PLR0912, C901
conf: Config,
loader: IniLoader,
value: str,
conf_args: ConfigLoadArgs,
) -> str | None:
# a return value of None indicates could not replace
pattern = _replace_ref(loader.section.prefix or loader.section.name)
match = pattern.match(value)
Expand All @@ -250,11 +255,12 @@ def replace_reference(conf: Config, loader: IniLoader, value: str, conf_args: Co
if isinstance(src, SectionProxy):
return loader.process_raw(conf, conf_args.env_name, src[key])
value = src.load(key, conf_args.chain)
except KeyError as exc: # if fails, keep trying maybe another source can satisfy
exception = exc
else:
as_str, _ = stringify(value)
as_str = as_str.replace("#", r"\#") # escape comment characters as these will be stripped
return as_str
except KeyError as exc: # if fails, keep trying maybe another source can satisfy
exception = exc
except Exception as exc: # noqa: BLE001
exception = exc
if exception is not None:
Expand Down Expand Up @@ -306,11 +312,8 @@ def replace_pos_args(conf: Config, args: list[str], conf_args: ConfigLoadArgs) -
except KeyError:
pass
pos_args = conf.pos_args(to_path)
if pos_args is None:
replace_value = ARG_DELIMITER.join(args) # if we use the defaults join back remaining args
else:
replace_value = shell_cmd(pos_args)
return replace_value
# if we use the defaults join back remaining args else take shell cmd
return ARG_DELIMITER.join(args) if pos_args is None else shell_cmd(pos_args)


def replace_env(conf: Config, args: list[str], conf_args: ConfigLoadArgs) -> str:
Expand Down Expand Up @@ -339,8 +342,7 @@ def replace_env(conf: Config, args: list[str], conf_args: ConfigLoadArgs) -> str


def replace_tty(args: list[str]) -> str:
result = (args[0] if len(args) > 0 else "") if sys.stdout.isatty() else args[1] if len(args) > 1 else ""
return result
return (args[0] if len(args) > 0 else "") if sys.stdout.isatty() else args[1] if len(args) > 1 else ""


__all__ = (
Expand Down
2 changes: 1 addition & 1 deletion src/tox/config/loader/section.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ def __repr__(self) -> str:

def __eq__(self, other: Any) -> bool:
return isinstance(other, self.__class__) and (self._prefix, self._name) == (
other._prefix,
other._prefix, # noqa: SLF001
other.name,
)

Expand Down
12 changes: 5 additions & 7 deletions src/tox/config/loader/str_convert.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ def to_command(value: str) -> Command:
for arg in splitter:
if is_win and len(arg) > 1 and arg[0] == arg[-1] and arg.startswith(("'", '"')): # pragma: win32 cover
# on Windows quoted arguments will remain quoted, strip it
arg = arg[1:-1]
arg = arg[1:-1] # noqa: PLW2901
args.append(arg)
pos = splitter.instream.tell()
except ValueError:
Expand Down Expand Up @@ -120,13 +120,11 @@ def to_bool(value: str) -> bool:
norm = str(value).strip().lower()
if norm in StrConvert.TRUTHFUL_VALUES:
return True
elif norm in StrConvert.FALSE_VALUES:
if norm in StrConvert.FALSE_VALUES:
return False
else:
msg = f"value {value!r} cannot be transformed to bool, valid: {', '.join(StrConvert.VALID_BOOL)}"
raise TypeError(
msg,
)

msg = f"value {value!r} cannot be transformed to bool, valid: {', '.join(StrConvert.VALID_BOOL)}"
raise TypeError(msg)


__all__ = ("StrConvert",)
12 changes: 7 additions & 5 deletions src/tox/config/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,12 +51,15 @@ def pos_args(self, to_path: Path | None) -> tuple[str, ...] | None:
"""
if self._pos_args is not None and to_path is not None and Path.cwd() != to_path:
args = []
to_path_str = os.path.abspath(str(to_path)) # we use os.path to unroll .. in path without resolve
# we use os.path to unroll .. in path without resolve
to_path_str = os.path.abspath(str(to_path)) # noqa: PTH100
for arg in self._pos_args:
path_arg = Path(arg)
if path_arg.exists() and not path_arg.is_absolute():
path_arg_str = os.path.abspath(str(path_arg)) # we use os.path to unroll .. in path without resolve
relative = os.path.relpath(path_arg_str, to_path_str) # we use os.path to not fail when not within
# we use os.path to unroll .. in path without resolve
path_arg_str = os.path.abspath(str(path_arg)) # noqa: PTH100
# we use os.path to not fail when not within
relative = os.path.relpath(path_arg_str, to_path_str)
args.append(relative)
else:
args.append(arg)
Expand Down Expand Up @@ -157,14 +160,13 @@ def get_env(
:return: the tox environments config
"""
section, base_test, base_pkg = self._src.get_tox_env_section(item)
conf_set = self.get_section_config(
return self.get_section_config(
section,
base=base_pkg if package else base_test,
of_type=EnvConfigSet,
for_env=item,
loaders=loaders,
)
return conf_set

def clear_env(self, name: str) -> None:
section, _, __ = self._src.get_tox_env_section(name)
Expand Down
5 changes: 2 additions & 3 deletions src/tox/config/of_type.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
"""Group together configuration values that belong together (such as base tox configuration, tox environment configs)."""
"""Group together configuration values (such as base tox configuration, tox environment configs)."""
from __future__ import annotations

from abc import ABC, abstractmethod
Expand Down Expand Up @@ -52,8 +52,7 @@ def __call__(
loaders: list[Loader[T]], # noqa: ARG002
args: ConfigLoadArgs, # noqa: ARG002
) -> T:
value = self.value() if callable(self.value) else self.value
return value
return self.value() if callable(self.value) else self.value

def __eq__(self, o: Any) -> bool:
return type(self) == type(o) and super().__eq__(o) and self.value == o.value
Expand Down
7 changes: 3 additions & 4 deletions src/tox/config/set_env.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ def _read_env_file(self, filename: str, args: ConfigLoadArgs) -> None:
msg = f"{env_file} does not exist for set_env"
raise Fail(msg)
for env_line in env_file.read_text().splitlines():
env_line = env_line.strip()
env_line = env_line.strip() # noqa: PLW2901
if not env_line or env_line.startswith("#"):
continue
key, value = self._extract_key_value(env_line)
Expand All @@ -66,9 +66,8 @@ def _extract_key_value(line: str) -> tuple[str, str]:
key, sep, value = line.partition("=")
if sep:
return key.strip(), value.strip()
else:
msg = f"invalid line {line!r} in set_env"
raise ValueError(msg)
msg = f"invalid line {line!r} in set_env"
raise ValueError(msg)

def load(self, item: str, args: ConfigLoadArgs | None = None) -> str:
if item in self._materialized:
Expand Down
4 changes: 2 additions & 2 deletions src/tox/config/sets.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,8 +189,8 @@ def _default_work_dir(self, conf: Config, env_name: str | None) -> Path: # noqa
def _default_temp_dir(self, conf: Config, env_name: str | None) -> Path: # noqa: ARG002
return cast(Path, self["work_dir"] / ".tmp")

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

def register_config(self) -> None:
self.add_constant(keys=["config_file_path"], desc="path to the configuration file", value=self._src_path)
Expand Down
5 changes: 2 additions & 3 deletions src/tox/config/source/discover.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,9 +79,8 @@ def _create_default_source(root_dir: Path | None) -> Source:
break
else: # if not set use where we find pyproject.toml in the tree or cwd
empty = root_dir
logging.warning(f"No {' or '.join(i.FILENAME for i in SOURCE_TYPES)} found, assuming empty tox.ini at {empty}")
src = ToxIni(empty / "tox.ini", content="")
return src
logging.warning("No %s found, assuming empty tox.ini at %s", " or ".join(i.FILENAME for i in SOURCE_TYPES), empty)
return ToxIni(empty / "tox.ini", content="")


__all__ = ("discover_source",)
3 changes: 1 addition & 2 deletions src/tox/config/source/ini_section.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,7 @@ def is_test_env(self) -> bool:

@property
def names(self) -> list[str]:
elements = list(extend_factors(self.name))
return elements
return list(extend_factors(self.name))


TEST_ENV_PREFIX = "testenv"
Expand Down
4 changes: 2 additions & 2 deletions src/tox/config/source/legacy_toml.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ def __init__(self, path: Path) -> None:
toml_content = tomllib.load(file_handler)
try:
content = toml_content["tool"]["tox"]["legacy_tox_ini"]
except KeyError:
raise ValueError
except KeyError as exc:
raise ValueError(path) from exc
super().__init__(path, content=content)


Expand Down

0 comments on commit b580e46

Please sign in to comment.