Debian Codegraph @

flake8_import_order/__init__.py

raw
1 import ast
2 import sys
3 from collections import namedtuple
4 from enum import IntEnum
5
6 if sys.version_info >= (3, 10):
7 STDLIB_NAMES = sys.stdlib_module_names | {"__main__", "test"}
8 else:
9 from .stdlib_list import STDLIB_NAMES
10
11 from .__about__ import __author__
12 from .__about__ import __copyright__
13 from .__about__ import __email__
14 from .__about__ import __license__
15 from .__about__ import __summary__
16 from .__about__ import __title__
17 from .__about__ import __uri__
18 from .__about__ import __version__
19
20 __all__ = [
21 "__title__",
22 "__summary__",
23 "__uri__",
24 "__version__",
25 "__author__",
26 "__email__",
27 "__license__",
28 "__copyright__",
29 ]
30
31 DEFAULT_IMPORT_ORDER_STYLE = "cryptography"
32
33 ClassifiedImport = namedtuple(
34 "ClassifiedImport",
35 [
36 "type",
37 "is_from",
38 "modules",
39 "names",
40 "lineno",
41 "end_lineno",
42 "level",
43 "package",
44 "type_checking",
45 ],
46 )
47 NewLine = namedtuple("NewLine", ["lineno"])
48
49
50 class ImportType(IntEnum):
51 FUTURE = 0
52 STDLIB = 10
53 THIRD_PARTY = 20
54 APPLICATION_PACKAGE = 30
55 APPLICATION = 40
56 APPLICATION_RELATIVE = 50
57 MIXED = -1
58
59
60 def get_package_names(name):
61 tree = ast.parse(name)
62 parts = []
63 for node in ast.walk(tree):
64 if isinstance(node, ast.Attribute):
65 parts.append(node.attr)
66 if isinstance(node, ast.Name):
67 parts.append(node.id)
68
69 if not parts:
70 return []
71
72 last_package_name = parts.pop()
73 package_names = [last_package_name]
74
75 for part in reversed(parts):
76 last_package_name = f"{last_package_name}.{part}"
77 package_names.append(last_package_name)
78
79 return package_names
80
81
82 def root_package_name(name):
83 tree = ast.parse(name)
84 for node in ast.walk(tree):
85 if isinstance(node, ast.Name):
86 return node.id
87 else:
88 return None
89
90
91 class ImportVisitor(ast.NodeVisitor):
92
93 def __init__(self, application_import_names, application_package_names):
94 self.imports = []
95 self.application_import_names = frozenset(application_import_names)
96 self.application_package_names = frozenset(application_package_names)
97
98 def generic_visit(self, node):
99 for child in ast.iter_child_nodes(node):
100 child.parent = node
101 return super().generic_visit(node)
102
103 def visit_Import(self, node): # noqa: N802
104 if node.col_offset == 0 or self._type_checking_import(node):
105 modules = [alias.name for alias in node.names]
106 types_ = {self._classify_type(module) for module in modules}
107 if len(types_) == 1:
108 type_ = types_.pop()
109 else:
110 type_ = ImportType.MIXED
111 classified_import = ClassifiedImport(
112 type_,
113 False,
114 modules,
115 [],
116 node.lineno,
117 node.end_lineno,
118 0,
119 root_package_name(modules[0]),
120 self._type_checking_import(node),
121 )
122 self.imports.append(classified_import)
123
124 def visit_ImportFrom(self, node): # noqa: N802
125 if node.col_offset == 0 or self._type_checking_import(node):
126 module = node.module or ""
127 if node.level > 0:
128 type_ = ImportType.APPLICATION_RELATIVE
129 else:
130 type_ = self._classify_type(module)
131 names = [alias.name for alias in node.names]
132 classified_import = ClassifiedImport(
133 type_,
134 True,
135 [module],
136 names,
137 node.lineno,
138 node.end_lineno,
139 node.level,
140 root_package_name(module),
141 self._type_checking_import(node),
142 )
143 self.imports.append(classified_import)
144
145 def _type_checking_import(self, node):
146 return isinstance(node.parent, ast.If) and (
147 (
148 isinstance(node.parent.test, ast.Name)
149 and node.parent.test.id == "TYPE_CHECKING"
150 )
151 or (
152 isinstance(node.parent.test, ast.Attribute)
153 and isinstance(node.parent.test.value, ast.Name)
154 and node.parent.test.value.id in {"t", "typing"}
155 and getattr(node.parent.test, "attr", "") == "TYPE_CHECKING"
156 )
157 )
158
159 def _classify_type(self, module):
160 package_names = get_package_names(module)
161
162 # Walk through package names from most-specific to least-specific,
163 # taking the first match found.
164 for package in reversed(package_names):
165 if package == "__future__":
166 return ImportType.FUTURE
167 elif package in self.application_import_names:
168 return ImportType.APPLICATION
169 elif package in self.application_package_names:
170 return ImportType.APPLICATION_PACKAGE
171 elif package in STDLIB_NAMES:
172 return ImportType.STDLIB
173
174 # Not future, stdlib or an application import.
175 # Must be 3rd party.
176 return ImportType.THIRD_PARTY