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.

69 lines
2.2 KiB

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