-
Notifications
You must be signed in to change notification settings - Fork 3
/
autoimport.py
222 lines (190 loc) · 8 KB
/
autoimport.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
import re
from rope.base import builtins
from rope.base import exceptions
from rope.base import libutils
from rope.base import pynames
from rope.base import pyobjects
from rope.base import resources
from rope.base import resourceobserver
from rope.base import taskhandle
from rope.refactor import importutils
class AutoImport(object):
"""A class for finding the module that provides a name
This class maintains a cache of global names in python modules.
Note that this cache is not accurate and might be out of date.
"""
def __init__(self, project, observe=True, underlined=False):
"""Construct an AutoImport object
If `observe` is `True`, listen for project changes and update
the cache.
If `underlined` is `True`, underlined names are cached, too.
"""
self.project = project
self.underlined = underlined
self.names = project.data_files.read_data('globalnames')
if self.names is None:
self.names = {}
project.data_files.add_write_hook(self._write)
# XXX: using a filtered observer
observer = resourceobserver.ResourceObserver(
changed=self._changed, moved=self._moved, removed=self._removed)
if observe:
project.add_observer(observer)
def import_assist(self, starting):
"""Return a list of ``(name, module)`` tuples
This function tries to find modules that have a global name
that starts with `starting`.
"""
# XXX: breaking if gave up! use generators
result = []
for module in self.names:
for global_name in self.names[module]:
if global_name.startswith(starting):
result.append((global_name, module))
return result
def get_modules(self, name):
"""Return the list of modules that have global `name`"""
result = []
for module in self.names:
if name in self.names[module]:
result.append(module)
return result
def get_all_names(self):
"""Return the list of all cached global names"""
result = set()
for module in self.names:
result.update(set(self.names[module]))
return result
def get_name_locations(self, name):
"""Return a list of ``(resource, lineno)`` tuples"""
result = []
for module in self.names:
if name in self.names[module]:
try:
pymodule = self.project.get_module(module)
if name in pymodule:
pyname = pymodule[name]
module, lineno = pyname.get_definition_location()
if module is not None:
resource = module.get_module().get_resource()
if resource is not None and lineno is not None:
result.append((resource, lineno))
except exceptions.ModuleNotFoundError:
pass
return result
def generate_cache(self, resources=None, underlined=None,
task_handle=taskhandle.NullTaskHandle()):
"""Generate global name cache for project files
If `resources` is a list of `rope.base.resource.File`\s, only
those files are searched; otherwise all python modules in the
project are cached.
"""
if resources is None:
resources = self.project.get_python_files()
job_set = task_handle.create_jobset(
'Generatig autoimport cache', len(resources))
for file in resources:
job_set.started_job('Working on <%s>' % file.path)
self.update_resource(file, underlined)
job_set.finished_job()
def generate_modules_cache(self, modules, underlined=None,
task_handle=taskhandle.NullTaskHandle()):
"""Generate global name cache for modules listed in `modules`"""
job_set = task_handle.create_jobset(
'Generatig autoimport cache for modules', len(modules))
for modname in modules:
job_set.started_job('Working on <%s>' % modname)
if modname.endswith('.*'):
mod = self.project.find_module(modname[:-2])
if mod:
for sub in submodules(mod):
self.update_resource(sub, underlined)
else:
self.update_module(modname, underlined)
job_set.finished_job()
def clear_cache(self):
"""Clear all entries in global-name cache
It might be a good idea to use this function before
regenerating global names.
"""
self.names.clear()
def find_insertion_line(self, code):
"""Guess at what line the new import should be inserted"""
match = re.search(r'^(def|class)\s+', code)
if match is not None:
code = code[:match.start()]
try:
pymodule = libutils.get_string_module(self.project, code)
except exceptions.ModuleSyntaxError:
return 1
testmodname = '__rope_testmodule_rope'
importinfo = importutils.NormalImport(((testmodname, None),))
module_imports = importutils.get_module_imports(self.project,
pymodule)
module_imports.add_import(importinfo)
code = module_imports.get_changed_source()
offset = code.index(testmodname)
lineno = code.count('\n', 0, offset) + 1
return lineno
def update_resource(self, resource, underlined=None):
"""Update the cache for global names in `resource`"""
try:
pymodule = self.project.get_pymodule(resource)
modname = self._module_name(resource)
self._add_names(pymodule, modname, underlined)
except exceptions.ModuleSyntaxError:
pass
def update_module(self, modname, underlined=None):
"""Update the cache for global names in `modname` module
`modname` is the name of a module.
"""
try:
pymodule = self.project.get_module(modname)
self._add_names(pymodule, modname, underlined)
except exceptions.ModuleNotFoundError:
pass
def _module_name(self, resource):
return libutils.modname(resource)
def _add_names(self, pymodule, modname, underlined):
if underlined is None:
underlined = self.underlined
globals = []
if isinstance(pymodule, pyobjects.PyDefinedObject):
attributes = pymodule._get_structural_attributes()
else:
attributes = pymodule.get_attributes()
for name, pyname in attributes.items():
if not underlined and name.startswith('_'):
continue
if isinstance(pyname, (pynames.AssignedName, pynames.DefinedName)):
globals.append(name)
if isinstance(pymodule, builtins.BuiltinModule):
globals.append(name)
self.names[modname] = globals
def _write(self):
self.project.data_files.write_data('globalnames', self.names)
def _changed(self, resource):
if not resource.is_folder():
self.update_resource(resource)
def _moved(self, resource, newresource):
if not resource.is_folder():
modname = self._module_name(resource)
if modname in self.names:
del self.names[modname]
self.update_resource(newresource)
def _removed(self, resource):
if not resource.is_folder():
modname = self._module_name(resource)
if modname in self.names:
del self.names[modname]
def submodules(mod):
if isinstance(mod, resources.File):
if mod.name.endswith('.py') and mod.name != '__init__.py':
return set([mod])
return set()
if not mod.has_child('__init__.py'):
return set()
result = set([mod])
for child in mod.get_children():
result |= submodules(child)
return result