summaryrefslogtreecommitdiff
path: root/pylint/config
diff options
context:
space:
mode:
authorDaniël van Noord <13665637+DanielNoord@users.noreply.github.com>2022-09-09 15:01:22 +0200
committerDaniël van Noord <13665637+DanielNoord@users.noreply.github.com>2022-09-09 20:48:44 +0200
commitd439f2a01f088b00fb788c12599281d3311c06ea (patch)
tree2bbbee7135c3d79693bebc0e822778e230675406 /pylint/config
parentad6a735e2c9be3f16d0d671962deb8b00f98ab09 (diff)
downloadpylint-git-d439f2a01f088b00fb788c12599281d3311c06ea.tar.gz
Add typing to deprecated modules
Diffstat (limited to 'pylint/config')
-rw-r--r--pylint/config/option.py30
-rw-r--r--pylint/config/option_manager_mixin.py74
2 files changed, 66 insertions, 38 deletions
diff --git a/pylint/config/option.py b/pylint/config/option.py
index f61ac37a6..3bd812c0f 100644
--- a/pylint/config/option.py
+++ b/pylint/config/option.py
@@ -56,14 +56,14 @@ def _regexp_paths_csv_validator(
return patterns
-def _choice_validator(choices, name, value):
+def _choice_validator(choices: list[Any], name: str, value: Any) -> Any:
if value not in choices:
msg = "option %s: invalid value: %r, should be in %s"
raise optparse.OptionValueError(msg % (name, value, choices))
return value
-def _yn_validator(opt, _, value):
+def _yn_validator(opt: str, _: str, value: Any) -> bool:
if isinstance(value, int):
return bool(value)
if isinstance(value, str):
@@ -76,7 +76,7 @@ def _yn_validator(opt, _, value):
raise optparse.OptionValueError(msg % (opt, value))
-def _multiple_choice_validator(choices, name, value):
+def _multiple_choice_validator(choices: list[Any], name: str, value: Any) -> Any:
values = utils._check_csv(value)
for csv_value in values:
if csv_value not in choices:
@@ -85,18 +85,24 @@ def _multiple_choice_validator(choices, name, value):
return values
-def _non_empty_string_validator(opt, _, value): # pragma: no cover # Unused
+def _non_empty_string_validator( # pragma: no cover # Unused
+ opt: Any, _: str, value: str
+) -> str:
if not value:
msg = "indent string can't be empty."
raise optparse.OptionValueError(msg)
return utils._unquote(value)
-def _multiple_choices_validating_option(opt, name, value): # pragma: no cover # Unused
- return _multiple_choice_validator(opt.choices, name, value)
+def _multiple_choices_validating_option( # pragma: no cover # Unused
+ opt: optparse.Option, name: str, value: Any
+) -> Any:
+ return _multiple_choice_validator(
+ opt.choices, name, value # type: ignore[attr-defined]
+ )
-def _py_version_validator(_, name, value):
+def _py_version_validator(_: Any, name: str, value: Any) -> tuple[int, int, int]:
if not isinstance(value, tuple):
try:
value = tuple(int(val) for val in value.split("."))
@@ -142,7 +148,7 @@ def _call_validator(opttype: str, optdict: Any, option: str, value: Any) -> Any:
) from e
-def _validate(value, optdict, name=""):
+def _validate(value: Any, optdict: Any, name: str = "") -> Any:
"""Return a validated value for an option according to its type.
optional argument name is only used for error message formatting
@@ -179,7 +185,7 @@ class Option(optparse.Option):
TYPE_CHECKER["non_empty_string"] = _non_empty_string_validator
TYPE_CHECKER["py_version"] = _py_version_validator
- def __init__(self, *opts, **attrs):
+ def __init__(self, *opts: Any, **attrs: Any) -> None:
# TODO: 3.0: Remove deprecated class
warnings.warn(
"Option has been deprecated and will be removed in pylint 3.0",
@@ -189,7 +195,7 @@ class Option(optparse.Option):
if hasattr(self, "hide") and self.hide: # type: ignore[attr-defined]
self.help = optparse.SUPPRESS_HELP
- def _check_choice(self):
+ def _check_choice(self) -> None:
if self.type in {"choice", "multiple_choice", "confidence"}:
if self.choices is None: # type: ignore[attr-defined]
raise optparse.OptionError(
@@ -209,7 +215,9 @@ class Option(optparse.Option):
optparse.Option.CHECK_METHODS[2] = _check_choice # type: ignore[index]
- def process(self, opt, value, values, parser): # pragma: no cover # Argparse
+ def process( # pragma: no cover # Argparse
+ self, opt: Any, value: Any, values: Any, parser: Any
+ ) -> int:
assert isinstance(self.dest, str)
if self.callback and self.callback.__module__ == "pylint.lint.run":
return 1
diff --git a/pylint/config/option_manager_mixin.py b/pylint/config/option_manager_mixin.py
index 230a13f32..ef46a074f 100644
--- a/pylint/config/option_manager_mixin.py
+++ b/pylint/config/option_manager_mixin.py
@@ -15,31 +15,37 @@ import optparse # pylint: disable=deprecated-module
import os
import sys
import warnings
+from collections.abc import Iterator
from pathlib import Path
-from typing import Any, TextIO
+from typing import TYPE_CHECKING, Any, TextIO
from pylint import utils
from pylint.config.option import Option
from pylint.config.option_parser import OptionParser # type: ignore[attr-defined]
from pylint.typing import OptionDict
+if TYPE_CHECKING:
+ from pylint.config.options_provider_mixin import ( # type: ignore[attr-defined]
+ OptionsProviderMixin,
+ )
+
if sys.version_info >= (3, 11):
import tomllib
else:
import tomli as tomllib
-def _expand_default(self, option):
+def _expand_default(self: optparse.HelpFormatter, option: Option) -> str:
"""Patch OptionParser.expand_default with custom behaviour.
This will handle defaults to avoid overriding values in the
configuration file.
"""
if self.parser is None or not self.default_tag:
- return option.help
+ return str(option.help)
optname = option._long_opts[0][2:]
try:
- provider = self.parser.options_manager._all_options[optname]
+ provider = self.parser.options_manager._all_options[optname] # type: ignore[attr-defined]
except KeyError:
value = None
else:
@@ -49,11 +55,11 @@ def _expand_default(self, option):
value = utils._format_option_value(optdict, value)
if value is optparse.NO_DEFAULT or not value:
value = self.NO_DEFAULT_VALUE
- return option.help.replace(self.default_tag, str(value))
+ return option.help.replace(self.default_tag, str(value)) # type: ignore[union-attr]
@contextlib.contextmanager
-def _patch_optparse():
+def _patch_optparse() -> Iterator[None]:
# pylint: disable = redefined-variable-type
orig_default = optparse.HelpFormatter
try:
@@ -66,7 +72,7 @@ def _patch_optparse():
class OptionsManagerMixIn:
"""Handle configuration from both a configuration file and command line options."""
- def __init__(self, usage):
+ def __init__(self, usage: str) -> None:
# TODO: 3.0: Remove deprecated class
warnings.warn(
"OptionsManagerMixIn has been deprecated and will be removed in pylint 3.0",
@@ -74,16 +80,16 @@ class OptionsManagerMixIn:
)
self.reset_parsers(usage)
# list of registered options providers
- self.options_providers = []
+ self.options_providers: list[OptionsProviderMixin] = []
# dictionary associating option name to checker
- self._all_options = collections.OrderedDict()
- self._short_options = {}
- self._nocallback_options = {}
- self._mygroups = {}
+ self._all_options: collections.OrderedDict[Any, Any] = collections.OrderedDict()
+ self._short_options: dict[Any, Any] = {}
+ self._nocallback_options: dict[Any, Any] = {}
+ self._mygroups: dict[Any, Any] = {}
# verbosity
self._maxlevel = 0
- def reset_parsers(self, usage=""):
+ def reset_parsers(self, usage: str = "") -> None:
# configuration file parser
self.cfgfile_parser = configparser.ConfigParser(
inline_comment_prefixes=("#", ";")
@@ -93,7 +99,9 @@ class OptionsManagerMixIn:
self.cmdline_parser.options_manager = self
self._optik_option_attrs = set(self.cmdline_parser.option_class.ATTRS)
- def register_options_provider(self, provider, own_group=True):
+ def register_options_provider(
+ self, provider: OptionsProviderMixin, own_group: bool = True
+ ) -> None:
"""Register an options provider."""
self.options_providers.append(provider)
non_group_spec_options = [
@@ -119,7 +127,9 @@ class OptionsManagerMixIn:
]
self.add_option_group(gname, gdoc, goptions, provider)
- def add_option_group(self, group_name, _, options, provider):
+ def add_option_group(
+ self, group_name: str, _: Any, options: Any, provider: OptionsProviderMixin
+ ) -> None:
# add option group to the command line parser
if group_name in self._mygroups:
group = self._mygroups[group_name]
@@ -141,13 +151,21 @@ class OptionsManagerMixIn:
optdict["action"] = "callback"
self.add_optik_option(provider, group, opt, optdict)
- def add_optik_option(self, provider, optikcontainer, opt, optdict):
+ def add_optik_option(
+ self,
+ provider: OptionsProviderMixin,
+ optikcontainer: Any,
+ opt: str,
+ optdict: OptionDict,
+ ) -> None:
args, optdict = self.optik_option(provider, opt, optdict)
option = optikcontainer.add_option(*args, **optdict)
self._all_options[opt] = provider
self._maxlevel = max(self._maxlevel, option.level or 0)
- def optik_option(self, provider, opt, optdict):
+ def optik_option(
+ self, provider: OptionsProviderMixin, opt: str, optdict: OptionDict
+ ) -> tuple[list[str], OptionDict]:
"""Get our personal option definition and return a suitable form for
use with optik/optparse.
"""
@@ -165,12 +183,12 @@ class OptionsManagerMixIn:
and optdict.get("default") is not None
and optdict["action"] not in ("store_true", "store_false")
):
- optdict["help"] += " [current: %default]"
+ optdict["help"] += " [current: %default]" # type: ignore[operator]
del optdict["default"]
args = ["--" + str(opt)]
if "short" in optdict:
self._short_options[optdict["short"]] = opt
- args.append("-" + optdict["short"])
+ args.append("-" + optdict["short"]) # type: ignore[operator]
del optdict["short"]
# cleanup option definition dict before giving it to optik
for key in list(optdict.keys()):
@@ -178,7 +196,9 @@ class OptionsManagerMixIn:
optdict.pop(key)
return args, optdict
- def cb_set_provider_option(self, option, opt, value, parser):
+ def cb_set_provider_option(
+ self, option: Option, opt: str, value: Any, parser: Any
+ ) -> None:
"""Optik callback for option setting."""
if opt.startswith("--"):
# remove -- on long option
@@ -191,7 +211,7 @@ class OptionsManagerMixIn:
value = 1
self.global_set_option(opt, value)
- def global_set_option(self, opt, value):
+ def global_set_option(self, opt: str, value: Any) -> None:
"""Set option on the correct option provider."""
self._all_options[opt].set_option(opt, value)
@@ -230,7 +250,7 @@ class OptionsManagerMixIn:
)
printed = True
- def load_provider_defaults(self):
+ def load_provider_defaults(self) -> None:
"""Initialize configuration using default values."""
for provider in self.options_providers:
provider.load_defaults()
@@ -303,7 +323,7 @@ class OptionsManagerMixIn:
parser.add_section(section_name)
parser.set(section_name, option, value=value)
- def load_config_file(self):
+ def load_config_file(self) -> None:
"""Dispatch values previously read from a configuration file to each
option's provider.
"""
@@ -315,11 +335,11 @@ class OptionsManagerMixIn:
except (KeyError, optparse.OptionError):
continue
- def load_configuration(self, **kwargs):
+ def load_configuration(self, **kwargs: Any) -> None:
"""Override configuration according to given parameters."""
return self.load_configuration_from_config(kwargs)
- def load_configuration_from_config(self, config):
+ def load_configuration_from_config(self, config: dict[str, Any]) -> None:
for opt, opt_value in config.items():
opt = opt.replace("_", "-")
provider = self._all_options[opt]
@@ -344,8 +364,8 @@ class OptionsManagerMixIn:
setattr(config, attr, value)
return args # type: ignore[return-value]
- def help(self, level=0):
+ def help(self, level: int = 0) -> str:
"""Return the usage string for available options."""
self.cmdline_parser.formatter.output_level = level
with _patch_optparse():
- return self.cmdline_parser.format_help()
+ return str(self.cmdline_parser.format_help())