author | Chris Jerdonek <chris.jerdonek@gmail.com> |
Sun, 22 Dec 2013 21:20:38 -0800 | |
changeset 20198 | f5393a9dc4e5 |
parent 20197 | 761f2929a6ad |
child 20200 | 532fa12033e1 |
permissions | -rw-r--r-- |
20036 | 1 |
import ast |
2 |
import os |
|
3 |
import sys |
|
4 |
||
20198
f5393a9dc4e5
import-checker: make test-module-imports.t work using virtualenv (issue4129)
Chris Jerdonek <chris.jerdonek@gmail.com>
parents:
20197
diff
changeset
|
5 |
# Import a minimal set of stdlib modules needed for list_stdlib_modules() |
f5393a9dc4e5
import-checker: make test-module-imports.t work using virtualenv (issue4129)
Chris Jerdonek <chris.jerdonek@gmail.com>
parents:
20197
diff
changeset
|
6 |
# to work when run from a virtualenv. The modules were chosen empirically |
f5393a9dc4e5
import-checker: make test-module-imports.t work using virtualenv (issue4129)
Chris Jerdonek <chris.jerdonek@gmail.com>
parents:
20197
diff
changeset
|
7 |
# so that the return value matches the return value without virtualenv. |
f5393a9dc4e5
import-checker: make test-module-imports.t work using virtualenv (issue4129)
Chris Jerdonek <chris.jerdonek@gmail.com>
parents:
20197
diff
changeset
|
8 |
import BaseHTTPServer |
f5393a9dc4e5
import-checker: make test-module-imports.t work using virtualenv (issue4129)
Chris Jerdonek <chris.jerdonek@gmail.com>
parents:
20197
diff
changeset
|
9 |
import zlib |
f5393a9dc4e5
import-checker: make test-module-imports.t work using virtualenv (issue4129)
Chris Jerdonek <chris.jerdonek@gmail.com>
parents:
20197
diff
changeset
|
10 |
|
20036 | 11 |
def dotted_name_of_path(path): |
12 |
"""Given a relative path to a source file, return its dotted module name. |
|
13 |
||
14 |
||
15 |
>>> dotted_name_of_path('mercurial/error.py') |
|
16 |
'mercurial.error' |
|
17 |
""" |
|
18 |
parts = path.split('/') |
|
19 |
parts[-1] = parts[-1][:-3] # remove .py |
|
20 |
return '.'.join(parts) |
|
21 |
||
22 |
||
23 |
def list_stdlib_modules(): |
|
24 |
"""List the modules present in the stdlib. |
|
25 |
||
26 |
>>> mods = set(list_stdlib_modules()) |
|
27 |
>>> 'BaseHTTPServer' in mods |
|
28 |
True |
|
29 |
||
30 |
os.path isn't really a module, so it's missing: |
|
31 |
||
32 |
>>> 'os.path' in mods |
|
33 |
False |
|
34 |
||
35 |
sys requires special treatment, because it's baked into the |
|
36 |
interpreter, but it should still appear: |
|
37 |
||
38 |
>>> 'sys' in mods |
|
39 |
True |
|
40 |
||
41 |
>>> 'collections' in mods |
|
42 |
True |
|
43 |
||
44 |
>>> 'cStringIO' in mods |
|
45 |
True |
|
46 |
""" |
|
47 |
for m in sys.builtin_module_names: |
|
48 |
yield m |
|
49 |
# These modules only exist on windows, but we should always |
|
50 |
# consider them stdlib. |
|
51 |
for m in ['msvcrt', '_winreg']: |
|
52 |
yield m |
|
53 |
# These get missed too |
|
54 |
for m in 'ctypes', 'email': |
|
55 |
yield m |
|
56 |
yield 'builtins' # python3 only |
|
20197
761f2929a6ad
import-checker: refactor sys.path prefix check (issue4129)
Chris Jerdonek <chris.jerdonek@gmail.com>
parents:
20038
diff
changeset
|
57 |
stdlib_prefixes = set([sys.prefix, sys.exec_prefix]) |
20198
f5393a9dc4e5
import-checker: make test-module-imports.t work using virtualenv (issue4129)
Chris Jerdonek <chris.jerdonek@gmail.com>
parents:
20197
diff
changeset
|
58 |
# We need to supplement the list of prefixes for the search to work |
f5393a9dc4e5
import-checker: make test-module-imports.t work using virtualenv (issue4129)
Chris Jerdonek <chris.jerdonek@gmail.com>
parents:
20197
diff
changeset
|
59 |
# when run from within a virtualenv. |
f5393a9dc4e5
import-checker: make test-module-imports.t work using virtualenv (issue4129)
Chris Jerdonek <chris.jerdonek@gmail.com>
parents:
20197
diff
changeset
|
60 |
for mod in (BaseHTTPServer, zlib): |
f5393a9dc4e5
import-checker: make test-module-imports.t work using virtualenv (issue4129)
Chris Jerdonek <chris.jerdonek@gmail.com>
parents:
20197
diff
changeset
|
61 |
try: |
f5393a9dc4e5
import-checker: make test-module-imports.t work using virtualenv (issue4129)
Chris Jerdonek <chris.jerdonek@gmail.com>
parents:
20197
diff
changeset
|
62 |
# Not all module objects have a __file__ attribute. |
f5393a9dc4e5
import-checker: make test-module-imports.t work using virtualenv (issue4129)
Chris Jerdonek <chris.jerdonek@gmail.com>
parents:
20197
diff
changeset
|
63 |
filename = mod.__file__ |
f5393a9dc4e5
import-checker: make test-module-imports.t work using virtualenv (issue4129)
Chris Jerdonek <chris.jerdonek@gmail.com>
parents:
20197
diff
changeset
|
64 |
except AttributeError: |
f5393a9dc4e5
import-checker: make test-module-imports.t work using virtualenv (issue4129)
Chris Jerdonek <chris.jerdonek@gmail.com>
parents:
20197
diff
changeset
|
65 |
continue |
f5393a9dc4e5
import-checker: make test-module-imports.t work using virtualenv (issue4129)
Chris Jerdonek <chris.jerdonek@gmail.com>
parents:
20197
diff
changeset
|
66 |
dirname = os.path.dirname(filename) |
f5393a9dc4e5
import-checker: make test-module-imports.t work using virtualenv (issue4129)
Chris Jerdonek <chris.jerdonek@gmail.com>
parents:
20197
diff
changeset
|
67 |
for prefix in stdlib_prefixes: |
f5393a9dc4e5
import-checker: make test-module-imports.t work using virtualenv (issue4129)
Chris Jerdonek <chris.jerdonek@gmail.com>
parents:
20197
diff
changeset
|
68 |
if dirname.startswith(prefix): |
f5393a9dc4e5
import-checker: make test-module-imports.t work using virtualenv (issue4129)
Chris Jerdonek <chris.jerdonek@gmail.com>
parents:
20197
diff
changeset
|
69 |
# Then this directory is redundant. |
f5393a9dc4e5
import-checker: make test-module-imports.t work using virtualenv (issue4129)
Chris Jerdonek <chris.jerdonek@gmail.com>
parents:
20197
diff
changeset
|
70 |
break |
f5393a9dc4e5
import-checker: make test-module-imports.t work using virtualenv (issue4129)
Chris Jerdonek <chris.jerdonek@gmail.com>
parents:
20197
diff
changeset
|
71 |
else: |
f5393a9dc4e5
import-checker: make test-module-imports.t work using virtualenv (issue4129)
Chris Jerdonek <chris.jerdonek@gmail.com>
parents:
20197
diff
changeset
|
72 |
stdlib_prefixes.add(dirname) |
20036 | 73 |
for libpath in sys.path: |
20197
761f2929a6ad
import-checker: refactor sys.path prefix check (issue4129)
Chris Jerdonek <chris.jerdonek@gmail.com>
parents:
20038
diff
changeset
|
74 |
# We want to walk everything in sys.path that starts with something |
761f2929a6ad
import-checker: refactor sys.path prefix check (issue4129)
Chris Jerdonek <chris.jerdonek@gmail.com>
parents:
20038
diff
changeset
|
75 |
# in stdlib_prefixes. |
761f2929a6ad
import-checker: refactor sys.path prefix check (issue4129)
Chris Jerdonek <chris.jerdonek@gmail.com>
parents:
20038
diff
changeset
|
76 |
for prefix in stdlib_prefixes: |
761f2929a6ad
import-checker: refactor sys.path prefix check (issue4129)
Chris Jerdonek <chris.jerdonek@gmail.com>
parents:
20038
diff
changeset
|
77 |
if libpath.startswith(prefix): |
761f2929a6ad
import-checker: refactor sys.path prefix check (issue4129)
Chris Jerdonek <chris.jerdonek@gmail.com>
parents:
20038
diff
changeset
|
78 |
break |
761f2929a6ad
import-checker: refactor sys.path prefix check (issue4129)
Chris Jerdonek <chris.jerdonek@gmail.com>
parents:
20038
diff
changeset
|
79 |
else: |
20036 | 80 |
continue |
81 |
if 'site-packages' in libpath: |
|
82 |
continue |
|
83 |
for top, dirs, files in os.walk(libpath): |
|
84 |
for name in files: |
|
85 |
if name == '__init__.py': |
|
86 |
continue |
|
87 |
if not (name.endswith('.py') or name.endswith('.so')): |
|
88 |
continue |
|
89 |
full_path = os.path.join(top, name) |
|
90 |
if 'site-packages' in full_path: |
|
91 |
continue |
|
92 |
rel_path = full_path[len(libpath) + 1:] |
|
93 |
mod = dotted_name_of_path(rel_path) |
|
94 |
yield mod |
|
95 |
||
96 |
stdlib_modules = set(list_stdlib_modules()) |
|
97 |
||
20037
957b43371928
import-checker: ignore nested imports
Augie Fackler <raf@durin42.com>
parents:
20036
diff
changeset
|
98 |
def imported_modules(source, ignore_nested=False): |
20036 | 99 |
"""Given the source of a file as a string, yield the names |
100 |
imported by that file. |
|
101 |
||
20037
957b43371928
import-checker: ignore nested imports
Augie Fackler <raf@durin42.com>
parents:
20036
diff
changeset
|
102 |
Args: |
957b43371928
import-checker: ignore nested imports
Augie Fackler <raf@durin42.com>
parents:
20036
diff
changeset
|
103 |
source: The python source to examine as a string. |
957b43371928
import-checker: ignore nested imports
Augie Fackler <raf@durin42.com>
parents:
20036
diff
changeset
|
104 |
ignore_nested: If true, import statements that do not start in |
957b43371928
import-checker: ignore nested imports
Augie Fackler <raf@durin42.com>
parents:
20036
diff
changeset
|
105 |
column zero will be ignored. |
957b43371928
import-checker: ignore nested imports
Augie Fackler <raf@durin42.com>
parents:
20036
diff
changeset
|
106 |
|
957b43371928
import-checker: ignore nested imports
Augie Fackler <raf@durin42.com>
parents:
20036
diff
changeset
|
107 |
Returns: |
957b43371928
import-checker: ignore nested imports
Augie Fackler <raf@durin42.com>
parents:
20036
diff
changeset
|
108 |
A list of module names imported by the given source. |
957b43371928
import-checker: ignore nested imports
Augie Fackler <raf@durin42.com>
parents:
20036
diff
changeset
|
109 |
|
957b43371928
import-checker: ignore nested imports
Augie Fackler <raf@durin42.com>
parents:
20036
diff
changeset
|
110 |
>>> sorted(imported_modules( |
20036 | 111 |
... 'import foo ; from baz import bar; import foo.qux')) |
20037
957b43371928
import-checker: ignore nested imports
Augie Fackler <raf@durin42.com>
parents:
20036
diff
changeset
|
112 |
['baz.bar', 'foo', 'foo.qux'] |
957b43371928
import-checker: ignore nested imports
Augie Fackler <raf@durin42.com>
parents:
20036
diff
changeset
|
113 |
>>> sorted(imported_modules( |
957b43371928
import-checker: ignore nested imports
Augie Fackler <raf@durin42.com>
parents:
20036
diff
changeset
|
114 |
... '''import foo |
957b43371928
import-checker: ignore nested imports
Augie Fackler <raf@durin42.com>
parents:
20036
diff
changeset
|
115 |
... def wat(): |
957b43371928
import-checker: ignore nested imports
Augie Fackler <raf@durin42.com>
parents:
20036
diff
changeset
|
116 |
... import bar |
957b43371928
import-checker: ignore nested imports
Augie Fackler <raf@durin42.com>
parents:
20036
diff
changeset
|
117 |
... ''', ignore_nested=True)) |
957b43371928
import-checker: ignore nested imports
Augie Fackler <raf@durin42.com>
parents:
20036
diff
changeset
|
118 |
['foo'] |
20036 | 119 |
""" |
120 |
for node in ast.walk(ast.parse(source)): |
|
20037
957b43371928
import-checker: ignore nested imports
Augie Fackler <raf@durin42.com>
parents:
20036
diff
changeset
|
121 |
if ignore_nested and getattr(node, 'col_offset', 0) > 0: |
957b43371928
import-checker: ignore nested imports
Augie Fackler <raf@durin42.com>
parents:
20036
diff
changeset
|
122 |
continue |
20036 | 123 |
if isinstance(node, ast.Import): |
124 |
for n in node.names: |
|
125 |
yield n.name |
|
126 |
elif isinstance(node, ast.ImportFrom): |
|
127 |
prefix = node.module + '.' |
|
128 |
for n in node.names: |
|
129 |
yield prefix + n.name |
|
130 |
||
131 |
def verify_stdlib_on_own_line(source): |
|
132 |
"""Given some python source, verify that stdlib imports are done |
|
133 |
in separate statements from relative local module imports. |
|
134 |
||
135 |
Observing this limitation is important as it works around an |
|
136 |
annoying lib2to3 bug in relative import rewrites: |
|
137 |
http://bugs.python.org/issue19510. |
|
138 |
||
139 |
>>> list(verify_stdlib_on_own_line('import sys, foo')) |
|
140 |
['mixed stdlib and relative imports:\\n foo, sys'] |
|
141 |
>>> list(verify_stdlib_on_own_line('import sys, os')) |
|
142 |
[] |
|
143 |
>>> list(verify_stdlib_on_own_line('import foo, bar')) |
|
144 |
[] |
|
145 |
""" |
|
146 |
for node in ast.walk(ast.parse(source)): |
|
147 |
if isinstance(node, ast.Import): |
|
148 |
from_stdlib = {} |
|
149 |
for n in node.names: |
|
150 |
from_stdlib[n.name] = n.name in stdlib_modules |
|
151 |
num_std = len([x for x in from_stdlib.values() if x]) |
|
152 |
if num_std not in (len(from_stdlib.values()), 0): |
|
153 |
yield ('mixed stdlib and relative imports:\n %s' % |
|
154 |
', '.join(sorted(from_stdlib.iterkeys()))) |
|
155 |
||
156 |
class CircularImport(Exception): |
|
157 |
pass |
|
158 |
||
159 |
||
160 |
def cyclekey(names): |
|
161 |
return tuple(sorted(set(names))) |
|
162 |
||
163 |
def check_one_mod(mod, imports, path=None, ignore=None): |
|
164 |
if path is None: |
|
165 |
path = [] |
|
166 |
if ignore is None: |
|
167 |
ignore = [] |
|
168 |
path = path + [mod] |
|
169 |
for i in sorted(imports.get(mod, [])): |
|
170 |
if i not in stdlib_modules: |
|
171 |
i = mod.rsplit('.', 1)[0] + '.' + i |
|
172 |
if i in path: |
|
173 |
firstspot = path.index(i) |
|
174 |
cycle = path[firstspot:] + [i] |
|
175 |
if cyclekey(cycle) not in ignore: |
|
176 |
raise CircularImport(cycle) |
|
177 |
continue |
|
178 |
check_one_mod(i, imports, path=path, ignore=ignore) |
|
179 |
||
20038
c65a6937b828
import-checker: try a little harder to show fewer cycles
Augie Fackler <raf@durin42.com>
parents:
20037
diff
changeset
|
180 |
def rotatecycle(cycle): |
c65a6937b828
import-checker: try a little harder to show fewer cycles
Augie Fackler <raf@durin42.com>
parents:
20037
diff
changeset
|
181 |
"""arrange a cycle so that the lexicographically first module listed first |
c65a6937b828
import-checker: try a little harder to show fewer cycles
Augie Fackler <raf@durin42.com>
parents:
20037
diff
changeset
|
182 |
|
c65a6937b828
import-checker: try a little harder to show fewer cycles
Augie Fackler <raf@durin42.com>
parents:
20037
diff
changeset
|
183 |
>>> rotatecycle(['foo', 'bar', 'foo']) |
c65a6937b828
import-checker: try a little harder to show fewer cycles
Augie Fackler <raf@durin42.com>
parents:
20037
diff
changeset
|
184 |
['bar', 'foo', 'bar'] |
c65a6937b828
import-checker: try a little harder to show fewer cycles
Augie Fackler <raf@durin42.com>
parents:
20037
diff
changeset
|
185 |
""" |
c65a6937b828
import-checker: try a little harder to show fewer cycles
Augie Fackler <raf@durin42.com>
parents:
20037
diff
changeset
|
186 |
lowest = min(cycle) |
c65a6937b828
import-checker: try a little harder to show fewer cycles
Augie Fackler <raf@durin42.com>
parents:
20037
diff
changeset
|
187 |
idx = cycle.index(lowest) |
c65a6937b828
import-checker: try a little harder to show fewer cycles
Augie Fackler <raf@durin42.com>
parents:
20037
diff
changeset
|
188 |
return cycle[idx:] + cycle[1:idx] + [lowest] |
20036 | 189 |
|
190 |
def find_cycles(imports): |
|
191 |
"""Find cycles in an already-loaded import graph. |
|
192 |
||
193 |
>>> imports = {'top.foo': ['bar', 'os.path', 'qux'], |
|
194 |
... 'top.bar': ['baz', 'sys'], |
|
195 |
... 'top.baz': ['foo'], |
|
196 |
... 'top.qux': ['foo']} |
|
197 |
>>> print '\\n'.join(sorted(find_cycles(imports))) |
|
20038
c65a6937b828
import-checker: try a little harder to show fewer cycles
Augie Fackler <raf@durin42.com>
parents:
20037
diff
changeset
|
198 |
top.bar -> top.baz -> top.foo -> top.bar -> top.bar |
c65a6937b828
import-checker: try a little harder to show fewer cycles
Augie Fackler <raf@durin42.com>
parents:
20037
diff
changeset
|
199 |
top.foo -> top.qux -> top.foo -> top.foo |
20036 | 200 |
""" |
201 |
cycles = {} |
|
202 |
for mod in sorted(imports.iterkeys()): |
|
203 |
try: |
|
204 |
check_one_mod(mod, imports, ignore=cycles) |
|
205 |
except CircularImport, e: |
|
206 |
cycle = e.args[0] |
|
207 |
cycles[cyclekey(cycle)] = ' -> '.join(rotatecycle(cycle)) |
|
208 |
return cycles.values() |
|
209 |
||
210 |
def _cycle_sortkey(c): |
|
211 |
return len(c), c |
|
212 |
||
213 |
def main(argv): |
|
214 |
if len(argv) < 2: |
|
215 |
print 'Usage: %s file [file] [file] ...' |
|
216 |
return 1 |
|
217 |
used_imports = {} |
|
218 |
any_errors = False |
|
219 |
for source_path in argv[1:]: |
|
220 |
f = open(source_path) |
|
221 |
modname = dotted_name_of_path(source_path) |
|
222 |
src = f.read() |
|
20037
957b43371928
import-checker: ignore nested imports
Augie Fackler <raf@durin42.com>
parents:
20036
diff
changeset
|
223 |
used_imports[modname] = sorted( |
957b43371928
import-checker: ignore nested imports
Augie Fackler <raf@durin42.com>
parents:
20036
diff
changeset
|
224 |
imported_modules(src, ignore_nested=True)) |
20036 | 225 |
for error in verify_stdlib_on_own_line(src): |
226 |
any_errors = True |
|
227 |
print source_path, error |
|
228 |
f.close() |
|
229 |
cycles = find_cycles(used_imports) |
|
230 |
if cycles: |
|
231 |
firstmods = set() |
|
232 |
for c in sorted(cycles, key=_cycle_sortkey): |
|
233 |
first = c.split()[0] |
|
234 |
# As a rough cut, ignore any cycle that starts with the |
|
235 |
# same module as some other cycle. Otherwise we see lots |
|
236 |
# of cycles that are effectively duplicates. |
|
237 |
if first in firstmods: |
|
238 |
continue |
|
239 |
print 'Import cycle:', c |
|
240 |
firstmods.add(first) |
|
241 |
any_errors = True |
|
242 |
return not any_errors |
|
243 |
||
244 |
if __name__ == '__main__': |
|
245 |
sys.exit(int(main(sys.argv))) |