Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
marvel
GitHub Repository: marvel/qnf
Path: blob/master/elisp/emacs-for-python/rope-dist/rope/contrib/fixmodnames.py
1494 views
1
"""Fix the name of modules
2
3
This module is useful when you want to rename many of the modules in
4
your project. That can happen specially when you want to change their
5
naming style.
6
7
For instance::
8
9
fixer = FixModuleNames(project)
10
changes = fixer.get_changes(fixer=str.lower)
11
project.do(changes)
12
13
Here it renames all modules and packages to use lower-cased chars.
14
You can tell it to use any other style by using the ``fixer``
15
argument.
16
17
"""
18
from rope.base import change, taskhandle
19
from rope.contrib import changestack
20
from rope.refactor import rename
21
22
23
class FixModuleNames(object):
24
25
def __init__(self, project):
26
self.project = project
27
28
def get_changes(self, fixer=str.lower,
29
task_handle=taskhandle.NullTaskHandle()):
30
"""Fix module names
31
32
`fixer` is a function that takes and returns a `str`. Given
33
the name of a module, it should return the fixed name.
34
35
"""
36
stack = changestack.ChangeStack(self.project, 'Fixing module names')
37
jobset = task_handle.create_jobset('Fixing module names',
38
self._count_fixes(fixer) + 1)
39
try:
40
while True:
41
for resource in self._tobe_fixed(fixer):
42
jobset.started_job(resource.path)
43
renamer = rename.Rename(self.project, resource)
44
changes = renamer.get_changes(fixer(self._name(resource)))
45
stack.push(changes)
46
jobset.finished_job()
47
break
48
else:
49
break
50
finally:
51
jobset.started_job('Reverting to original state')
52
stack.pop_all()
53
jobset.finished_job()
54
return stack.merged()
55
56
def _count_fixes(self, fixer):
57
return len(list(self._tobe_fixed(fixer)))
58
59
def _tobe_fixed(self, fixer):
60
for resource in self.project.pycore.get_python_files():
61
modname = self._name(resource)
62
if modname != fixer(modname):
63
yield resource
64
65
def _name(self, resource):
66
modname = resource.name.rsplit('.', 1)[0]
67
if modname == '__init__':
68
modname = resource.parent.name
69
return modname
70
71