extended-mypy-django-plugin 0.8.0__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/_plugin/__init__.py +0 -0
- extended_mypy_django_plugin/_plugin/analyze.py +53 -0
- extended_mypy_django_plugin/_plugin/annotation_resolver.py +313 -0
- extended_mypy_django_plugin/_plugin/config.py +160 -0
- extended_mypy_django_plugin/_plugin/debug.py +9 -0
- extended_mypy_django_plugin/_plugin/entry.py +126 -0
- extended_mypy_django_plugin/_plugin/hook.py +279 -0
- extended_mypy_django_plugin/_plugin/plugin.py +203 -0
- extended_mypy_django_plugin/_plugin/protocols.py +222 -0
- extended_mypy_django_plugin/_plugin/type_checker.py +115 -0
- extended_mypy_django_plugin/_plugin/virtual_dependencies.py +70 -0
- extended_mypy_django_plugin/annotations.py +74 -0
- extended_mypy_django_plugin/django_analysis/__init__.py +22 -0
- extended_mypy_django_plugin/django_analysis/discovery/__init__.py +15 -0
- extended_mypy_django_plugin/django_analysis/discovery/concrete_models.py +48 -0
- extended_mypy_django_plugin/django_analysis/discovery/container.py +22 -0
- extended_mypy_django_plugin/django_analysis/discovery/import_path.py +59 -0
- extended_mypy_django_plugin/django_analysis/discovery/known_models.py +113 -0
- extended_mypy_django_plugin/django_analysis/discovery/settings_types.py +44 -0
- extended_mypy_django_plugin/django_analysis/fields.py +39 -0
- extended_mypy_django_plugin/django_analysis/hasher.py +12 -0
- extended_mypy_django_plugin/django_analysis/models.py +79 -0
- extended_mypy_django_plugin/django_analysis/modules.py +39 -0
- extended_mypy_django_plugin/django_analysis/project.py +152 -0
- extended_mypy_django_plugin/django_analysis/protocols.py +703 -0
- extended_mypy_django_plugin/django_analysis/virtual_dependencies/__init__.py +33 -0
- extended_mypy_django_plugin/django_analysis/virtual_dependencies/dependency.py +139 -0
- extended_mypy_django_plugin/django_analysis/virtual_dependencies/folder.py +136 -0
- extended_mypy_django_plugin/django_analysis/virtual_dependencies/handler.py +179 -0
- extended_mypy_django_plugin/django_analysis/virtual_dependencies/namer.py +18 -0
- extended_mypy_django_plugin/django_analysis/virtual_dependencies/report.py +583 -0
- extended_mypy_django_plugin/main.py +3 -0
- extended_mypy_django_plugin/plugin.py +15 -0
- extended_mypy_django_plugin/py.typed +0 -0
- extended_mypy_django_plugin/scripts/__init__.py +0 -0
- extended_mypy_django_plugin/scripts/determine_django_state.py +114 -0
- extended_mypy_django_plugin/version.py +1 -0
- extended_mypy_django_plugin-0.8.0.dist-info/METADATA +36 -0
- extended_mypy_django_plugin-0.8.0.dist-info/RECORD +42 -0
- extended_mypy_django_plugin-0.8.0.dist-info/WHEEL +4 -0
- extended_mypy_django_plugin-0.8.0.dist-info/licenses/LICENSE +22 -0
|
File without changes
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
from mypy.plugin import AnalyzeTypeContext
|
|
2
|
+
from mypy.types import Type as MypyType
|
|
3
|
+
from mypy.types import TypeQuery, TypeVarType, get_proper_type
|
|
4
|
+
|
|
5
|
+
from . import protocols
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class HasTypeVars(TypeQuery[bool]):
|
|
9
|
+
"""
|
|
10
|
+
Find where we have a concrete annotation
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
def __init__(self) -> None:
|
|
14
|
+
super().__init__(any)
|
|
15
|
+
|
|
16
|
+
def visit_type_var(self, t: TypeVarType) -> bool:
|
|
17
|
+
return True
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class Analyzer:
|
|
21
|
+
def __init__(self, make_resolver: protocols.ResolverMaker) -> None:
|
|
22
|
+
self.make_resolver = make_resolver
|
|
23
|
+
|
|
24
|
+
def analyze_type(
|
|
25
|
+
self, ctx: AnalyzeTypeContext, annotation: protocols.KnownAnnotations
|
|
26
|
+
) -> MypyType:
|
|
27
|
+
"""
|
|
28
|
+
We resolve annotations at this point. Unless the type being analyzed involves type vars.
|
|
29
|
+
|
|
30
|
+
Resolving type vars requires we wait until we are analyzing method/function calls. Between now
|
|
31
|
+
and then we replace the type with an unbound type that wraps a resolved instance because when we
|
|
32
|
+
can resolve the type vars we can't resolve what the type var actually is!
|
|
33
|
+
"""
|
|
34
|
+
args = ctx.type.args
|
|
35
|
+
if len(args) != 1:
|
|
36
|
+
ctx.api.fail("Concrete annotations must contain exactly one argument", ctx.context)
|
|
37
|
+
return ctx.type
|
|
38
|
+
|
|
39
|
+
model_type = get_proper_type(ctx.api.analyze_type(args[0]))
|
|
40
|
+
|
|
41
|
+
resolver = self.make_resolver(ctx=ctx)
|
|
42
|
+
|
|
43
|
+
if model_type.accept(HasTypeVars()):
|
|
44
|
+
ctx.api.fail(
|
|
45
|
+
"Using a concrete annotation on a TypeVar is not currently supported", ctx.context
|
|
46
|
+
)
|
|
47
|
+
return ctx.type
|
|
48
|
+
|
|
49
|
+
resolved = resolver.resolve(annotation, model_type)
|
|
50
|
+
if resolved is None:
|
|
51
|
+
return ctx.type
|
|
52
|
+
else:
|
|
53
|
+
return resolved
|
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
import functools
|
|
2
|
+
from collections.abc import Iterator, Sequence
|
|
3
|
+
from typing import TYPE_CHECKING, cast
|
|
4
|
+
|
|
5
|
+
from mypy.errorcodes import ErrorCode
|
|
6
|
+
from mypy.message_registry import ErrorMessage
|
|
7
|
+
from mypy.nodes import Context, PlaceholderNode, TypeAlias, TypeInfo
|
|
8
|
+
from mypy.plugin import (
|
|
9
|
+
AnalyzeTypeContext,
|
|
10
|
+
AttributeContext,
|
|
11
|
+
DynamicClassDefContext,
|
|
12
|
+
FunctionContext,
|
|
13
|
+
MethodContext,
|
|
14
|
+
)
|
|
15
|
+
from mypy.semanal import SemanticAnalyzer
|
|
16
|
+
from mypy.typeanal import TypeAnalyser
|
|
17
|
+
from mypy.types import (
|
|
18
|
+
AnyType,
|
|
19
|
+
Instance,
|
|
20
|
+
PlaceholderType,
|
|
21
|
+
ProperType,
|
|
22
|
+
TypeOfAny,
|
|
23
|
+
TypeType,
|
|
24
|
+
UnionType,
|
|
25
|
+
get_proper_type,
|
|
26
|
+
)
|
|
27
|
+
from mypy.types import Type as MypyType
|
|
28
|
+
from typing_extensions import Self, assert_never
|
|
29
|
+
|
|
30
|
+
from . import protocols
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class ShouldDefer(Exception):
|
|
34
|
+
pass
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class FailedLookup(Exception):
|
|
38
|
+
pass
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class AnnotationResolver:
|
|
42
|
+
@classmethod
|
|
43
|
+
def create(
|
|
44
|
+
cls,
|
|
45
|
+
*,
|
|
46
|
+
get_concrete_aliases: protocols.AliasGetter,
|
|
47
|
+
get_queryset_aliases: protocols.AliasGetter,
|
|
48
|
+
plugin_lookup_fully_qualified: protocols.LookupFullyQualified,
|
|
49
|
+
ctx: protocols.ValidContextForAnnotationResolver,
|
|
50
|
+
) -> Self:
|
|
51
|
+
"""
|
|
52
|
+
This classmethod constructor lets us normalise the ctx to satisfy the interface the
|
|
53
|
+
AnnotationResolver expects.
|
|
54
|
+
|
|
55
|
+
Because each ctx type has a different api on it that provides a different set of
|
|
56
|
+
abilities.
|
|
57
|
+
"""
|
|
58
|
+
|
|
59
|
+
def sem_defer(sem_api: SemanticAnalyzer) -> bool:
|
|
60
|
+
"""
|
|
61
|
+
The semantic analyzer is the only api that can actually defer
|
|
62
|
+
|
|
63
|
+
Return True if was able to defer
|
|
64
|
+
"""
|
|
65
|
+
if sem_api.final_iteration:
|
|
66
|
+
return False
|
|
67
|
+
else:
|
|
68
|
+
sem_api.defer()
|
|
69
|
+
return True
|
|
70
|
+
|
|
71
|
+
def _lookup_info(sem_api: SemanticAnalyzer | None, fullname: str) -> TypeInfo | None:
|
|
72
|
+
"""
|
|
73
|
+
If we have the semantic api, there's more we can do when trying to lookup
|
|
74
|
+
some name
|
|
75
|
+
"""
|
|
76
|
+
if sem_api is not None:
|
|
77
|
+
instance = sem_api.named_type_or_none(fullname)
|
|
78
|
+
if instance:
|
|
79
|
+
return instance.type
|
|
80
|
+
|
|
81
|
+
sym = plugin_lookup_fully_qualified(fullname)
|
|
82
|
+
if not sym or not isinstance(node := sym.node, TypeInfo):
|
|
83
|
+
return None
|
|
84
|
+
else:
|
|
85
|
+
return node
|
|
86
|
+
|
|
87
|
+
def checker_named_type_or_none(
|
|
88
|
+
fullname: str, args: list[MypyType] | None = None
|
|
89
|
+
) -> Instance | None:
|
|
90
|
+
"""
|
|
91
|
+
When we have a TypeChecker we need to replicate close to what the semantic api
|
|
92
|
+
does for named_type_or_none
|
|
93
|
+
"""
|
|
94
|
+
sym = plugin_lookup_fully_qualified(fullname)
|
|
95
|
+
if not sym or not isinstance(node := sym.node, TypeInfo):
|
|
96
|
+
return None
|
|
97
|
+
if args:
|
|
98
|
+
return Instance(node, args)
|
|
99
|
+
return Instance(node, [AnyType(TypeOfAny.special_form)] * len(node.defn.type_vars))
|
|
100
|
+
|
|
101
|
+
def _lookup_alias(line: int, alias: str) -> Iterator[Instance | PlaceholderType]:
|
|
102
|
+
"""
|
|
103
|
+
This is the same regardless of which ctx we have
|
|
104
|
+
"""
|
|
105
|
+
try:
|
|
106
|
+
sym = plugin_lookup_fully_qualified(alias)
|
|
107
|
+
except AssertionError:
|
|
108
|
+
raise FailedLookup(f"Failed to lookup {alias}")
|
|
109
|
+
|
|
110
|
+
if not sym or isinstance(sym.node, PlaceholderNode):
|
|
111
|
+
yield PlaceholderType(alias, [], line)
|
|
112
|
+
return
|
|
113
|
+
|
|
114
|
+
assert sym and isinstance(sym.node, TypeAlias)
|
|
115
|
+
target = get_proper_type(sym.node.target)
|
|
116
|
+
|
|
117
|
+
if isinstance(target, Instance):
|
|
118
|
+
yield target
|
|
119
|
+
elif isinstance(target, UnionType):
|
|
120
|
+
for item in target.items:
|
|
121
|
+
found = get_proper_type(item)
|
|
122
|
+
assert isinstance(found, Instance | PlaceholderType)
|
|
123
|
+
yield found
|
|
124
|
+
else:
|
|
125
|
+
raise FailedLookup(f"Expected only an instance or union for {alias}: got {target}")
|
|
126
|
+
|
|
127
|
+
fail: protocols.FailFunc
|
|
128
|
+
defer: protocols.DeferFunc
|
|
129
|
+
context: Context
|
|
130
|
+
lookup_info: protocols.LookupInfo
|
|
131
|
+
named_type_or_none: protocols.NamedTypeOrNone
|
|
132
|
+
|
|
133
|
+
match ctx:
|
|
134
|
+
case DynamicClassDefContext(api=api):
|
|
135
|
+
assert isinstance(api, SemanticAnalyzer)
|
|
136
|
+
context = ctx.call
|
|
137
|
+
sem_api = api
|
|
138
|
+
defer = functools.partial(sem_defer, sem_api)
|
|
139
|
+
fail = functools.partial(sem_api.fail, ctx=context)
|
|
140
|
+
lookup_info = functools.partial(_lookup_info, sem_api)
|
|
141
|
+
lookup_alias = functools.partial(_lookup_alias, context.line)
|
|
142
|
+
named_type_or_none = sem_api.named_type_or_none
|
|
143
|
+
case AnalyzeTypeContext(api=api):
|
|
144
|
+
assert isinstance(api, TypeAnalyser)
|
|
145
|
+
assert isinstance(api.api, SemanticAnalyzer)
|
|
146
|
+
context = ctx.context
|
|
147
|
+
sem_api = api.api
|
|
148
|
+
defer = functools.partial(sem_defer, sem_api)
|
|
149
|
+
fail = functools.partial(sem_api.fail, ctx=context)
|
|
150
|
+
lookup_info = functools.partial(_lookup_info, sem_api)
|
|
151
|
+
lookup_alias = functools.partial(_lookup_alias, context.line)
|
|
152
|
+
named_type_or_none = sem_api.named_type_or_none
|
|
153
|
+
case AttributeContext(api=api) | MethodContext(api=api) | FunctionContext(api=api):
|
|
154
|
+
context = ctx.context
|
|
155
|
+
defer = lambda: False
|
|
156
|
+
|
|
157
|
+
def checker_fail(msg: str | ErrorMessage, code: ErrorCode | None = None) -> None:
|
|
158
|
+
return api.fail(msg, context, code=code)
|
|
159
|
+
|
|
160
|
+
fail = checker_fail
|
|
161
|
+
|
|
162
|
+
lookup_info = functools.partial(_lookup_info, None)
|
|
163
|
+
lookup_alias = functools.partial(_lookup_alias, context.line)
|
|
164
|
+
named_type_or_none = checker_named_type_or_none
|
|
165
|
+
case _:
|
|
166
|
+
assert_never(ctx)
|
|
167
|
+
|
|
168
|
+
return cls(
|
|
169
|
+
context=context,
|
|
170
|
+
get_concrete_aliases=get_concrete_aliases,
|
|
171
|
+
get_queryset_aliases=get_queryset_aliases,
|
|
172
|
+
defer=defer,
|
|
173
|
+
fail=fail,
|
|
174
|
+
lookup_info=lookup_info,
|
|
175
|
+
lookup_alias=lookup_alias,
|
|
176
|
+
named_type_or_none=named_type_or_none,
|
|
177
|
+
)
|
|
178
|
+
|
|
179
|
+
def __init__(
|
|
180
|
+
self,
|
|
181
|
+
*,
|
|
182
|
+
context: Context,
|
|
183
|
+
get_concrete_aliases: protocols.AliasGetter,
|
|
184
|
+
get_queryset_aliases: protocols.AliasGetter,
|
|
185
|
+
fail: protocols.FailFunc,
|
|
186
|
+
defer: protocols.DeferFunc,
|
|
187
|
+
lookup_alias: protocols.LookupAlias,
|
|
188
|
+
lookup_info: protocols.LookupInfo,
|
|
189
|
+
named_type_or_none: protocols.NamedTypeOrNone,
|
|
190
|
+
) -> None:
|
|
191
|
+
self._defer = defer
|
|
192
|
+
self._named_type_or_none = named_type_or_none
|
|
193
|
+
self.fail = fail
|
|
194
|
+
self.context = context
|
|
195
|
+
self.lookup_info = lookup_info
|
|
196
|
+
self.lookup_alias = lookup_alias
|
|
197
|
+
self.get_concrete_aliases = get_concrete_aliases
|
|
198
|
+
self.get_queryset_aliases = get_queryset_aliases
|
|
199
|
+
|
|
200
|
+
def _flatten_union(self, typ: ProperType) -> Iterator[ProperType]:
|
|
201
|
+
"""
|
|
202
|
+
Recursively flatten a union
|
|
203
|
+
"""
|
|
204
|
+
if isinstance(typ, UnionType):
|
|
205
|
+
for item in typ.items:
|
|
206
|
+
yield from self._flatten_union(get_proper_type(item))
|
|
207
|
+
else:
|
|
208
|
+
yield typ
|
|
209
|
+
|
|
210
|
+
def _concrete_for(
|
|
211
|
+
self, model_type: ProperType, get_aliases: protocols.AliasGetter
|
|
212
|
+
) -> Instance | TypeType | UnionType | PlaceholderType | None:
|
|
213
|
+
"""
|
|
214
|
+
Given some type that represents a model, and an alias getter, determine an
|
|
215
|
+
Instance if we can from the model_type and use it with the alias getter.
|
|
216
|
+
"""
|
|
217
|
+
is_type: bool = False
|
|
218
|
+
|
|
219
|
+
found: ProperType = model_type
|
|
220
|
+
if isinstance(model_type, TypeType):
|
|
221
|
+
is_type = True
|
|
222
|
+
found = model_type.item
|
|
223
|
+
|
|
224
|
+
if isinstance(found, AnyType):
|
|
225
|
+
did_defer = self._defer()
|
|
226
|
+
if not did_defer:
|
|
227
|
+
self.fail("Tried to use concrete annotations on a typing.Any")
|
|
228
|
+
return None
|
|
229
|
+
|
|
230
|
+
if not isinstance(found, Instance | UnionType):
|
|
231
|
+
return None
|
|
232
|
+
|
|
233
|
+
all_types = list(self._flatten_union(found))
|
|
234
|
+
are_all_instances: bool = True
|
|
235
|
+
names: list[str] = []
|
|
236
|
+
concrete: list[Instance | PlaceholderType] = []
|
|
237
|
+
|
|
238
|
+
for item in all_types:
|
|
239
|
+
if not isinstance(item, Instance):
|
|
240
|
+
self.fail(
|
|
241
|
+
f"Expected to operate on specific classes, got a {item.__class__.__name__}: {item}"
|
|
242
|
+
)
|
|
243
|
+
are_all_instances = False
|
|
244
|
+
continue
|
|
245
|
+
|
|
246
|
+
name = item.type.fullname
|
|
247
|
+
names.append(name)
|
|
248
|
+
concrete.extend(self._instances_from_aliases(get_aliases, name))
|
|
249
|
+
|
|
250
|
+
if not are_all_instances:
|
|
251
|
+
return None
|
|
252
|
+
|
|
253
|
+
if not concrete:
|
|
254
|
+
# We found instances, but couldn't get aliases
|
|
255
|
+
# Either defer and we'll try again later or fail if we can't defer
|
|
256
|
+
did_defer = self._defer()
|
|
257
|
+
if not did_defer:
|
|
258
|
+
self.fail(f"No concrete models found for {names}")
|
|
259
|
+
return None
|
|
260
|
+
|
|
261
|
+
return self._make_union(is_type, tuple(concrete))
|
|
262
|
+
|
|
263
|
+
def _make_union(
|
|
264
|
+
self, is_type: bool, instances: Sequence[Instance | PlaceholderType]
|
|
265
|
+
) -> UnionType | Instance | TypeType | PlaceholderType:
|
|
266
|
+
"""
|
|
267
|
+
Given a sequence of instances, make them all TypeType if is_type and then
|
|
268
|
+
return either the one type if the list is of 1, or the list wrapped in a UnionType
|
|
269
|
+
"""
|
|
270
|
+
items: Sequence[UnionType | TypeType | Instance | PlaceholderType]
|
|
271
|
+
|
|
272
|
+
if is_type:
|
|
273
|
+
items = [TypeType(item) for item in instances]
|
|
274
|
+
else:
|
|
275
|
+
items = instances
|
|
276
|
+
|
|
277
|
+
if len(items) == 1:
|
|
278
|
+
return items[0]
|
|
279
|
+
else:
|
|
280
|
+
return UnionType(tuple(items))
|
|
281
|
+
|
|
282
|
+
def _instances_from_aliases(
|
|
283
|
+
self, get_aliases: protocols.AliasGetter, *models: str
|
|
284
|
+
) -> Iterator[Instance | PlaceholderType]:
|
|
285
|
+
for model, alias in get_aliases(*models).items():
|
|
286
|
+
if alias is None:
|
|
287
|
+
self.fail(f"Failed to find concrete alias instance for '{model}'")
|
|
288
|
+
continue
|
|
289
|
+
|
|
290
|
+
try:
|
|
291
|
+
yield from self.lookup_alias(alias)
|
|
292
|
+
except FailedLookup as error:
|
|
293
|
+
self.fail(
|
|
294
|
+
f"Failed to create concrete alias instance for '{model}' ({error}) (this is likely a bug in extended_mypy_django_plugin)"
|
|
295
|
+
)
|
|
296
|
+
|
|
297
|
+
def resolve(
|
|
298
|
+
self, annotation: protocols.KnownAnnotations, model_type: ProperType
|
|
299
|
+
) -> Instance | TypeType | UnionType | PlaceholderType | None:
|
|
300
|
+
if annotation is protocols.KnownAnnotations.CONCRETE:
|
|
301
|
+
return self._concrete_for(model_type, self.get_concrete_aliases)
|
|
302
|
+
|
|
303
|
+
elif annotation is protocols.KnownAnnotations.DEFAULT_QUERYSET:
|
|
304
|
+
return self._concrete_for(model_type, self.get_queryset_aliases)
|
|
305
|
+
|
|
306
|
+
else:
|
|
307
|
+
assert_never(annotation)
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
make_resolver = AnnotationResolver.create
|
|
311
|
+
|
|
312
|
+
if TYPE_CHECKING:
|
|
313
|
+
_R: protocols.Resolver = cast(AnnotationResolver, None)
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import configparser
|
|
2
|
+
import dataclasses
|
|
3
|
+
import pathlib
|
|
4
|
+
import sys
|
|
5
|
+
from collections.abc import Mapping
|
|
6
|
+
|
|
7
|
+
from mypy_django_plugin import config as django_stubs_config
|
|
8
|
+
from typing_extensions import Self
|
|
9
|
+
|
|
10
|
+
from ..django_analysis import ImportPath, protocols
|
|
11
|
+
from ..version import VERSION
|
|
12
|
+
|
|
13
|
+
if sys.version_info >= (3, 11):
|
|
14
|
+
import tomllib
|
|
15
|
+
else:
|
|
16
|
+
import tomli as tomllib
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclasses.dataclass(frozen=True)
|
|
20
|
+
class ExtraOptions:
|
|
21
|
+
"""
|
|
22
|
+
The extended_mypy_django_plugin adds two options to the django-stubs configuration in the mypy configuration
|
|
23
|
+
|
|
24
|
+
scratch_path
|
|
25
|
+
A folder where virtual dependencies are written to
|
|
26
|
+
|
|
27
|
+
project_root
|
|
28
|
+
This defaults to the folder the config is found in. It should be the path to the root of
|
|
29
|
+
the project. This value will be added to sys.path before Django is loaded
|
|
30
|
+
|
|
31
|
+
django_settings_module
|
|
32
|
+
The option used to set DJANGO_SETTINGS_MODULE when loading django
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
scratch_path: pathlib.Path
|
|
36
|
+
project_root: pathlib.Path
|
|
37
|
+
django_settings_module: protocols.ImportPath
|
|
38
|
+
|
|
39
|
+
@classmethod
|
|
40
|
+
def from_config(cls, filepath: str | pathlib.Path | None) -> Self:
|
|
41
|
+
if filepath is None:
|
|
42
|
+
django_stubs_config.exit_with_error(django_stubs_config.INVALID_FILE)
|
|
43
|
+
|
|
44
|
+
config_path = pathlib.Path(filepath)
|
|
45
|
+
return cls.from_options(options=_parse_mypy_config(config_path), filepath=config_path)
|
|
46
|
+
|
|
47
|
+
@classmethod
|
|
48
|
+
def from_options(cls, *, options: Mapping[str, object], filepath: pathlib.Path) -> Self:
|
|
49
|
+
"""
|
|
50
|
+
Construct the extra options from the mypy configuration
|
|
51
|
+
"""
|
|
52
|
+
scratch_path = _sanitize_path(filepath, options, "scratch_path", required=True)
|
|
53
|
+
assert scratch_path is not None
|
|
54
|
+
|
|
55
|
+
project_root = _sanitize_path(filepath, options, "project_root")
|
|
56
|
+
if project_root is None:
|
|
57
|
+
project_root = filepath.parent
|
|
58
|
+
|
|
59
|
+
django_settings_module_value = _sanitize_str(
|
|
60
|
+
filepath, options, "django_settings_module", required=True
|
|
61
|
+
)
|
|
62
|
+
assert django_settings_module_value is not None
|
|
63
|
+
django_settings_module = ImportPath(django_settings_module_value)
|
|
64
|
+
|
|
65
|
+
scratch_path.mkdir(parents=True, exist_ok=True)
|
|
66
|
+
|
|
67
|
+
return cls(
|
|
68
|
+
scratch_path=scratch_path,
|
|
69
|
+
project_root=project_root,
|
|
70
|
+
django_settings_module=django_settings_module,
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
def for_report(self) -> dict[str, str]:
|
|
74
|
+
"""
|
|
75
|
+
Get the options that were found to be used for the mypy report_config_data hook
|
|
76
|
+
"""
|
|
77
|
+
return {
|
|
78
|
+
"scratch_path": str(self.scratch_path),
|
|
79
|
+
"project_root": str(self.project_root),
|
|
80
|
+
"django_settings_module": self.django_settings_module,
|
|
81
|
+
"plugin_version": str(VERSION),
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _parse_mypy_config(filepath: pathlib.Path) -> Mapping[str, object]:
|
|
86
|
+
if filepath.suffix == ".toml":
|
|
87
|
+
return _parse_toml_config(filepath)
|
|
88
|
+
else:
|
|
89
|
+
return _parse_ini_config(filepath)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _parse_toml_config(filepath: pathlib.Path) -> Mapping[str, object]:
|
|
93
|
+
try:
|
|
94
|
+
with filepath.open(mode="rb") as f:
|
|
95
|
+
data = tomllib.load(f)
|
|
96
|
+
except (tomllib.TOMLDecodeError, OSError):
|
|
97
|
+
django_stubs_config.exit_with_error(django_stubs_config.COULD_NOT_LOAD_FILE, is_toml=True)
|
|
98
|
+
|
|
99
|
+
if not isinstance(tool := data.get("tool"), Mapping) or not isinstance(
|
|
100
|
+
result := tool.get("django-stubs"), Mapping
|
|
101
|
+
):
|
|
102
|
+
django_stubs_config.exit_with_error(
|
|
103
|
+
django_stubs_config.MISSING_SECTION.format(section="tool.django-stubs"),
|
|
104
|
+
is_toml=True,
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
return result
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _parse_ini_config(filepath: pathlib.Path) -> Mapping[str, object]:
|
|
111
|
+
parser = configparser.ConfigParser()
|
|
112
|
+
try:
|
|
113
|
+
with filepath.open(encoding="utf-8") as f:
|
|
114
|
+
parser.read_file(f, source=str(filepath))
|
|
115
|
+
except (configparser.ParsingError, OSError):
|
|
116
|
+
django_stubs_config.exit_with_error(django_stubs_config.COULD_NOT_LOAD_FILE)
|
|
117
|
+
|
|
118
|
+
section = "mypy.plugins.django-stubs"
|
|
119
|
+
if not parser.has_section(section):
|
|
120
|
+
django_stubs_config.exit_with_error(
|
|
121
|
+
django_stubs_config.MISSING_SECTION.format(section=section)
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
return dict(parser.items("mypy.plugins.django-stubs"))
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _sanitize_str(
|
|
128
|
+
config_path: pathlib.Path,
|
|
129
|
+
options: Mapping[str, object],
|
|
130
|
+
option: str,
|
|
131
|
+
*,
|
|
132
|
+
required: bool = False,
|
|
133
|
+
) -> str | None:
|
|
134
|
+
if not isinstance(value := options.get(option), str):
|
|
135
|
+
if required:
|
|
136
|
+
raise ValueError(
|
|
137
|
+
f"Please specify '{option}' in the django-stubs section of your mypy configuration ({config_path})"
|
|
138
|
+
)
|
|
139
|
+
else:
|
|
140
|
+
return None
|
|
141
|
+
|
|
142
|
+
while value and value.startswith('"'):
|
|
143
|
+
value = value[1:]
|
|
144
|
+
while value and value.endswith('"'):
|
|
145
|
+
value = value[:-1]
|
|
146
|
+
|
|
147
|
+
return value
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _sanitize_path(
|
|
151
|
+
config_path: pathlib.Path,
|
|
152
|
+
options: Mapping[str, object],
|
|
153
|
+
option: str,
|
|
154
|
+
*,
|
|
155
|
+
required: bool = False,
|
|
156
|
+
) -> pathlib.Path | None:
|
|
157
|
+
value = _sanitize_str(config_path, options, option, required=required)
|
|
158
|
+
if value is None:
|
|
159
|
+
return None
|
|
160
|
+
return pathlib.Path(value.replace("$MYPY_CONFIG_FILE_DIR", str(config_path.parent)))
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import pathlib
|
|
2
|
+
import subprocess
|
|
3
|
+
import sys
|
|
4
|
+
import tempfile
|
|
5
|
+
from collections.abc import MutableMapping
|
|
6
|
+
from itertools import chain
|
|
7
|
+
from typing import Generic
|
|
8
|
+
|
|
9
|
+
from mypy.options import Options
|
|
10
|
+
from mypy.plugin import Plugin as MypyPlugin
|
|
11
|
+
|
|
12
|
+
from . import plugin, protocols
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class PluginProvider(Generic[protocols.T_Report]):
|
|
16
|
+
"""
|
|
17
|
+
This can be used to provide both a mypy plugin as well as a __version__ that changes
|
|
18
|
+
when mypy needs to do a full restart.
|
|
19
|
+
|
|
20
|
+
Given either the extended_mypy_django_plugin.plugin.ExtendedMypyStubs class or a subclass
|
|
21
|
+
of that, usage is::
|
|
22
|
+
|
|
23
|
+
from extended_mypy_django_plugin.plugin import ExtendedMypyStubs, PluginProvider, VirtualDependencyHandler
|
|
24
|
+
|
|
25
|
+
plugin = PluginProvider(ExtendedMypyStubs, VirtualDependencyHandler.create_report, locals())
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
previous_version: str
|
|
29
|
+
|
|
30
|
+
def __init__(
|
|
31
|
+
self,
|
|
32
|
+
plugin_cls: type[plugin.ExtendedMypyStubs[protocols.T_Report]],
|
|
33
|
+
virtual_dependency_handler: protocols.VirtualDependencyHandler[protocols.T_Report],
|
|
34
|
+
locals: MutableMapping[str, object],
|
|
35
|
+
/,
|
|
36
|
+
) -> None:
|
|
37
|
+
self.locals = locals
|
|
38
|
+
self.instance: plugin.ExtendedMypyStubs[protocols.T_Report] | None = None
|
|
39
|
+
self.virtual_dependency_handler = virtual_dependency_handler
|
|
40
|
+
self.plugin_cls = plugin_cls
|
|
41
|
+
|
|
42
|
+
def __call__(self, version: str) -> type[MypyPlugin]:
|
|
43
|
+
if self.instance is not None:
|
|
44
|
+
# This only happens when using the mypy daemon
|
|
45
|
+
# and also self.instance is only ever not None after previous_version is set
|
|
46
|
+
# In this case if the options have changed then dmypy will already have restarted
|
|
47
|
+
# So we can rely on the options on our previous instance
|
|
48
|
+
self.set_new_version(
|
|
49
|
+
self.determine_plugin_version(
|
|
50
|
+
options=self.instance.options, previous_version=self.previous_version
|
|
51
|
+
)
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
# Inside dmypy, don't create a new plugin
|
|
55
|
+
return MypyPlugin
|
|
56
|
+
|
|
57
|
+
provider = self
|
|
58
|
+
major, minor, _ = version.split(".", 2)
|
|
59
|
+
|
|
60
|
+
def __init__(
|
|
61
|
+
instance: plugin.ExtendedMypyStubs[protocols.T_Report], options: Options
|
|
62
|
+
) -> None:
|
|
63
|
+
super(instance.__class__, instance).__init__(
|
|
64
|
+
options,
|
|
65
|
+
mypy_version_tuple=(int(major), int(minor)), # type: ignore[call-arg]
|
|
66
|
+
virtual_dependency_handler=self.virtual_dependency_handler,
|
|
67
|
+
)
|
|
68
|
+
provider.set_new_version(instance.virtual_dependency_report.version)
|
|
69
|
+
provider.instance = instance
|
|
70
|
+
|
|
71
|
+
return type("Plugin", (provider.plugin_cls,), {"__init__": __init__})
|
|
72
|
+
|
|
73
|
+
def set_new_version(self, new_version: str) -> None:
|
|
74
|
+
self.previous_version = new_version
|
|
75
|
+
self.locals["__version__"] = new_version
|
|
76
|
+
|
|
77
|
+
def determine_plugin_version(self, *, options: Options, previous_version: str) -> str:
|
|
78
|
+
cmd = [
|
|
79
|
+
sys.executable,
|
|
80
|
+
"-m",
|
|
81
|
+
"extended_mypy_django_plugin.scripts.determine_django_state",
|
|
82
|
+
*(["--config-file", options.config_file] if options.config_file is not None else []),
|
|
83
|
+
*chain.from_iterable(["--mypy-plugin", plugin] for plugin in options.plugins),
|
|
84
|
+
]
|
|
85
|
+
|
|
86
|
+
err: subprocess.CalledProcessError | None = None
|
|
87
|
+
|
|
88
|
+
with tempfile.NamedTemporaryFile() as fle:
|
|
89
|
+
cmd.extend(["--version-file", fle.name])
|
|
90
|
+
|
|
91
|
+
try:
|
|
92
|
+
subprocess.run(cmd, capture_output=True, check=True)
|
|
93
|
+
except subprocess.CalledProcessError as failed:
|
|
94
|
+
err = failed
|
|
95
|
+
else:
|
|
96
|
+
return pathlib.Path(fle.name).read_text().strip()
|
|
97
|
+
|
|
98
|
+
if err.returncode == 2:
|
|
99
|
+
return previous_version
|
|
100
|
+
else:
|
|
101
|
+
message = [
|
|
102
|
+
"",
|
|
103
|
+
"Failed to determine information about the django setup",
|
|
104
|
+
"",
|
|
105
|
+
f" > {' '.join(cmd)}",
|
|
106
|
+
" |",
|
|
107
|
+
]
|
|
108
|
+
if err.stdout:
|
|
109
|
+
for line in err.stdout.splitlines():
|
|
110
|
+
if isinstance(line, bytes):
|
|
111
|
+
line = line.decode()
|
|
112
|
+
message.append(f" | {line}")
|
|
113
|
+
if err.stderr:
|
|
114
|
+
message.append(" |")
|
|
115
|
+
if err.stderr:
|
|
116
|
+
for line in err.stderr.splitlines():
|
|
117
|
+
if isinstance(line, bytes):
|
|
118
|
+
line = line.decode()
|
|
119
|
+
message.append(f" | {line}")
|
|
120
|
+
message.append(" |")
|
|
121
|
+
|
|
122
|
+
if previous_version:
|
|
123
|
+
print("\n".join(message), file=sys.stderr) # noqa: T201
|
|
124
|
+
return previous_version
|
|
125
|
+
else:
|
|
126
|
+
raise RuntimeError("\n".join(message))
|