Debian Codegraph @

flake8_import_order/styles.py

raw
1 import importlib.metadata
2 from collections import namedtuple
3
4 from flake8_import_order import ClassifiedImport
5 from flake8_import_order import ImportType
6 from flake8_import_order import NewLine
7
8 Error = namedtuple("Error", ["lineno", "code", "message"])
9
10
11 def list_entry_points():
12 entry_points = importlib.metadata.entry_points()
13 if not hasattr(entry_points, "select"):
14 return entry_points.get("flake8_import_order.styles", [])
15 return entry_points.select(group="flake8_import_order.styles")
16
17
18 def lookup_entry_point(name):
19 for style in list_entry_points():
20 if style.name == name:
21 return style
22
23 raise LookupError(f"Unknown style {name}")
24
25
26 class Style:
27
28 accepts_application_package_names = False
29
30 def __init__(self, nodes):
31 self.nodes = nodes
32
33 def check(self):
34 previous = None
35 previous_import = None
36 for current in self.nodes:
37 if isinstance(current, ClassifiedImport):
38 yield from self._check(previous_import, previous, current)
39 previous_import = current
40 previous = current
41
42 def _check(self, previous_import, previous, current_import):
43 yield from self._check_I666(current_import)
44 yield from self._check_I101(current_import)
45 if (
46 previous_import is not None
47 and not previous_import.type_checking
48 and current_import.type_checking
49 ):
50 yield from self._check_I300(previous_import, current_import)
51 previous_import = None
52 if previous_import is not None:
53 yield from self._check_I100(previous_import, current_import)
54 yield from self._check_I201(
55 previous_import, previous, current_import
56 )
57 yield from self._check_I202(
58 previous_import, previous, current_import
59 )
60
61 def _check_I666(self, current_import): # noqa: N802
62 if current_import.type == ImportType.MIXED:
63 yield Error(
64 current_import.lineno,
65 "I666",
66 "Import statement mixes groups",
67 )
68
69 def _check_I101(self, current_import): # noqa: N802
70 correct_names = self.sorted_names(current_import.names)
71 if correct_names != current_import.names:
72 corrected = ", ".join(correct_names)
73 yield Error(
74 current_import.lineno,
75 "I101",
76 "Imported names are in the wrong order. "
77 "Should be {}".format(corrected),
78 )
79
80 def _check_I300(self, previous_import, current_import): # noqa: N802
81 if current_import.lineno - previous_import.end_lineno != 3:
82 yield Error(
83 current_import.lineno,
84 "I300",
85 "TYPE_CHECKING block should have one newline above.",
86 )
87
88 def _check_I100(self, previous_import, current_import): # noqa: N802
89 previous_key = self.import_key(previous_import)
90 current_key = self.import_key(current_import)
91 if previous_key > current_key:
92 message = (
93 "Import statements are in the wrong order. "
94 "'{}' should be before '{}'"
95 ).format(
96 self._explain_import(current_import),
97 self._explain_import(previous_import),
98 )
99 same_section = self.same_section(
100 previous_import,
101 current_import,
102 )
103 if not same_section:
104 message = f"{message} and in a different group."
105 yield Error(current_import.lineno, "I100", message)
106
107 def _check_I201( # noqa: N802
108 self, previous_import, previous, current_import
109 ):
110 same_section = self.same_section(previous_import, current_import)
111 has_newline = isinstance(previous, NewLine)
112 if not same_section and not has_newline:
113 yield Error(
114 current_import.lineno,
115 "I201",
116 "Missing newline between import groups. {}".format(
117 self._explain_grouping(
118 current_import,
119 previous_import,
120 )
121 ),
122 )
123
124 def _check_I202( # noqa: N802
125 self, previous_import, previous, current_import
126 ):
127 same_section = self.same_section(previous_import, current_import)
128 has_newline = isinstance(previous, NewLine)
129 if same_section and has_newline:
130 yield Error(
131 current_import.lineno,
132 "I202",
133 "Additional newline in a group of imports. {}".format(
134 self._explain_grouping(
135 current_import,
136 previous_import,
137 )
138 ),
139 )
140
141 @staticmethod
142 def sorted_names(names):
143 return names
144
145 @staticmethod
146 def import_key(import_):
147 return (import_.type,)
148
149 @staticmethod
150 def same_section(previous, current):
151 same_type = current.type == previous.type
152 both_first = {previous.type, current.type} <= {
153 ImportType.APPLICATION,
154 ImportType.APPLICATION_RELATIVE,
155 }
156 return same_type or both_first
157
158 @staticmethod
159 def _explain_import(import_):
160 if import_.is_from:
161 return "from {}{} import {}".format(
162 import_.level * ".",
163 ", ".join(import_.modules),
164 ", ".join(import_.names),
165 )
166 else:
167 return "import {}".format(", ".join(import_.modules))
168
169 @staticmethod
170 def _explain_grouping(current_import, previous_import):
171 return (
172 "'{}' is identified as {} and " "'{}' is identified as {}."
173 ).format(
174 Style._explain_import(current_import),
175 current_import.type.name.title().replace("_", " "),
176 Style._explain_import(previous_import),
177 previous_import.type.name.title().replace("_", " "),
178 )
179
180
181 class PEP8(Style):
182 pass
183
184
185 class Google(Style):
186
187 @staticmethod
188 def sorted_names(names):
189 return sorted(names, key=Google.name_key)
190
191 @staticmethod
192 def name_key(name):
193 return (name.lower(), name)
194
195 @staticmethod
196 def import_key(import_):
197 modules = [Google.name_key(module) for module in import_.modules]
198 names = [Google.name_key(name) for name in import_.names]
199 return (import_.type, import_.level, modules, names)
200
201
202 class AppNexus(Google):
203 accepts_application_package_names = True
204
205
206 class Smarkets(Style):
207
208 @staticmethod
209 def sorted_names(names):
210 return sorted(names, key=Smarkets.name_key)
211
212 @staticmethod
213 def name_key(name):
214 return (name.lower(), name)
215
216 @staticmethod
217 def import_key(import_):
218 modules = [Smarkets.name_key(module) for module in import_.modules]
219 names = [Smarkets.name_key(name) for name in import_.names]
220 return (import_.type, import_.is_from, import_.level, modules, names)
221
222
223 class Edited(Smarkets):
224 accepts_application_package_names = True
225
226 def _check_I202( # noqa: N802
227 self, previous_import, previous, current_import
228 ):
229 same_section = self.same_section(previous_import, current_import)
230 has_newline = isinstance(previous, NewLine)
231 optional_split = (
232 current_import.is_from and not previous_import.is_from
233 )
234 if same_section and has_newline and not optional_split:
235 yield Error(
236 current_import.lineno,
237 "I202",
238 "Additional newline in a group of imports. {}".format(
239 self._explain_grouping(
240 current_import,
241 previous_import,
242 )
243 ),
244 )
245
246 @staticmethod
247 def same_section(previous, current):
248 return current.type == previous.type
249
250
251 class PyCharm(Smarkets):
252 @staticmethod
253 def sorted_names(names):
254 return sorted(names)
255
256 @staticmethod
257 def import_key(import_):
258 return (
259 import_.type,
260 import_.is_from,
261 import_.level,
262 import_.modules,
263 import_.names,
264 )
265
266
267 class ISort(PyCharm):
268 @staticmethod
269 def name_key(name):
270 # Group by CONSTANT, Class, func.
271 group = 0 if name.isupper() else 2 if name.islower() else 1
272 return (group, name)
273
274 @staticmethod
275 def sorted_names(names):
276 return sorted(names, key=ISort.name_key)
277
278
279 class Cryptography(Style):
280
281 @staticmethod
282 def sorted_names(names):
283 return sorted(names)
284
285 @staticmethod
286 def import_key(import_):
287 if import_.type in {ImportType.THIRD_PARTY, ImportType.APPLICATION}:
288 return (
289 import_.type,
290 import_.package,
291 import_.is_from,
292 import_.level,
293 import_.modules,
294 import_.names,
295 )
296 else:
297 return (
298 import_.type,
299 "",
300 import_.is_from,
301 import_.level,
302 import_.modules,
303 import_.names,
304 )
305
306 @staticmethod
307 def same_section(previous, current):
308 app_or_third = current.type in {
309 ImportType.THIRD_PARTY,
310 ImportType.APPLICATION,
311 }
312 same_type = current.type == previous.type
313 both_relative = (
314 previous.type == current.type == ImportType.APPLICATION_RELATIVE
315 )
316 same_package = previous.package == current.package
317 return (not app_or_third and same_type or both_relative) or (
318 app_or_third and same_package
319 )