Example #1
0
 def _ensure_import_magic(self):  # pragma: no cover
     if not self.import_magic.is_enabled:
         raise Fault(
             "fixup_imports not enabled; install importmagic module",
             code=400)
     if not self.import_magic.symbol_index:
         raise Fault(self.import_magic.fail_message, code=200)  # XXX code?
Example #2
0
def fix_code(code, directory):
    """Formats Python code to conform to the PEP 8 style guide.

    """
    if not black:
        raise Fault("black not installed", code=400)
    # Get black config from pyproject.toml
    line_length = black.DEFAULT_LINE_LENGTH
    string_normalization = True
    parser = configparser.ConfigParser()
    pyproject_path = os.path.join(directory, "pyproject.toml")
    if parser.read(pyproject_path):
        if parser.has_option("tool.black", "line-length"):
            line_length = parser.getint("tool.black", "line-length")
        if parser.has_option("tool.black", "skip-string-normalization"):
            string_normalization = not parser.getboolean(
                "tool.black", "skip-string-normalization"
            )
    try:
        if parse_version(black.__version__) < parse_version("19.0"):
            reformatted_source = black.format_file_contents(
                src_contents=code, line_length=line_length, fast=False
            )
        else:
            fm = black.FileMode(
                line_length=line_length, string_normalization=string_normalization
            )
            reformatted_source = black.format_file_contents(
                src_contents=code, fast=False, mode=fm
            )
        return reformatted_source
    except black.NothingChanged:
        return code
    except Exception as e:
        raise Fault("Error during formatting: {}".format(e), code=400)
Example #3
0
def fix_code(code, directory):
    """Formats Python code to conform to the PEP 8 style guide.

    """
    if not black:
        raise Fault("black not installed", code=400)
    # Get black config from pyproject.toml
    line_length = black.DEFAULT_LINE_LENGTH
    string_normalization = True
    if find_pyproject_toml:
        pyproject_path = find_pyproject_toml((directory, ))
    else:
        pyproject_path = os.path.join(directory, "pyproject.toml")
    if toml and pyproject_path and os.path.exists(pyproject_path):
        pyproject_config = toml.load(pyproject_path)
        black_config = pyproject_config.get("tool", {}).get("black", {})
        if "line-length" in black_config:
            line_length = black_config["line-length"]
        if "skip-string-normalization" in black_config:
            string_normalization = not black_config["skip-string-normalization"]
    try:
        if parse_version(black.__version__) < parse_version("19.0"):
            reformatted_source = black.format_file_contents(
                src_contents=code, line_length=line_length, fast=False)
        else:
            fm = black.FileMode(line_length=line_length,
                                string_normalization=string_normalization)
            reformatted_source = black.format_file_contents(src_contents=code,
                                                            fast=False,
                                                            mode=fm)
        return reformatted_source
    except black.NothingChanged:
        return code
    except Exception as e:
        raise Fault("Error during formatting: {}".format(e), code=400)
Example #4
0
 def __init__(self, project_root, filename):
     self.project_root = project_root
     if not ROPE_AVAILABLE:
         raise Fault('rope not installed, cannot refactor code.', code=400)
     if not os.path.exists(project_root):
         raise Fault("cannot do refactoring without a local project root",
                     code=400)
     self.project = Project(project_root, ropefolder=None)
     self.resource = path_to_resource(self.project, filename)
Example #5
0
def fix_code(code, directory):
    """Formats Python code to conform to the PEP 8 style guide.

    """
    if not black:
        raise Fault('black not installed', code=400)

    try:
        reformatted_source = black.format_file_contents(
            src_contents=code,
            line_length=black.DEFAULT_LINE_LENGTH,
            fast=False)
        return reformatted_source
    except Exception as e:
        raise Fault("Error during formatting: {}".format(e), code=400)
Example #6
0
def fix_code(code):
    """Formats Python code to conform to the PEP 8 style guide.

    """
    if not autopep8:
        raise Fault('autopep8 not installed, cannot fix code.', code=400)
    return autopep8.fix_code(code)
Example #7
0
 def _get_changes(self, refactor, *args, **kwargs):
     try:
         changes = refactor.get_changes(*args, **kwargs)
     except Exception as e:
         raise Fault("Error during refactoring: {}".format(e),
                     code=400)
     return translate_changes(changes)
