Пример #1
0
def rename_symbol(_, main_project, multiproj, other_projects, file_path,
                  cursor_position, replacement):
    """
    Renames symbol under cusror.
    """
    try:
        main_project.validate()
        module = libutils.path_to_resource(main_project, file_path)
        if multiproj:
            # we need to rename cross project
            crossrename = multiproject.MultiProjectRefactoring(
                Rename, other_projects)
            renamer = crossrename(main_project, module, cursor_position)
            pending_changes = renamer.get_all_changes(replacement, docs=True)
        else:
            renamer = Rename(main_project, module, cursor_position)
            pending_changes = renamer.get_changes(replacement, docs=True)
        return multiproj, pending_changes
    except RopeError as e:
        error = RefactoringError()
        error.exc = str(e)
        error.traceback = traceback.format_exc()
        error.critical = False
        return error
    except Exception as e:
        error = RefactoringError()
        error.exc = str(e)
        error.traceback = traceback.format_exc()
        error.critical = True
        return error
Пример #2
0
 def refactor_rename_at_point(self, offset, new_name, in_hierarchy, docs):
     """Rename the symbol at point."""
     refactor = Rename(self.project, self.resource, offset)
     changes = refactor.get_changes(new_name,
                                    in_hierarchy=in_hierarchy,
                                    docs=docs)
     return translate_changes(changes)
Пример #3
0
class PythonRefactorRename(sublime_plugin.TextCommand):
    def run(self, edit, block=False):
        self.view.run_command("save")
        self.original_loc = self.view.rowcol(self.view.sel()[0].a)
        with ropemate.ropecontext(self.view) as context:
            self.sel = self.view.sel()[0]
            word = self.view.substr(self.view.word(self.sel.b))

            self.rename = Rename(context.project, context.resource, self.sel.b)
            self.view.window().show_input_panel("New name", word,
                                                self.new_name_entered, None,
                                                None)

    def new_name_entered(self, new_name):
        with ropemate.ropecontext(self.view) as context:
            if new_name is None or new_name == self.rename.old_name:
                return
            changes = self.rename.get_changes(new_name, in_hierarchy=True)
            self.handle = TaskHandle(name="rename_handle")
            self.handle.add_observer(self.refactoring_done)
            context.project.do(changes, task_handle=self.handle)

    def refactoring_done(self):
        percent_done = self.handle.current_jobset().get_percent_done()
        if percent_done == 100:
            self.view.run_command('revert')

            row, col = self.original_loc
            path = self.view.file_name() + ":%i:%i" % (row + 1, col + 1)
            self.view.window().open_file(path, sublime.ENCODED_POSITION)
Пример #4
0
def pyls_rename(config, workspace, document, position, new_name):
    rope_config = config.settings(document_path=document.path).get('rope', {})
    rope_project = workspace._rope_project_builder(rope_config)

    rename = Rename(rope_project,
                    libutils.path_to_resource(rope_project, document.path),
                    document.offset_at_position(position))

    log.debug("Executing rename of %s to %s",
              document.word_at_position(position), new_name)
    changeset = rename.get_changes(new_name, in_hierarchy=True, docs=True)
    log.debug("Finished rename: %s", changeset.changes)
    return {
        'documentChanges': [{
            'textDocument': {
                'uri':
                uris.uri_with(document.uri,
                              path=os.path.join(workspace.root_path,
                                                change.resource.path)),
            },
            'edits': [{
                'range': {
                    'start': {
                        'line': 0,
                        'character': 0
                    },
                    'end': {
                        'line': sys.maxsize,
                        'character': 0
                    },
                },
                'newText': change.new_contents
            }]
        } for change in changeset.changes]
    }
