rope_py3k / rope / refactor / localtofield.py

from rope.refactor.rename import RenameRefactoring
import rope.codeanalyze
from rope.refactor.change import (ChangeSet, ChangeFileContents,
                                  MoveResource, CreateFolder)


class ConvertLocalToFieldRefactoring(object):
    
    def __init__(self, pycore):
        self.pycore = pycore
    
    def convert_local_variable_to_field(self, resource, offset):
        name = rope.codeanalyze.get_name_at(resource, offset)
        pyname = rope.codeanalyze.get_pyname_at(self.pycore, resource, offset)
        if not self._is_a_method_local(pyname):
            raise rope.exceptions.RefactoringException(
                'Convert local variable to field should be performed on \n'
                'the a local variable of a method.')
        
        pymodule, lineno = pyname.get_definition_location()
        function_scope = pymodule.get_scope().get_inner_scope_for_line(lineno)
        class_scope = function_scope.parent
        if name in class_scope.pyobject.get_attributes():
            raise rope.exceptions.RefactoringException(
                'The field %s already exists' % name)
        
        new_name = self._get_field_name(function_scope.pyobject, name)
        changes = RenameRefactoring(self.pycore).local_rename(resource, offset,
                                                              new_name)
        return changes

    def _get_field_name(self, pyfunction, name):
        self_name = pyfunction.parameters[0]
        new_name = self_name + '.' + name
        return new_name
    
    def _is_a_method_local(self, pyname):
        pymodule, lineno = pyname.get_definition_location()
        holding_scope = pymodule.get_scope().get_inner_scope_for_line(lineno)
        parent = holding_scope.parent
        return isinstance(pyname, rope.pynames.AssignedName) and \
               pyname in holding_scope.get_names().values() and \
               holding_scope.get_kind() == 'Function' and \
               parent is not None and parent.get_kind() == 'Class'
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.