Personal emacs config
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

68 lines
2.2 KiB

  1. """Glue for the "black" library.
  2. """
  3. import sys
  4. from elpy.rpc import Fault
  5. # in case pkg_resources is not properly installed
  6. # (see https://github.com/jorgenschaefer/elpy/issues/1674).
  7. try:
  8. from pkg_resources import parse_version
  9. except ImportError: # pragma: no cover
  10. def parse_version(*arg, **kwargs):
  11. raise Fault("`pkg_resources` could not be imported, "
  12. "please reinstall Elpy RPC virtualenv with"
  13. " `M-x elpy-rpc-reinstall-virtualenv`", code=400)
  14. import os
  15. try:
  16. import toml
  17. except ImportError:
  18. toml = None
  19. BLACK_NOT_SUPPORTED = sys.version_info < (3, 6)
  20. try:
  21. if BLACK_NOT_SUPPORTED: # pragma: no cover
  22. black = None
  23. else:
  24. import black
  25. except ImportError: # pragma: no cover
  26. black = None
  27. def fix_code(code, directory):
  28. """Formats Python code to conform to the PEP 8 style guide.
  29. """
  30. if not black:
  31. raise Fault("black not installed", code=400)
  32. # Get black config from pyproject.toml
  33. line_length = black.DEFAULT_LINE_LENGTH
  34. string_normalization = True
  35. pyproject_path = os.path.join(directory, "pyproject.toml")
  36. if toml is not None and os.path.exists(pyproject_path):
  37. pyproject_config = toml.load(pyproject_path)
  38. black_config = pyproject_config.get("tool", {}).get("black", {})
  39. if "line-length" in black_config:
  40. line_length = black_config["line-length"]
  41. if "skip-string-normalization" in black_config:
  42. string_normalization = not black_config["skip-string-normalization"]
  43. try:
  44. if parse_version(black.__version__) < parse_version("19.0"):
  45. reformatted_source = black.format_file_contents(
  46. src_contents=code, line_length=line_length, fast=False)
  47. else:
  48. fm = black.FileMode(
  49. line_length=line_length,
  50. string_normalization=string_normalization)
  51. reformatted_source = black.format_file_contents(
  52. src_contents=code, fast=False, mode=fm)
  53. return reformatted_source
  54. except black.NothingChanged:
  55. return code
  56. except Exception as e:
  57. raise Fault("Error during formatting: {}".format(e), code=400)