Пример #5
0
def rename_symbol(_, main_project, multiproj, other_projects, file_path,
                  cursor_position, replacement):
    """
    Renames symbol under cusror.
    """
    try:
        main_project.validate()
        module = libutils.path_to_resource(main_project, file_path)
        if multiproj:
            # we need to rename cross project
            crossrename = multiproject.MultiProjectRefactoring(
                Rename, other_projects)
            renamer = crossrename(main_project, module, cursor_position)
            pending_changes = renamer.get_all_changes(replacement, docs=True)
        else:
            renamer = Rename(main_project, module, cursor_position)
            pending_changes = renamer.get_changes(replacement, docs=True)
        return multiproj, pending_changes
    except RopeError as e:
        error = RefactoringError()
        error.exc = str(e)
        error.traceback = traceback.format_exc()
        error.critical = False
        return error
    except Exception as e:
        error = RefactoringError()
        error.exc = str(e)
        error.traceback = traceback.format_exc()
        error.critical = True
        return error
Пример #6
0
class PythonRefactorRename(sublime_plugin.TextCommand):

    def run(self, edit, block=False):
        self.view.run_command("save")
        self.original_loc = self.view.rowcol(self.view.sel()[0].a)
        with ropemate.ropecontext(self.view) as context:
            self.sel = self.view.sel()[0]
            word = self.view.substr(self.view.word(self.sel.b))

            self.rename = Rename(context.project, context.resource, self.sel.b)
            self.view.window().show_input_panel(
                "New name", word, self.new_name_entered, None, None)

    def new_name_entered(self, new_name):
        with ropemate.ropecontext(self.view) as context:
            if new_name is None or new_name == self.rename.old_name:
                return
            changes = self.rename.get_changes(new_name, in_hierarchy=True)
            self.handle = TaskHandle(name="rename_handle")
            self.handle.add_observer(self.refactoring_done)
            context.project.do(changes, task_handle=self.handle)

    def refactoring_done(self):
        percent_done = self.handle.current_jobset().get_percent_done()
        if percent_done == 100:
            self.view.run_command('revert')

            row, col = self.original_loc
            path = self.view.file_name() + ":%i:%i" % (row + 1, col + 1)
            self.view.window().open_file(
                path, sublime.ENCODED_POSITION)
Пример #7
0
def rename():
    with ropemate.context as context:
        if current_identifier == "":
            tooltip("Select an identifier to rename")
            return context.input
        
        offset = caret_position(context.input)
        try:
            rename = Rename(context.project, context.resource, offset)
            
            func_name = get_input(title="New name",default=rename.old_name)
            if func_name is None or func_name == rename.old_name:
                tooltip("Enter a new name!")
                return context.input
            
            changes = rename.get_changes(func_name, in_hierarchy=True)
            # remove the current file from the changeset.
            # we will apply the changes to this file manually,
            # (as the result of the TM Command) to keep TM's undo history in order
            current_file_changes = filter_changes_in_current_file(changes,context.resource)
            result = current_file_changes.new_contents
            # apply changes to all other files
            context.project.do(changes)
        except Exception, e:
            tooltip(e)
            result = context.input
        
        return result
Пример #8
0
def rename(source_string, start, end, new_name):
    if new_name == '':
        new_name = 'renamed_variable'
    project, resource = make_temporary_project_and_resource(source_string)

    renamer = Rename(project, resource, start)
    changes = renamer.get_changes(new_name)

    return get_result(changes, project, resource)
Пример #9
0
 def onRefactor(self):
     renamed = Rename(self.project, self.resource, self.startOffset)
     changes = renamed.get_changes(self._newName, task_handle=self._handle)
     for item in changes.changes:
         if isinstance(item, rope.base.change.ChangeContents):
             self.changes.append(
                 Change(item.resource.real_path, ChangeType.EDIT, get_diff(item)))
         else:
             raise Exception('Unknown Change')
Пример #10
0
 def onRefactor(self):
     renamed = Rename(self.project, self.resource, self.startOffset)
     changes = renamed.get_changes(self._newName, task_handle=self._handle)
     for item in changes.changes:
         if isinstance(item, rope.base.change.ChangeContents):
             self.changes.append(
                 Change(item.resource.real_path, ChangeType.EDIT, item.get_description()))
         else:
             raise Exception('Unknown Change')
Пример #11
0
 def refactor_rename_at_point(self, offset, new_name, in_hierarchy, docs):
     """Rename the symbol at point."""
     try:
         refactor = Rename(self.project, self.resource, offset)
     except RefactoringError as e:
         raise Fault(str(e), code=400)
     changes = refactor.get_changes(new_name, in_hierarchy=in_hierarchy,
                                    docs=docs)
     return translate_changes(changes)
