extended-mypy-django-plugin 0.5__py2.py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- extended_mypy_django_plugin/__init__.py +3 -0
- extended_mypy_django_plugin/annotations.py +75 -0
- extended_mypy_django_plugin/entry.py +48 -0
- extended_mypy_django_plugin/main.py +4 -0
- extended_mypy_django_plugin/plugin/__init__.py +3 -0
- extended_mypy_django_plugin/plugin/_config.py +124 -0
- extended_mypy_django_plugin/plugin/_debug.py +9 -0
- extended_mypy_django_plugin/plugin/_dependencies.py +61 -0
- extended_mypy_django_plugin/plugin/_hook.py +169 -0
- extended_mypy_django_plugin/plugin/_plugin.py +246 -0
- extended_mypy_django_plugin/plugin/_reports.py +411 -0
- extended_mypy_django_plugin/plugin/_store.py +251 -0
- extended_mypy_django_plugin/plugin/actions/__init__.py +5 -0
- extended_mypy_django_plugin/plugin/actions/_sem_analyze.py +88 -0
- extended_mypy_django_plugin/plugin/actions/_type_analyze.py +110 -0
- extended_mypy_django_plugin/plugin/actions/_type_checker.py +183 -0
- extended_mypy_django_plugin/py.typed +0 -0
- extended_mypy_django_plugin/scripts/__init__.py +3 -0
- extended_mypy_django_plugin/scripts/find_models.py +30 -0
- extended_mypy_django_plugin/scripts/get_installed_apps.py +53 -0
- extended_mypy_django_plugin/version.py +1 -0
- extended_mypy_django_plugin-0.5.dist-info/METADATA +59 -0
- extended_mypy_django_plugin-0.5.dist-info/RECORD +25 -0
- extended_mypy_django_plugin-0.5.dist-info/WHEEL +5 -0
- extended_mypy_django_plugin-0.5.dist-info/licenses/LICENSE +22 -0
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from collections.abc import Sequence
|
|
4
|
+
from typing import Generic, TypeVar
|
|
5
|
+
|
|
6
|
+
from django.db import models
|
|
7
|
+
|
|
8
|
+
T_Parent = TypeVar("T_Parent", bound=models.Model)
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class Concrete(Generic[T_Parent]):
|
|
12
|
+
"""
|
|
13
|
+
The ``Concrete`` annotation exists as a class with functionality for both
|
|
14
|
+
runtime and static type checking time.
|
|
15
|
+
|
|
16
|
+
At runtime it can be used to create special ``TypeVar`` objects that may
|
|
17
|
+
represent any one of the concrete children of some abstract class and
|
|
18
|
+
it can be used to find those concrete children.
|
|
19
|
+
|
|
20
|
+
At static type checking time (specifically with ``mypy``) it is used to create
|
|
21
|
+
a type that represents the Union of all the concrete children of some
|
|
22
|
+
abstract model.
|
|
23
|
+
|
|
24
|
+
.. automethod:: find_children
|
|
25
|
+
.. automethod:: type_var
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
@classmethod
|
|
29
|
+
def find_children(cls, parent: type[models.Model]) -> Sequence[type[models.Model]]:
|
|
30
|
+
"""
|
|
31
|
+
At runtime this will find all the concrete children of some model.
|
|
32
|
+
|
|
33
|
+
That is all models that inherit from this model and aren't abstract
|
|
34
|
+
themselves.
|
|
35
|
+
"""
|
|
36
|
+
found: list[type[models.Model]] = []
|
|
37
|
+
|
|
38
|
+
from django.contrib.contenttypes.models import ContentType
|
|
39
|
+
|
|
40
|
+
content_types = ContentType.objects.filter(app_label=parent._meta.app_label)
|
|
41
|
+
for ct in content_types:
|
|
42
|
+
model = ct.model_class()
|
|
43
|
+
if model is None:
|
|
44
|
+
continue
|
|
45
|
+
if not issubclass(model, parent):
|
|
46
|
+
continue
|
|
47
|
+
if hasattr(model, "Meta") and getattr(model.Meta, "is_abstract", False):
|
|
48
|
+
continue
|
|
49
|
+
found.append(model)
|
|
50
|
+
|
|
51
|
+
return found
|
|
52
|
+
|
|
53
|
+
@classmethod
|
|
54
|
+
def type_var(cls, name: str, parent: type[models.Model]) -> TypeVar:
|
|
55
|
+
"""
|
|
56
|
+
This returns an empty ``TypeVar`` at runtime, but the ``mypy`` plugin will
|
|
57
|
+
recognise that this ``TypeVar`` represents a choice of all the concrete
|
|
58
|
+
children of the specified model.
|
|
59
|
+
"""
|
|
60
|
+
return TypeVar(name)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class ConcreteQuerySet(Generic[T_Parent]):
|
|
64
|
+
"""
|
|
65
|
+
This is used to annotate a model such that the mypy plugin may turn this into
|
|
66
|
+
a union of all the default querysets for all the concrete children of the
|
|
67
|
+
specified abstract model class.
|
|
68
|
+
"""
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class DefaultQuerySet(Generic[T_Parent]):
|
|
72
|
+
"""
|
|
73
|
+
This is used to annotate a model such that the mypy plugin may turn this into
|
|
74
|
+
the queryset type used by the default manager on the model.
|
|
75
|
+
"""
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
from collections.abc import MutableMapping
|
|
2
|
+
|
|
3
|
+
from mypy.options import Options
|
|
4
|
+
from mypy.plugin import Plugin as MypyPlugin
|
|
5
|
+
|
|
6
|
+
from .plugin import ExtendedMypyStubs
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class PluginProvider:
|
|
10
|
+
"""
|
|
11
|
+
This can be used to provide both a mypy plugin as well as a __version__ that changes
|
|
12
|
+
when mypy needs to do a full restart.
|
|
13
|
+
|
|
14
|
+
Given either the extended_mypy_django_plugin.plugin.ExtendedMypyStubs class or a subclass
|
|
15
|
+
of that, usage is::
|
|
16
|
+
|
|
17
|
+
from extended_mypy_django_plugin.plugin import ExtendedMypyStubs
|
|
18
|
+
from extended_mypy_django_plugin.entry import PluginProvider
|
|
19
|
+
|
|
20
|
+
plugin = PluginProvider(ExtendedMypyStubs, locals())
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
def __init__(
|
|
24
|
+
self, plugin_cls: type[ExtendedMypyStubs], locals: MutableMapping[str, object], /
|
|
25
|
+
) -> None:
|
|
26
|
+
self.locals = locals
|
|
27
|
+
self.instance: ExtendedMypyStubs | None = None
|
|
28
|
+
self.plugin_cls = plugin_cls
|
|
29
|
+
|
|
30
|
+
def __call__(self, version: str) -> type[MypyPlugin]:
|
|
31
|
+
if self.instance is not None:
|
|
32
|
+
self.locals["__version__"] = str(self.instance.determine_plugin_version())
|
|
33
|
+
|
|
34
|
+
# Inside dmypy, don't create a new plugin
|
|
35
|
+
return MypyPlugin
|
|
36
|
+
|
|
37
|
+
provider = self
|
|
38
|
+
major, minor, _ = version.split(".", 2)
|
|
39
|
+
|
|
40
|
+
def __init__(instance: ExtendedMypyStubs, options: Options) -> None:
|
|
41
|
+
super(instance.__class__, instance).__init__(
|
|
42
|
+
options,
|
|
43
|
+
mypy_version_tuple=(int(major), int(minor)), # type: ignore[call-arg]
|
|
44
|
+
)
|
|
45
|
+
provider.instance = instance
|
|
46
|
+
provider.locals["__version__"] = str(instance.determine_plugin_version())
|
|
47
|
+
|
|
48
|
+
return type("Plugin", (provider.plugin_cls,), {"__init__": __init__})
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
"""
|
|
2
|
+
The config class is copied from ``django-stubs`` except it also looks for a
|
|
3
|
+
``python_identifier`` option and ensures it's a valid python identifier.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import configparser
|
|
7
|
+
import pathlib
|
|
8
|
+
import sys
|
|
9
|
+
from collections.abc import Callable
|
|
10
|
+
from functools import partial
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Any, NoReturn
|
|
13
|
+
|
|
14
|
+
from mypy_django_plugin.config import (
|
|
15
|
+
COULD_NOT_LOAD_FILE,
|
|
16
|
+
MISSING_DJANGO_SETTINGS,
|
|
17
|
+
MISSING_SECTION,
|
|
18
|
+
DjangoPluginConfig,
|
|
19
|
+
exit_with_error,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
if sys.version_info[:2] >= (3, 11):
|
|
23
|
+
import tomllib
|
|
24
|
+
else:
|
|
25
|
+
import tomli as tomllib
|
|
26
|
+
|
|
27
|
+
MISSING_SCRATCH_PATH = "missing required 'scratch_path' config"
|
|
28
|
+
INVALID_BOOL_SETTING = "invalid {key!r}: the setting must be a boolean"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class Config(DjangoPluginConfig):
|
|
32
|
+
__slots__ = (
|
|
33
|
+
"django_settings_module",
|
|
34
|
+
"strict_settings",
|
|
35
|
+
"scratch_path",
|
|
36
|
+
"installed_apps_script",
|
|
37
|
+
)
|
|
38
|
+
scratch_path: Path
|
|
39
|
+
installed_apps_script: Path | None
|
|
40
|
+
|
|
41
|
+
def parse_toml_file(self, filepath: pathlib.Path) -> None:
|
|
42
|
+
toml_exit: Callable[[str], NoReturn] = partial(exit_with_error, is_toml=True)
|
|
43
|
+
try:
|
|
44
|
+
with filepath.open(mode="rb") as f:
|
|
45
|
+
data = tomllib.load(f)
|
|
46
|
+
except (tomllib.TOMLDecodeError, OSError):
|
|
47
|
+
toml_exit(COULD_NOT_LOAD_FILE)
|
|
48
|
+
|
|
49
|
+
try:
|
|
50
|
+
config: dict[str, Any] = data["tool"]["django-stubs"]
|
|
51
|
+
except KeyError:
|
|
52
|
+
toml_exit(MISSING_SECTION.format(section="tool.django-stubs"))
|
|
53
|
+
|
|
54
|
+
if "django_settings_module" not in config:
|
|
55
|
+
toml_exit(MISSING_DJANGO_SETTINGS)
|
|
56
|
+
|
|
57
|
+
if "scratch_path" not in config:
|
|
58
|
+
toml_exit(MISSING_SCRATCH_PATH)
|
|
59
|
+
|
|
60
|
+
self.django_settings_module = config["django_settings_module"]
|
|
61
|
+
if not isinstance(self.django_settings_module, str):
|
|
62
|
+
toml_exit("invalid 'django_settings_module': the setting must be a string")
|
|
63
|
+
|
|
64
|
+
if not isinstance(config["scratch_path"], str):
|
|
65
|
+
toml_exit("invalid 'scratch_path': the setting must be a string")
|
|
66
|
+
self.scratch_path = filepath.parent / config["scratch_path"]
|
|
67
|
+
self.scratch_path.mkdir(parents=True, exist_ok=True)
|
|
68
|
+
|
|
69
|
+
if "installed_apps_path" in config:
|
|
70
|
+
if not isinstance(config["installed_apps_script"], str):
|
|
71
|
+
toml_exit("invalid 'installed_apps_script': the setting must be a string")
|
|
72
|
+
self.installed_apps_script = filepath.parent / config["installed_apps_script"]
|
|
73
|
+
else:
|
|
74
|
+
self.installed_apps_script = None
|
|
75
|
+
|
|
76
|
+
self.strict_settings = config.get("strict_settings", True)
|
|
77
|
+
if not isinstance(self.strict_settings, bool):
|
|
78
|
+
toml_exit(INVALID_BOOL_SETTING.format(key="strict_settings"))
|
|
79
|
+
|
|
80
|
+
def parse_ini_file(self, filepath: Path) -> None:
|
|
81
|
+
parser = configparser.ConfigParser()
|
|
82
|
+
try:
|
|
83
|
+
with filepath.open(encoding="utf-8") as f:
|
|
84
|
+
parser.read_file(f, source=str(filepath))
|
|
85
|
+
except OSError:
|
|
86
|
+
exit_with_error(COULD_NOT_LOAD_FILE)
|
|
87
|
+
|
|
88
|
+
section = "mypy.plugins.django-stubs"
|
|
89
|
+
if not parser.has_section(section):
|
|
90
|
+
exit_with_error(MISSING_SECTION.format(section=section))
|
|
91
|
+
|
|
92
|
+
if not parser.has_option(section, "django_settings_module"):
|
|
93
|
+
exit_with_error(MISSING_DJANGO_SETTINGS)
|
|
94
|
+
|
|
95
|
+
if not parser.has_option(section, "scratch_path"):
|
|
96
|
+
exit_with_error(MISSING_SCRATCH_PATH)
|
|
97
|
+
|
|
98
|
+
self.django_settings_module = parser.get(section, "django_settings_module").strip("'\"")
|
|
99
|
+
|
|
100
|
+
self.scratch_path = filepath.parent / parser.get(section, "scratch_path").strip("'\"")
|
|
101
|
+
self.scratch_path.mkdir(parents=True, exist_ok=True)
|
|
102
|
+
|
|
103
|
+
if parser.has_option(section, "installed_apps_script"):
|
|
104
|
+
self.installed_apps_script = filepath.parent / parser.get(
|
|
105
|
+
section, "installed_apps_script"
|
|
106
|
+
).strip("'\"")
|
|
107
|
+
else:
|
|
108
|
+
self.installed_apps_script = None
|
|
109
|
+
|
|
110
|
+
try:
|
|
111
|
+
self.strict_settings = parser.getboolean(section, "strict_settings", fallback=True)
|
|
112
|
+
except ValueError:
|
|
113
|
+
exit_with_error(INVALID_BOOL_SETTING.format(key="strict_settings"))
|
|
114
|
+
|
|
115
|
+
def to_json(self) -> dict[str, Any]:
|
|
116
|
+
"""We use this method to reset mypy cache via `report_config_data` hook."""
|
|
117
|
+
return {
|
|
118
|
+
"django_settings_module": self.django_settings_module,
|
|
119
|
+
"scratch_path": str(self.scratch_path),
|
|
120
|
+
"installed_apps_script": (
|
|
121
|
+
None if self.installed_apps_script is None else str(self.installed_apps_script)
|
|
122
|
+
),
|
|
123
|
+
"strict_settings": self.strict_settings,
|
|
124
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
from mypy.nodes import Import, ImportBase, ImportFrom
|
|
2
|
+
|
|
3
|
+
from ._reports import ModelModules, ReportNamesGetter
|
|
4
|
+
|
|
5
|
+
Dep = tuple[int, str, int]
|
|
6
|
+
DepList = list[tuple[int, str, int]]
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class Dependencies:
|
|
10
|
+
"""
|
|
11
|
+
This object is used to determine if a model is known, and also what
|
|
12
|
+
dependencies to return for a file for the get_additional_deps hook
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
def __init__(
|
|
16
|
+
self, model_modules: ModelModules, report_names_getter: ReportNamesGetter
|
|
17
|
+
) -> None:
|
|
18
|
+
self._model_modules = model_modules
|
|
19
|
+
self._report_names_getter = report_names_getter
|
|
20
|
+
|
|
21
|
+
def is_model_known(self, fullname: str) -> bool:
|
|
22
|
+
for mod, known in self._model_modules.items():
|
|
23
|
+
for cls in known.values():
|
|
24
|
+
if fullname == f"{cls.__module__}.{cls.__qualname__}":
|
|
25
|
+
return True
|
|
26
|
+
|
|
27
|
+
return False
|
|
28
|
+
|
|
29
|
+
def for_file(self, fullname: str, imports: list[ImportBase], super_deps: DepList) -> DepList:
|
|
30
|
+
deps = list(super_deps)
|
|
31
|
+
|
|
32
|
+
if fullname.startswith("django."):
|
|
33
|
+
return deps
|
|
34
|
+
|
|
35
|
+
for imp in imports:
|
|
36
|
+
found: set[str] = set()
|
|
37
|
+
if isinstance(imp, ImportFrom):
|
|
38
|
+
for name in imp.names:
|
|
39
|
+
found.add(f"{imp.id}.{name[0]}")
|
|
40
|
+
elif isinstance(imp, Import):
|
|
41
|
+
for name in imp.ids:
|
|
42
|
+
found.add(name[0])
|
|
43
|
+
|
|
44
|
+
for full in found:
|
|
45
|
+
for mod in self._model_modules:
|
|
46
|
+
if full == fullname:
|
|
47
|
+
continue
|
|
48
|
+
|
|
49
|
+
if full == mod or full.startswith(f"{mod}."):
|
|
50
|
+
new_dep = (10, mod, -1)
|
|
51
|
+
if new_dep not in deps:
|
|
52
|
+
deps.append(new_dep)
|
|
53
|
+
break
|
|
54
|
+
|
|
55
|
+
for report in self._report_names_getter(fullname, {m for _, m, _ in deps}):
|
|
56
|
+
new_dep = (10, report, -1)
|
|
57
|
+
|
|
58
|
+
if new_dep not in deps:
|
|
59
|
+
deps.append(new_dep)
|
|
60
|
+
|
|
61
|
+
return deps
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
"""
|
|
2
|
+
This exists as a helper for defining the mypy plugin.
|
|
3
|
+
|
|
4
|
+
The way a mypy plugin works is there is a class that inherits from
|
|
5
|
+
``mypy.plugin.Plugin`` with specific hooks that take in a string and returns
|
|
6
|
+
a function.
|
|
7
|
+
|
|
8
|
+
So for example, the ``get_customize_class_mro_hook`` hook will take in the
|
|
9
|
+
``fullname`` representing classes that can be altered, and a function that takes
|
|
10
|
+
in a ``ClassDefContext`` object and returns ``None`` must be returned if
|
|
11
|
+
the plugin wants to do something with that object.
|
|
12
|
+
|
|
13
|
+
The first plugin that mypy encounters which returns a function will win and no
|
|
14
|
+
other plugins will get to look at that fullname.
|
|
15
|
+
|
|
16
|
+
This is fine but it can get awkward when the function returned takes in more
|
|
17
|
+
options than only the context. To improve this situation, this module implements
|
|
18
|
+
a ``Hook`` class and associated decorator to turn those hooks into python
|
|
19
|
+
descriptors that do the correct thing.
|
|
20
|
+
|
|
21
|
+
.. code-block:: python
|
|
22
|
+
|
|
23
|
+
from typing import Generic
|
|
24
|
+
from mypy.plugin import Plugin, AttributeContext
|
|
25
|
+
from mypy.types import Type as MypyType
|
|
26
|
+
from extended_mypy_django_plugin.plugin import _hook
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class Hook(
|
|
31
|
+
Generic[_hook.T_Ctx, _hook.T_Ret], _hook.Hook["MyPlugin", _hook.T_Ctx, _hook.T_Ret]
|
|
32
|
+
): ...
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class MyPlugin(Plugin):
|
|
36
|
+
@_hook.hook
|
|
37
|
+
class get_attribute_hook(Hook[AttributeContext, MypyType]):
|
|
38
|
+
def choose(self) -> bool:
|
|
39
|
+
# return True if we want to use the run method for ``self.fullname``.
|
|
40
|
+
return self.fullname.endswith(".blah")
|
|
41
|
+
|
|
42
|
+
def run(self, ctx: AttributeContext) -> MypyType:
|
|
43
|
+
# Do stuff
|
|
44
|
+
return ...
|
|
45
|
+
|
|
46
|
+
The hook has ``choose`` which is essentially what would be on the plugin itself
|
|
47
|
+
in normal situations. It can find the string that would be passed in as
|
|
48
|
+
``self.fullname``. It returns ``True`` if we want to handle this string, otherwise
|
|
49
|
+
``False``.
|
|
50
|
+
|
|
51
|
+
If the hook is chosen, then ``run`` is ran with the specified context class and
|
|
52
|
+
needs to return what is needed from it.
|
|
53
|
+
|
|
54
|
+
The hook has access to it:
|
|
55
|
+
|
|
56
|
+
plugin
|
|
57
|
+
The plugin instance itself.
|
|
58
|
+
|
|
59
|
+
fullname
|
|
60
|
+
The string that was passed into the plugin's hook
|
|
61
|
+
|
|
62
|
+
super_hook
|
|
63
|
+
What would have been returned by the class the plugin is inheriting from.
|
|
64
|
+
"""
|
|
65
|
+
|
|
66
|
+
from __future__ import annotations
|
|
67
|
+
|
|
68
|
+
import abc
|
|
69
|
+
from collections.abc import Callable
|
|
70
|
+
from typing import Generic, TypeAlias, TypeVar, overload
|
|
71
|
+
|
|
72
|
+
from mypy.plugin import Plugin
|
|
73
|
+
|
|
74
|
+
T_Ctx = TypeVar("T_Ctx")
|
|
75
|
+
T_Ret = TypeVar("T_Ret")
|
|
76
|
+
T_Plugin = TypeVar("T_Plugin", bound=Plugin)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
_HookChooser: TypeAlias = Callable[[str], Callable[[T_Ctx], T_Ret] | None]
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class Hook(Generic[T_Plugin, T_Ctx, T_Ret], abc.ABC):
|
|
83
|
+
"""
|
|
84
|
+
Class used to represent both the choosing and running logic for a hook
|
|
85
|
+
on a mypy Plugin.
|
|
86
|
+
|
|
87
|
+
This is to be used with the ``hook`` descriptor defined below. See the
|
|
88
|
+
docstring on the module for more information.
|
|
89
|
+
|
|
90
|
+
Concrete subclasses of this must implement ``choose`` and ``run``.
|
|
91
|
+
|
|
92
|
+
The ``choose`` method will be used to determine if this hook should be used
|
|
93
|
+
by mypy to do something.
|
|
94
|
+
|
|
95
|
+
The ``run`` method will take in the context provided by mypy if this hook
|
|
96
|
+
was chosen. The type of that context and what needs to be returned is defined
|
|
97
|
+
by the specific mypy hook being implemented, and should be specified as
|
|
98
|
+
type vars when defining the implementation of the hook.
|
|
99
|
+
"""
|
|
100
|
+
|
|
101
|
+
def __init__(
|
|
102
|
+
self,
|
|
103
|
+
plugin: T_Plugin,
|
|
104
|
+
fullname: str,
|
|
105
|
+
super_hook: Callable[[T_Ctx], T_Ret] | None,
|
|
106
|
+
) -> None:
|
|
107
|
+
self.plugin = plugin
|
|
108
|
+
self.fullname = fullname
|
|
109
|
+
self.super_hook = super_hook
|
|
110
|
+
self.extra_init()
|
|
111
|
+
|
|
112
|
+
def extra_init(self) -> None: ...
|
|
113
|
+
|
|
114
|
+
@abc.abstractmethod
|
|
115
|
+
def run(self, ctx: T_Ctx) -> T_Ret: ...
|
|
116
|
+
|
|
117
|
+
@abc.abstractmethod
|
|
118
|
+
def choose(self) -> bool: ...
|
|
119
|
+
|
|
120
|
+
def hook(self) -> Callable[[T_Ctx], T_Ret] | None:
|
|
121
|
+
"""
|
|
122
|
+
This is the function that mypy ends up calling when asking the plugin
|
|
123
|
+
if it should handle something.
|
|
124
|
+
"""
|
|
125
|
+
if self.choose():
|
|
126
|
+
return self.run
|
|
127
|
+
else:
|
|
128
|
+
return self.super_hook
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
class hook(Generic[T_Plugin, T_Ctx, T_Ret]):
|
|
132
|
+
"""
|
|
133
|
+
This is a descriptor classes used to return a callable object that takes in
|
|
134
|
+
a string and either returns a function that mypy can use to perform an action,
|
|
135
|
+
or return None if this hook does not need to do anything in that instance.
|
|
136
|
+
"""
|
|
137
|
+
|
|
138
|
+
def __init__(self, hook: type[Hook[T_Plugin, T_Ctx, T_Ret]]) -> None:
|
|
139
|
+
self.hook = hook
|
|
140
|
+
self.__doc__ = hook.__doc__
|
|
141
|
+
|
|
142
|
+
name: str
|
|
143
|
+
|
|
144
|
+
def __set_name__(self, owner: type, name: str) -> None:
|
|
145
|
+
self.name = name
|
|
146
|
+
self.owner = owner
|
|
147
|
+
|
|
148
|
+
@overload
|
|
149
|
+
def __get__(self, instance: None, owner: None) -> hook[T_Plugin, T_Ctx, T_Ret]: ...
|
|
150
|
+
|
|
151
|
+
@overload
|
|
152
|
+
def __get__(self, instance: T_Plugin, owner: type[T_Plugin]) -> _HookChooser[T_Ctx, T_Ret]: ...
|
|
153
|
+
|
|
154
|
+
def __get__(
|
|
155
|
+
self, instance: T_Plugin | None, owner: type[T_Plugin] | None = None
|
|
156
|
+
) -> hook[T_Plugin, T_Ctx, T_Ret] | _HookChooser[T_Ctx, T_Ret]:
|
|
157
|
+
if instance is None:
|
|
158
|
+
return self
|
|
159
|
+
|
|
160
|
+
super_hook = getattr(super(self.owner, instance), self.name)
|
|
161
|
+
|
|
162
|
+
def result(fullname: str) -> Callable[[T_Ctx], T_Ret] | None:
|
|
163
|
+
return self.hook(
|
|
164
|
+
plugin=instance,
|
|
165
|
+
fullname=fullname,
|
|
166
|
+
super_hook=super_hook(fullname),
|
|
167
|
+
).hook()
|
|
168
|
+
|
|
169
|
+
return result
|