示例#1
0
 def rpc_get_completions(self, project_root, filename, source, offset):
     project = self.get_project(project_root)
     resource = self.get_resource(project, filename)
     try:
         proposals = self.codeassist.code_assist(project,
                                                 source,
                                                 offset,
                                                 resource,
                                                 maxfixes=MAXFIXES)
     except self.ModuleSyntaxError as e:
         linenos = re.findall("^  \\* line ([0-9]*):", str(e), re.MULTILINE)
         linenos = [int(x) for x in linenos]
         linedesc = ", ".join(str(x) for x in sorted(set(linenos)))
         raise rpc.Fault(code=101,
                         message=("Too many syntax errors in file {0} "
                                  "(line{1} {2})".format(
                                      e.filename, "s" if
                                      ("," in linedesc) else "", linedesc)))
     except IndentationError:
         raise rpc.Fault(code=101, message="Indentation error")
     except IndexError as e:
         # Bug in Rope, see #186
         return []
     starting_offset = self.codeassist.starting_offset(source, offset)
     prefixlen = offset - starting_offset
     return [[proposal.name[prefixlen:],
              proposal.get_doc()] for proposal in proposals]
示例#2
0
 def __init__(self, project_root):
     super(RopeBackend, self).__init__()
     self.last_validation = 0
     if not os.path.exists(project_root):
         raise rpc.Fault(
             "rope does not support files without a local project root",
             code=400)
     self.project_root = project_root
     self.completions = {}
     prefs = dict(ignored_resources=[
         '*.pyc', '*~', '.ropeproject', '.hg', '.svn', '_svn', '.git'
     ],
                  python_files=['*.py'],
                  save_objectdb=False,
                  compress_objectdb=False,
                  automatic_soa=True,
                  soa_followed_calls=0,
                  perform_doa=True,
                  validate_objectdb=True,
                  max_history_items=32,
                  save_history=False,
                  compress_history=False,
                  indent_size=4,
                  extension_modules=[],
                  import_dynload_stdmods=True,
                  ignore_syntax_errors=False,
                  ignore_bad_imports=False)
     self.project = rope.base.project.Project(self.project_root,
                                              ropefolder=None,
                                              **prefs)
示例#3
0
 def call_rope(self, rope_function, filename, source, offset, **kwargs):
     self.validate()
     resource = self.get_resource(filename)
     try:
         return rope_function(self.project,
                              source,
                              offset,
                              resource,
                              maxfixes=MAXFIXES,
                              **kwargs)
     except (RopeError, IndentationError, LookupError, AttributeError):
         return None
     except Exception as e:
         data = {
             "traceback": traceback.format_exc(),
             "rope_debug_info": {
                 "project_root":
                 self.project_root,
                 "filename":
                 filename,
                 "source":
                 source,
                 "function_name":
                 (rope_function.__module__ + "." + rope_function.__name__),
                 "function_args":
                 ", ".join([
                     "project", "source",
                     str(offset), "resource", "maxfixes={0}".format(
                         MAXFIXES)
                 ] + [u"{}={}".format(k, v) for (k, v) in kwargs.items()])
             }
         }
         raise rpc.Fault(code=500, message=str(e), data=data)