Пример #12
0
def rename_all_api_modules():
    print('API modules are renaming (drop redundant "_api" suffix).')
    for api_resource in api_resources.get_folders():
        if api_resource.name.endswith('_api'):
            rename = Rename(project, api_resource)
            new_name = rename.get_old_name().split('_api')[0]

            print('\told: ' + api_resource.name + ' new: ' + new_name)

            changes = rename.get_changes(new_name)
            project.do(changes)
Пример #13
0
def main():
    from rope.base.project import Project
    from rope.base import libutils
    from rope.refactor.rename import Rename
    from rope.base.exceptions import RopeError

    path = editor.get_path()
    selection = editor.get_selection()

    if not path or not selection:
        console.hud_alert('Not a Python file', 'error')
        return

    tab.save()

    project = None
    try:
        project = Project(os.path.dirname(path), ropefolder=None)
        resource = libutils.path_to_resource(project, path)
        if not libutils.is_python_file(project, resource):
            console.hud_alert('Not a Python file', 'error')
            return

        renamer = Rename(project, resource, selection[0])
        old_name = renamer.get_old_name()

        if not old_name:
            console.hud_alert('Unable to get identifier name', 'error')
            return

        new_name = _ask_for_new_name(old_name)

        change_set = renamer.get_changes(new_name,
                                         docs=True,
                                         resources=[resource])
        if not change_set:
            console.hud_alert('No changes required')
            return

        if refactoring.ask_if_apply_change_set(change_set):
            refactoring.apply_change_set(change_set, path, selection)
            console.hud_alert('Identifier renamed')

    except RopeError as e:
        console.hud_alert(str(e), 'error')

    except KeyboardInterrupt:
        pass

    finally:
        if project:
            project.close()
Пример #14
0
 def run(self):
     self.error = None
     self.changedFiles = []
     try:
         self.ropeProject.validate()
         rename = Rename(self.ropeProject, libutils.path_to_resource(
             self.ropeProject, self.path), self.offset)
         changes = rename.get_changes(self.new_name, docs=True)
         self.ropeProject.do(changes)
         changed = changes.get_changed_resources()
         # changed is a set
         for i in changed:
             self.changedFiles.append(i.real_path)
     except Exception as err:
         self.error = str(err)
Пример #15
0
 def run(self):
     self.error = None
     self.changedFiles = []
     try:
         self.ropeProject.validate()
         rename = Rename(
             self.ropeProject,
             libutils.path_to_resource(self.ropeProject, self.path),
             self.offset)
         changes = rename.get_changes(self.new_name, docs=True)
         self.ropeProject.do(changes)
         changed = changes.get_changed_resources()
         # changed is a set
         for i in changed:
             self.changedFiles.append(i.real_path)
     except Exception as err:
         self.error = str(err)
Пример #16
0
    def rename(self, name):
        tmp0    = self.area.get('1.0', 'insert')
        offset  = len(tmp0)
        path    = self.get_root_path()
        project = Project(path)
        mod     = path_to_resource(project, self.area.filename)
        renamer = Rename(project, mod, offset)
        changes = renamer.get_changes(name)
        project.do(changes)

        self.update_instances(changes)

        print('\nRope - Renamed resource ..\n')
        print(changes.get_description())
        self.area.chmode('NORMAL')
        root.status.set_msg('Resources renamed!')
        project.close()
Пример #17
0
 def run(self):
     self.error = None
     self.changedFiles = []
     try:
         self.ropeProject.validate()
         rename = Rename(self.ropeProject, libutils.path_to_resource(
             self.ropeProject, self.path), self.offset)
         changes = rename.get_changes(self.new_name)
         self.ropeProject.do(changes)
         changed = changes.get_changed_resources()
         # changed is a set
         for i in changed:
             self.changedFiles.append(i.real_path)
     except Exception as err:
         exc_type, exc_value, exc_traceback = sys.exc_info()
         logging.error(repr(traceback.format_exception(exc_type, exc_value,
                      exc_traceback)))
                          
         self.error = str(err)
