RefactoringRope/RefactoringClient.py

Fri, 15 Sep 2017 19:50:07 +0200

author
Detlev Offenbach <detlev@die-offenbachs.de>
date
Fri, 15 Sep 2017 19:50:07 +0200
branch
server_client_variant
changeset 165
ea41742015af
parent 164
121d426d4ed7
child 166
6fc202183b3b
permissions
-rw-r--r--

Implemented the "Query References" function.

# -*- coding: utf-8 -*-

# Copyright (c) 2017 Detlev Offenbach <detlev@die-offenbachs.de>
#

"""
Module implementing the refactoring client interface to rope.
"""

from __future__ import unicode_literals

import sys
import os

sys.path.insert(0, os.path.dirname(__file__))
if sys.version_info[0] >= 3:
    path = os.path.join(os.path.dirname(__file__), 'rope_py3')
else:
    path = os.path.join(os.path.dirname(__file__), 'rope_py2')
    str = unicode   # __IGNORE_WARNING__
sys.path.insert(0, path)

import rope.base.project
import rope.base.libutils

from JsonClient import JsonClient


class RefactoringClient(JsonClient):
    """
    Class implementing the refactoring client interface to rope.
    """
    def __init__(self, host, port, projectPath):
        """
        Constructor
        
        @param host ip address the background service is listening
        @type str
        @param port port of the background service
        @type int
        @param projectPath path to the project
        @type str
        """
        super(RefactoringClient, self).__init__(host, port)
        
        from FileSystemCommands import RefactoringClientFileSystemCommands
        self.__fsCommands = RefactoringClientFileSystemCommands(self)
        
        self.__projectpath = projectPath
        self.__project = rope.base.project.Project(
            self.__projectpath, fscommands=self.__fsCommands)
        
        self.__progressHandle = None
    
    def handleCall(self, method, params):
        """
        Public method to handle a method call from the server.
        
        @param method requested method name
        @type str
        @param params dictionary with method specific parameters
        @type dict
        """
##        if "filename" in params and sys.version_info[0] == 2:
##            params["filename"] = params["filename"].encode(
##                sys.getfilesystemencoding())
        
        if method == "AbortAction":
            if self.__progressHandle is not None and \
               not self.__progressHandle.is_stopped():
                self.__progressHandle.stop()
        
        elif method == "Validate":
            self.__project.validate(self.__project.root)
        
        elif method == "QueryReferences":
            self.__queryReferences(params)
        
        elif method == "ping":
            self.sendJson("pong", {})
    
    def __handleRopeError(self, err):
        """
        Private method to process a rope error.
        
        @param err rope exception object
        @type Exception
        @return dictionary containing the error information
        @rtype dict
        """
        ropeError = str(type(err)).split()[-1]
        ropeError = ropeError[1:-2].split('.')[-1]
        errorDict = {
            "Error": ropeError,
            "ErrorString": str(err),
        }
        if ropeError == 'ModuleSyntaxError':
            errorDict["ErrorFile"] = err.filename
            errorDict["ErrorLine"] = err.lineno
        
        return errorDict
    
    def __queryReferences(self, params):
        """
        Private method to handle the Find References action.
        
        @param params dictionary containing the method parameters sent by
            the server
        @type dict
        """
        title = params["Title"]
        filename = params["FileName"]
        offset = params["Offset"]
        
        errorDict = {}
        occurrences = []
        
        import rope.contrib.findit
        from ProgressHandle import ProgressHandle
        resource = rope.base.libutils.path_to_resource(
            self.__project, filename)
        handle = ProgressHandle(self, title, True)
        try:
            occurrences = rope.contrib.findit.find_occurrences(
                self.__project, resource, offset,
                unsure=True, in_hierarchy=True, task_handle=handle)
        except Exception as err:
            errorDict = self.__handleRopeError(err)
        handle.reset()
        
        result = {
            "Title": title,
            "EntriesCount": len(occurrences),
            "Entries": [
                [occurrence.resource.real_path, occurrence.lineno,
                 occurrence.unsure] for occurrence in occurrences
            ],
        }
        result.update(errorDict)
        
        self.sendJson("QueryReferencesResult", result)

if __name__ == '__main__':
    if len(sys.argv) != 4:
        print('Host, port and project path parameters are missing. Abort.')
        sys.exit(1)
    
    host, port, projectPath = sys.argv[1:]
    client = RefactoringClient(host, int(port), projectPath)
    # Start the main loop
    client.run()

#
# eflag: noqa = M801

eric ide

mercurial