Example #8
0
def fix_code(code):
    """Formats Python code to conform to the PEP 8 style guide.

    """
    if not yapf_api:
        raise Fault('yapf not installed', code=400)
    style_config = file_resources.GetDefaultStyleForDir(os.getcwd())
    try:
        reformatted_source, _ = yapf_api.FormatCode(code,
                                                    filename='<stdin>',
                                                    style_config=style_config,
                                                    verify=False)
        return reformatted_source
    except Exception as e:
            raise Fault("Error during formatting: {}".format(e),
                        code=400)
Example #9
0
 def refactor_use_function(self, offset):
     """Use the function at point wherever possible."""
     try:
         refactor = UseFunction(self.project, self.resource, offset)
     except RefactoringError as e:
         raise Fault('Refactoring error: {}'.format(e), code=400)
     return self._get_changes(refactor)
Example #10
0
    def handle(self, method_name, args):
        """Call the RPC method method_name with the specified args.

        """
        method = getattr(self.backend, "rpc_" + method_name, None)
        if method is None:
            raise Fault("Unknown method {0}".format(method_name))
        return method(*args)
Example #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)
     return self._get_changes(refactor, new_name,
                              in_hierarchy=in_hierarchy, docs=docs)
Example #12
0
    def rpc_get_import_symbols(self, filename, source, symbol):
        """Return a list of modules from which the given symbol can be imported.

        """
        self._ensure_import_magic()
        try:
            return self.import_magic.get_import_symbols(symbol)
        except ImportMagicError as err:
            raise Fault(str(err), code=200)
Example #13
0
    def rpc_get_unresolved_symbols(self, filename, source):
        """Return a list of unreferenced symbols in the module.

        """
        self._ensure_import_magic()
        source = get_source(source)
        try:
            return self.import_magic.get_unresolved_symbols(source)
        except ImportMagicError as err:
            raise Fault(str(err), code=200)
Example #14
0
    def rpc_add_import(self, filename, source, statement):
        """Add an import statement to the module.

        """
        self._ensure_import_magic()
        source = get_source(source)
        try:
            return self.import_magic.add_import(source, statement)
        except ImportMagicError as err:
            raise Fault(str(err), code=200)
Example #15
0
    def rpc_remove_unreferenced_imports(self, filename, source):
        """Remove unused import statements.

        """
        self._ensure_import_magic()
        source = get_source(source)
        try:
            return self.import_magic.remove_unreferenced_imports(source)
        except ImportMagicError as err:
            raise Fault(str(err), code=200)
Example #16
0
    def rpc_get_names(self, filename, source, offset):
        """Get all possible names

        """
        source = get_source(source)
        if hasattr(self.backend, "rpc_get_names"):
            return self.backend.rpc_get_names(filename, source, offset)
        else:
            raise Fault("get_names not implemented by current backend",
                        code=400)
Example #17
0
    def rpc_get_usages(self, filename, source, offset):
        """Get usages for the symbol at point.

        """
        source = get_source(source)
        if hasattr(self.backend, "rpc_get_usages"):
            return self.backend.rpc_get_usages(filename, source, offset)
        else:
            raise Fault("get_usages not implemented by current backend",
                        code=400)
Example #18
0
def fix_code(code, directory):
    """Formats Python code to conform to the PEP 8 style guide.

    """
    if not autopep8:
        raise Fault('autopep8 not installed, cannot fix code.', code=400)
    old_dir = os.getcwd()
    try:
        os.chdir(directory)
        return autopep8.fix_code(code, apply_config=True)
    finally:
        os.chdir(old_dir)
Example #19
0
def fix_code(code, directory):
    """Formats Python code to conform to the PEP 8 style guide.

    """
    if not black:
        raise Fault("black not installed", code=400)

    try:
        if parse_version(black.__version__) < parse_version("19.0"):
            reformatted_source = black.format_file_contents(
                src_contents=code,
                line_length=black.DEFAULT_LINE_LENGTH,
                fast=False)
        else:
            fm = black.FileMode()
            reformatted_source = black.format_file_contents(src_contents=code,
                                                            fast=False,
                                                            mode=fm)
        return reformatted_source
    except black.NothingChanged:
        return code
    except Exception as e:
        raise Fault("Error during formatting: {}".format(e), code=400)
Example #20
0
 def rpc_get_assignment(self, filename, source, offset):
     raise Fault("Obsolete since jedi 17.0. Please use 'get_definition'.")
Example #21
0
 def parse_version(*arg, **kwargs):
     raise Fault(
         "`pkg_resources` could not be imported, "
         "please reinstall Elpy RPC virtualenv with"
         " `M-x elpy-rpc-reinstall-virtualenv`",
         code=400)