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)
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
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
def rename(self): """ Renames word under cursor. """ editor = api.editor.get_current_editor() if editor is None: return editor.file.save() assert isinstance(editor, PyCodeEdit) module = libutils.path_to_resource(self._main_project, editor.file.path) self._main_project.validate() cursor_position = self._get_real_position( editor.textCursor().position()) try: renamer = Rename(self._main_project, module, cursor_position) except RopeError: return if not renamer.get_old_name(): return preview, replacement = DlgRope.rename(self.main_window, renamer.get_old_name()) if preview is None and replacement is None: return multiproj = self._has_multiple_projects() other_projects = self._get_other_projects() main_project = self._main_project self._preview = preview api.tasks.start(_('Refactoring: rename'), rename_symbol, self._on_changes_available, args=(main_project, multiproj, other_projects, editor.file.path, cursor_position, replacement), cancellable=True, use_thread=True)
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] }
def rename(self): """ Renames word under cursor. """ editor = api.editor.get_current_editor() if editor is None: return editor.file.save() assert isinstance(editor, PyCodeEdit) module = libutils.path_to_resource( self._main_project, editor.file.path) self._main_project.validate() cursor_position = self._get_real_position( editor.textCursor().position()) try: renamer = Rename(self._main_project, module, cursor_position) except RopeError: return if not renamer.get_old_name(): return preview, replacement = DlgRope.rename( self.main_window, renamer.get_old_name()) if preview is None and replacement is None: return multiproj = self._has_multiple_projects() other_projects = self._get_other_projects() main_project = self._main_project self._preview = preview api.tasks.start(_('Refactoring: rename'), rename_symbol, self._on_changes_available, args=( main_project, multiproj, other_projects, editor.file.path, cursor_position, replacement), cancellable=True, use_thread=True)
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')
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)
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)
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')
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 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)
def rename_module(project, old_module, new_module): try: tempdir = tempfile.mkdtemp() os.makedirs(os.path.join(tempdir, old_module)) open(os.path.join(tempdir, old_module, '__init__.py'), 'a').close() sys.path.append(tempdir) resource = project.find_module(old_module) changes = Rename(project, resource).get_changes(new_module) changes.do() finally: shutil.rmtree(tempdir, ignore_errors=True)
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()
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)
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)
def _local_rename(self, source_code, offset, new_name): testmod = testutils.create_module(self.project, 'testmod') testmod.write(source_code) changes = Rename(self.project, testmod, offset).\ get_changes(new_name, resources=[testmod]) self.project.do(changes) return testmod.read()
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)
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)
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) return self._get_changes(refactor, new_name, in_hierarchy=in_hierarchy, docs=docs)
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()
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)
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
def setFileToRename_destinationName(self, wantedResultName: str): self.destinationName = wantedResultName try: self.change = Rename( self.proj, self.fileToRename ).get_changes(wantedResultName) # )._rename_module(wantedResultName) except FileNotFoundError as err: print("\n+++There is no file in given name or path to change its name or path.\n") print(err) except Exception as err: print("\n+++Error while searching file which you wanted to be renamed.\n") print(err)
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}
def _rename_package(project: Project, old_name: str, new_name: str) -> None: """ Rename a Python package, refactoring relevant imports along the way, as well as references in comments. Args: project: rope.base.Project holding the scope of the refactoring. old_name: Old module name. Can be a fully qualified module path, e.g. "package.pipelines.pipeline" or "package/pipelines/pipeline", relative to the `project` root. new_name: New module name. Can't be a fully qualified module path. """ folder = project.get_folder(old_name) change = Rename(project, folder).get_changes(new_name, docs=True) project.do(change)
def get_renaming_changes(project, module, offset, new_name, name, source_file_name, docs=True): """Get the changes for doing a rename refactoring. If Rope raises a `RefactoringError` it prints a warning and returns `None`.""" try: changes = Rename(project, module, offset).get_changes(new_name, docs=docs, unsure=None) return changes except rope.base.exceptions.RefactoringError: print("Error in calculating a rename from '{0}' to '{1}' in file" "\n {2}".format(name, new_name, source_file_name)) return None
def get_changes(self): name = worder.get_name_at(self.resource, self.offset) this_pymodule = self.project.get_pymodule(self.resource) pyname = evaluate.eval_location(this_pymodule, self.offset) if not self._is_a_method_local(pyname): raise exceptions.RefactoringError( 'Convert local variable to field should be performed on \n' 'a local variable of a method.') pymodule, lineno = pyname.get_definition_location() function_scope = pymodule.get_scope().get_inner_scope_for_line(lineno) # Not checking redefinition #self._check_redefinition(name, function_scope) new_name = self._get_field_name(function_scope.pyobject, name) changes = Rename(self.project, self.resource, self.offset).\ get_changes(new_name, resources=[self.resource]) return changes
def get_renaming_changes(project, module, offset, new_name, name, source_file_name, docs=True): """Get the changes for doing a rename refactoring. Returns a tuple of the changes and any error that was raised. If Rope raises certain errors such as `RefactoringError` it prints a warning and returns `None, e` where `e` is the error.""" err_message = "Rope {} in calculating a rename from '{}' to '{}' in file\n {}\n" e = None try: changes = Rename(project, module, offset).get_changes(new_name, docs=docs, unsure=None) return changes, e except rope.base.exceptions.RefactoringError as error: print_warning( err_message.format("RefactoringError", name, new_name, source_file_name)) except AttributeError as e: print_warning( err_message.format("AttributeError", name, new_name, source_file_name)) except SyntaxError as e: print_warning( err_message.format("SyntaxError", name, new_name, source_file_name)) except: print_warning( "Unexpected error in calculating a rename from '{}' to '{}' in file" "\n {}".format(name, new_name, source_file_name)) raise return None, e
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)
from rope.base import project from rope.refactor.move import MoveModule from rope.refactor.rename import Rename my_project = project.Project('.') providers_dest = my_project.get_folder('cfme/providers') if not providers_dest.exists(): providers_dest.create() if not providers_dest.get_children(): providers_dest.create_file('__init__.py') folders_to_process = ['infrastructure', 'cloud', 'middleware', 'containers'] for folder in folders_to_process: def find(fmt): return my_project.find_module(fmt.format(folder=folder)) print(folder) print(" append name") res = find('cfme.{folder}.provider') Rename(my_project, res).get_changes('provider_' + folder).do() print(" move") res = find('cfme.{folder}.provider_{folder}') MoveModule(my_project, res).get_changes(providers_dest).do() print(" fix_name") res = find('cfme.providers.provider_{folder}') Rename(my_project, res).get_changes(folder).do()
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)
def _rename(self, resource, offset, new_name, **kwds): changes = Rename(self.project, resource, offset).\ get_changes(new_name, **kwds) self.project.do(changes)
from rope.base.project import Project from rope.refactor.rename import Rename proj = Project('src') # resource = myProj.get_resource(r'app/src/app/services/gridMaker') moduleToChange = proj.get_module(r'app/services/theGrid/gridLinesCoordsStore').get_resource() change = Rename(proj, moduleToChange).get_changes('gridInfoStore') print(change.get_description()) proj.do(change)
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)
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)
from rope.base.project import Project from rope.refactor.rename import Rename proj = Project('../lib/ansible') context = proj.get_file('context.py') change = Rename(proj, context).get_changes('new_context') proj.do(change)
from rope.base.project import Project from rope.refactor.rename import Rename from rope.contrib import generate project = Project('.') pycore = project.pycore package = pycore.find_module('sindice') changes = Rename(project, package).get_changes('core') project.do(changes)
def create_refactoring_operation(self, project, resource, start, end): return Rename(project, resource, start)