-
Notifications
You must be signed in to change notification settings - Fork 0
/
flake8_wot.py
80 lines (60 loc) · 2.92 KB
/
flake8_wot.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import importlib.metadata
from ast import NodeVisitor, AST, ImportFrom, AnnAssign, Assign, FunctionDef, Call
from typing import Generator, Any
OLD_SCHOOL_TYPES = ["Dict", "FrozenSet", "List", "Set", "Tuple"]
def _old_school(type_name: str) -> bool:
return type_name in OLD_SCHOOL_TYPES
class Visitor(NodeVisitor):
def __init__(self):
self.problems: dict[str, list[tuple[int, int, str]]] = {
"WOT001": [],
"WOT002": [],
}
def _report_problem(self, key: str, node: AST, type_name: str):
self.problems[key].append((node.lineno, node.col_offset, type_name))
def visit_AnnAssign(self, node: AnnAssign) -> Any:
if annotation := node.annotation:
if value := getattr(annotation, "value", False):
if type_name := getattr(value, "attr", False):
if _old_school(type_name):
self._report_problem("WOT002", node, type_name)
def visit_Assign(self, node: Assign) -> Any:
if not isinstance(node.value, Call):
if type_name := getattr(node.value, "attr", False):
if _old_school(type_name):
self._report_problem("WOT002", node, type_name)
def visit_Call(self, node: Call) -> Any:
for arg in node.args:
if type_name := getattr(arg, "attr", False):
if _old_school(type_name):
self._report_problem("WOT002", node, type_name)
def visit_FunctionDef(self, node: FunctionDef) -> Any:
if returns := node.returns:
if type_name := getattr(returns, "attr", False):
if _old_school(type_name):
self._report_problem("WOT002", node, type_name)
if args := node.args.args:
for arg in args:
if type_name := getattr(arg.annotation, "attr", False):
if _old_school(type_name):
self._report_problem("WOT002", node, type_name)
def visit_ImportFrom(self, node: ImportFrom) -> None:
for name in node.names:
type_name = name.name
if _old_school(type_name):
self._report_problem("WOT001", node, type_name)
self.generic_visit(node)
class Plugin:
name = __name__
version = importlib.metadata.version(__name__)
def __init__(self, tree: AST) -> None:
self._tree = tree
def _report(self, visitor: Visitor) -> Generator[tuple[int, int, str, type[Any]], None, None]:
for line, col, old_type in visitor.problems["WOT001"]:
yield line, col, f"WOT001 don't import type {old_type}", type(self)
for line, col, old_type in visitor.problems["WOT002"]:
yield line, col, f"WOT002 don't use type typing.{old_type}", type(self)
def run(self) -> Generator[tuple[int, int, str, type[Any]], None, None]:
visitor = Visitor()
visitor.visit(self._tree)
return self._report(visitor)