Debian Codegraph @

flufl/testing/imports.py

raw
1 """flake8 plugin."""
2
3 from ast import NodeVisitor
4 from collections import namedtuple
5 from enum import Enum
6
7
8 class ImportType(Enum):
9 non_from = 0
10 from_import = 1
11
12
13 ImportRecord = namedtuple('ImportRecord', 'itype lineno colno, module, names')
14
15
16 NONFROM_FOLLOWS_FROM = 'U401 Non-from import follows from-import'
17 NONFROM_MULTIPLE_NAMES = 'U402 Multiple names on non-from import'
18 NONFROM_SHORTER_FOLLOWS = 'U403 Shorter non-from import follows longer'
19 NONFROM_ALPHA_UNSORTED = (
20 'U404 Same-length non-from imports not sorted alphabetically')
21 NONFROM_EXTRA_BLANK_LINE = (
22 'U405 Unexpected blank line since last non-from import')
23 NONFROM_DOTTED_UNSORTED = (
24 'U406 Dotted non-from import not sorted alphabetically')
25
26 FROMIMPORT_MISSING_BLANK_LINE = (
27 'U411 Expected one blank line since last non-from import')
28 FROMIMPORT_ALPHA_UNSORTED = 'U412 from-import not sorted alphabetically'
29 FROMIMPORT_MULTIPLE = 'U413 Multiple from-imports of same module'
30 FROMIMPORT_NAMES_UNSORTED = (
31 'U414 from-imported names are not sorted alphabetically')
32
33
34 class ImportVisitor(NodeVisitor):
35 def __init__(self):
36 self.imports = []
37
38 def visit_Import(self, node):
39 if node.col_offset != 0:
40 # Ignore nested imports.
41 return
42 names = [alias.name for alias in node.names]
43 self.imports.append(
44 ImportRecord(ImportType.non_from, node.lineno, node.col_offset,
45 None, names))
46
47 def visit_ImportFrom(self, node):
48 if node.col_offset != 0:
49 # Ignore nested imports.
50 return
51 names = [alias.name for alias in node.names]
52 self.imports.append(
53 ImportRecord(ImportType.from_import, node.lineno, node.col_offset,
54 node.module, names))
55
56
57 class ImportOrder:
58 name = 'flufl-import-order'
59 version = '0.2'
60 off_by_default = True
61
62 def __init__(self, tree, filename):
63 self.tree = tree
64 self.filename = filename
65
66 def _error(self, record, error):
67 code, space, text = error.partition(' ')
68 return (record.lineno, record.colno,
69 '{} {}'.format(code, text), ImportOrder)
70
71 def run(self):
72 visitor = ImportVisitor()
73 visitor.visit(self.tree)
74 last_import = None
75 for record in visitor.imports:
76 if last_import is None:
77 last_import = record
78 continue
79 if record.itype is ImportType.non_from:
80 if len(record.names) != 1:
81 yield self._error(record, NONFROM_MULTIPLE_NAMES)
82 if last_import.itype is ImportType.from_import:
83 # If the previous import was a __future__ import, just
84 # ignore the rest of the checks.
85 if last_import.module is '__future__':
86 continue
87 yield self._error(record, NONFROM_FOLLOWS_FROM)
88 # Shorter imports should always precede longer import *except*
89 # when they are dotted imports and everything but the last
90 # path component are the same. In that case, they should be
91 # sorted alphabetically.
92 last_name = last_import.names[0]
93 this_name = record.names[0]
94 if '.' in last_name and '.' in this_name:
95 last_parts = last_name.split('.')
96 this_parts = this_name.split('.')
97 if (last_parts[:-1] == this_parts[:-1] and
98 last_parts[-1] > this_parts[-1]):
99 yield self._error(record, NONFROM_DOTTED_UNSORTED)
100 elif len(last_name) > len(this_name):
101 yield self._error(record, NONFROM_SHORTER_FOLLOWS)
102 # It's also possible that the imports are the same length, in
103 # which case they must be sorted alphabetically.
104 if (len(last_import.names[0]) == len(record.names[0]) and
105 last_import.names[0] > record.names[0]):
106 yield self._error(record, NONFROM_ALPHA_UNSORTED)
107 if last_import.lineno + 1 != record.lineno:
108 yield self._error(record, NONFROM_DOTTED_UNSORTED)
109 else:
110 assert record.itype is ImportType.from_import
111 if (last_import.itype is ImportType.non_from and
112 record.lineno != last_import.lineno + 2):
113 yield self._error(record, FROMIMPORT_MISSING_BLANK_LINE)
114 if last_import.itype is ImportType.non_from:
115 last_import = record
116 continue
117 if last_import.module > record.module:
118 yield self._error(record, FROMIMPORT_ALPHA_UNSORTED)
119 # All imports from the same module should show up in the same
120 # multiline import.
121 if last_import.module == record.module:
122 yield self._error(record, FROMIMPORT_MULTIPLE)
123 # Check the sort order of the imported names.
124 if sorted(record.names) != record.names:
125 yield self._error(record, FROMIMPORT_NAMES_UNSORTED)
126 # How to check for no blank lines between from imports?
127 # Update the last import.
128 last_import = record