示例#4
0
def run_with_debug(jedi, name, *args, **kwargs):
    re_raise = kwargs.pop('re_raise', ())
    try:
        script = jedi.Script(*args, **kwargs)
        return getattr(script, name)()
    except Exception as e:
        if isinstance(e, re_raise):
            raise
        # Bug jedi#485
        if (
                isinstance(e, ValueError) and
                "invalid \\x escape" in str(e)
        ):
            return None
        # Bug jedi#485 in Python 3
        if (
                isinstance(e, SyntaxError) and
                "truncated \\xXX escape" in str(e)
        ):
            return None

        from jedi import debug

        debug_info = []

        def _debug(level, str_out):
            if level == debug.NOTICE:
                prefix = "[N]"
            elif level == debug.WARNING:
                prefix = "[W]"
            else:
                prefix = "[?]"
            debug_info.append(u"{0} {1}".format(prefix, str_out))

        jedi.set_debug_function(_debug, speed=False)
        try:
            script = jedi.Script(*args, **kwargs)
            return getattr(script, name)()
        except Exception as e:
            source = kwargs.get('source')
            sc_args = []
            sc_args.extend(repr(arg) for arg in args)
            sc_args.extend("{0}={1}".format(k, "source" if k == "source"
                                            else repr(v))
                           for (k, v) in kwargs.items())

            data = {
                "traceback": traceback.format_exc(),
                "jedi_debug_info": {'script_args': ", ".join(sc_args),
                                    'source': source,
                                    'method': name,
                                    'debug_info': debug_info}
            }
            raise rpc.Fault(message=str(e),
                            code=500,
                            data=data)
        finally:
            jedi.set_debug_function(None)
示例#5
0
文件: test_rpc.py 项目: offbyone/elpy
 def test_should_have_defaults_for_code_and_data(self):
     fault = rpc.Fault("Hello")
     self.assertEqual(str(fault), "Hello")
     self.assertEqual(fault.code, 500)
     self.assertIsNone(fault.data)
示例#6
0
文件: test_rpc.py 项目: offbyone/elpy
 def test_should_have_code_and_data(self):
     fault = rpc.Fault("Hello", code=250, data="Fnord")
     self.assertEqual(str(fault), "Hello")
     self.assertEqual(fault.code, 250)
     self.assertEqual(fault.data, "Fnord")
示例#7
0
def run_with_debug(jedi, name, *args, **kwargs):
    re_raise = kwargs.pop('re_raise', ())
    # Remove form feed characters, they confuse Jedi (jedi#424)
    if 'source' in kwargs:
        kwargs['source'] = kwargs['source'].replace("\f", " ")
    try:
        script = jedi.Script(*args, **kwargs)
        return getattr(script, name)()
    except Exception as e:
        if isinstance(e, re_raise):
            raise
        # Bug jedi#417
        if isinstance(e, TypeError) and str(e) == 'no dicts allowed':
            return None
        # Bug jedi#427
        if isinstance(e, UnicodeDecodeError):
            return None
        # Bug jedi#429
        if isinstance(e, IndexError):
            return None
        # Bug jedi#431
        if isinstance(e, AttributeError) and str(e).endswith("'end_pos'"):
            return None
        # Bug in Python 2.6, see #275
        if isinstance(e, OSError) and e.errno == 13:
            return None
        # Bug jedi#466
        if (isinstance(e, SyntaxError)
                and "EOL while scanning string literal" in str(e)):
            return None
        # Bug jedi#482
        if isinstance(e, UnicodeEncodeError):
            return None
        # Bug jedi#485
        if (isinstance(e, ValueError) and "invalid \\x escape" in str(e)):
            return None
        # Bug jedi#485 in Python 3
        if (isinstance(e, SyntaxError) and "truncated \\xXX escape" in str(e)):
            return None
        # Bug jedi#465
        if (isinstance(e, SyntaxError)
                and "encoding declaration in Unicode string" in str(e)):
            return None
        # Bug #337 / jedi#471
        if (isinstance(e, ImportError) and "No module named" in str(e)):
            return None
        # Bug #365 / jedi#486 - fixed in Jedi 0.8.2
        if (isinstance(e, UnboundLocalError)
                and "local variable 'path' referenced before assignment"
                in str(e)):
            return None
        # Bug #366 / jedi#491
        if (isinstance(e, ValueError) and "__loader__ is None" in str(e)):
            return None
        # Bug #353
        if (isinstance(e, OSError) and "No such file or directory" in str(e)):
            return None
        # Bug #561, #564, #570, #588, #593, #599 / jedi#572, jedi#579, jedi#590
        if isinstance(e, KeyError):
            return None
        # Bug #519 / jedi#610
        if (isinstance(e, RuntimeError)
                and "maximum recursion depth exceeded" in str(e)):
            return None
        # Bug #563 / jedi#589
        if (isinstance(e, AttributeError) and "MergedNamesDict" in str(e)):
            return None
        # Bug #615 / jedi#592
        if (isinstance(e, AttributeError) and "ListComprehension" in str(e)):
            return None
        # Bug #569 / jedi#593
        if (isinstance(e, AttributeError) and "names_dict" in str(e)):
            return None

        from jedi import debug

        debug_info = []

        def _debug(level, str_out):
            if level == debug.NOTICE:
                prefix = "[N]"
            elif level == debug.WARNING:
                prefix = "[W]"
            else:
                prefix = "[?]"
            debug_info.append(u"{0} {1}".format(prefix, str_out))

        jedi.set_debug_function(_debug, speed=False)
        try:
            script = jedi.Script(*args, **kwargs)
            return getattr(script, name)()
        except Exception as e:
            source = kwargs.get('source')
            sc_args = []
            sc_args.extend(repr(arg) for arg in args)
            sc_args.extend(
                "{0}={1}".format(k, "source" if k == "source" else repr(v))
                for (k, v) in kwargs.items())

            data = {
                "traceback": traceback.format_exc(),
                "jedi_debug_info": {
                    'script_args': ", ".join(sc_args),
                    'source': source,
                    'method': name,
                    'debug_info': debug_info
                }
            }
            raise rpc.Fault(message=str(e), code=500, data=data)
        finally:
            jedi.set_debug_function(None)