Пример #18
0
 def run(self):
     self.error = None
     self.changedFiles = []
     try:
         self.ropeProject.validate()
         rename = Rename(self.ropeProject, libutils.path_to_resource(
             self.ropeProject, self.path), self.offset)
         changes = rename.get_changes(self.new_name)
         self.ropeProject.do(changes)
         changed = changes.get_changed_resources()
         # changed is a set
         for i in changed:
             self.changedFiles.append(i.real_path)
     except Exception as err:
         exc_type, exc_value, exc_traceback = sys.exc_info()
         logging.error(repr(traceback.format_exception(exc_type, exc_value,
                      exc_traceback)))
                          
         self.error = str(err)
Пример #19
0
    def rename_attribute(project_path: str, resource_path: str,
                         offset: Optional[int],
                         new_name: str) -> RenameChanges:
        """

        Raises:
            RefactoringError
        """
        try:
            project_manager = project.Project(project_path)
            file_resource = libutils.path_to_resource(project_manager,
                                                      resource_path)

            rename_task = Rename(project_manager, file_resource, offset)
            changes = rename_task.get_changes(new_name)

            project_manager.close()
            # return RenameChanges(changes)
            return changes

        except RefactoringError as err:
            raise ValueError(err) from err
Пример #20
0
def pyls_rename(config, workspace, document, position, new_name):
    rope_config = config.settings(document_path=document.path).get('rope', {})
    rope_project = workspace._rope_project_builder(rope_config)

    rename = Rename(
        rope_project,
        libutils.path_to_resource(rope_project, document.path),
        document.offset_at_position(position)
    )

    log.debug("Executing rename of %s to %s", document.word_at_position(position), new_name)
    changeset = rename.get_changes(new_name, in_hierarchy=True, docs=True)
    log.debug("Finished rename: %s", changeset.changes)
    changes = []
    for change in changeset.changes:
        uri = uris.from_fs_path(change.resource.path)
        doc = workspace.get_maybe_document(uri)
        changes.append({
            'textDocument': {
                'uri': uri,
                'version': doc.version if doc else None
            },
            'edits': [
                {
                    'range': {
                        'start': {'line': 0, 'character': 0},
                        'end': {
                            'line': _num_lines(change.resource),
                            'character': 0,
                        },
                    },
                    'newText': change.new_contents,
                }
            ]
        })
    return {'documentChanges': changes}
Пример #21
0
from rope.base.project import Project
from rope.refactor.rename import Rename

proj_dir = "code"
project = Project(proj_dir)
module = project.pycore.find_module("colors")

# Offset of the variable 'sum'
renamer = Rename(project, module, 37)
changes = renamer.get_changes("la")
project.do(changes)

# Offset of the variable 'average'
renamer = Rename(project, module, 67)
changes = renamer.get_changes("lb")
project.do(changes)
Пример #22
0
 def rename(self, project_path, file_path, loc, source, new_name):
     project, resource = self._get_resource(project_path, file_path, source)
     rename = Rename(project, resource, loc)
     changes = rename.get_changes(new_name, in_hierarchy=True)
     project.do(changes)
Пример #23
0
 def refactor_rename_current_module(self, new_name):
     """Rename the current module."""
     refactor = Rename(self.project, self.resource, None)
     changes = refactor.get_changes(new_name)
     return translate_changes(changes)
Пример #24
0
 def refactor_rename_at_point(self, offset, new_name):
     """Rename the symbol at point."""
     refactor = Rename(self.project, self.resource, offset)
     changes = refactor.get_changes(new_name)
     return translate_changes(changes)
Пример #25
0
 def rename(self, project_path, file_path, loc, source, new_name):
     project, resource = self._get_resource(project_path, file_path, source)
     rename = Rename(project, resource, loc)
     changes = rename.get_changes(new_name, in_hierarchy=True)
     project.do(changes)
Пример #26
0
 def refactor_rename_current_module(self, new_name):
     """Rename the current module."""
     refactor = Rename(self.project, self.resource, None)
     changes = refactor.get_changes(new_name)
     return translate_changes(changes)