示例#8
0
    def rpc_get_usages(self, project_root, filename, source, offset):
        """Get usages for the symbol at point.

        """
        raise rpc.Fault("get_usages not implemented by current backend")
示例#9
0
 def test_method():
     raise rpc.Fault("St. Andreas' Fault", code=12345, data="Yippieh")
示例#10
0
 def test_method():
     raise rpc.Fault("This is a fault")
示例#11
0
def run_with_debug(jedi, name, *args, **kwargs):
    re_raise = kwargs.pop('re_raise', ())
    # Remove form feed characters, they confuse Jedi (jedi#424)
    if 'source' in kwargs:
        kwargs['source'] = kwargs['source'].replace("\f", " ")
    try:
        script = jedi.Script(*args, **kwargs)
        return getattr(script, name)()
    except Exception as e:
        if isinstance(e, re_raise):
            raise
        # Bug jedi#417
        if isinstance(e, TypeError) and str(e) == 'no dicts allowed':
            return None
        # Bug jedi#427
        if isinstance(e, UnicodeDecodeError):
            return None
        # Bug jedi#429
        if isinstance(e, IndexError):
            return None
        # Bug jedi#431
        if isinstance(e, AttributeError) and str(e).endswith("'end_pos'"):
            return None
        # Bug in Python 2.6, see #275
        if isinstance(e, OSError) and e.errno == 13:
            return None

        from jedi import debug

        debug_info = []

        def _debug(level, str_out):
            if level == debug.NOTICE:
                prefix = "[N]"
            elif level == debug.WARNING:
                prefix = "[W]"
            else:
                prefix = "[?]"
            debug_info.append("{0} {1}".format(prefix, str_out))

        jedi.set_debug_function(_debug, speed=False)
        try:
            script = jedi.Script(*args, **kwargs)
            return getattr(script, name)()
        except Exception as e:
            source = kwargs.get('source')
            sc_args = []
            sc_args.extend(repr(arg) for arg in args)
            sc_args.extend(
                "{0}={1}".format(k, "source" if k == "source" else repr(v))
                for (k, v) in kwargs.items())

            data = {
                "traceback": traceback.format_exc(),
                "jedi_debug_info": {
                    'script_args': ", ".join(sc_args),
                    'source': source,
                    'method': name,
                    'debug_info': debug_info
                }
            }
            raise rpc.Fault(message=str(e), code=500, data=data)
        finally:
            jedi.set_debug_function(None)